1

I'm trying to convert the input tensor to a numpy array inside a custom keras loss function, after following the instructions here.

The above code runs on my machine with no errors. Now, I want to extract a numpy array with values from the input tensor. However, I get the following error:

"tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input_1' with dtype float
[[Node: input_1 = Placeholderdtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]]"

I need to convert to a numpy array because I have other keras models that must operate on the input - I haven't shown those lines below in joint_loss, but even the code sample below doesn't run at all.

import numpy as np
from keras.models import Model, Sequential
from keras.layers import Dense, Activation, Input
import keras.backend as K

def joint_loss_wrapper(x):
    def joint_loss(y_true, y_pred):
        x_val = K.eval(x)
        return y_true - y_pred
    return joint_loss


input_tensor = Input(shape=(6,))
hidden1 = Dense(30, activation='relu')(input_tensor)
hidden2 = Dense(40, activation='sigmoid')(hidden1)
out = Dense(1, activation='sigmoid')(hidden2)
model = Model(input_tensor, out)
model.compile(loss=joint_loss_wrapper(input_tensor), optimizer='adam')
sdcbr
  • 7,021
  • 3
  • 27
  • 44
Ameya
  • 326
  • 3
  • 9
  • 1
    You cannot eval the input tensor, you need to do all these operations in a symbolic way, without eval. – Dr. Snoopy Jan 27 '19 at 16:17
  • How would I feed the input tensor x to the other models? `y_pred = submodel.predict(x)` won't work because x is a tensor. – Ameya Jan 28 '19 at 17:06

1 Answers1

1

I figured it out! What you want to do is use the Functional API for Keras.
Then your submodels outputs as tensors can be obtained as y_pred_submodel = submodel(x).
This is similar to how a Keras layer operates on a tensor.
Manipulate only tensors within the loss function. That should work fine.

Ameya
  • 326
  • 3
  • 9