Matt
Matt

Reputation: 21

keras loss function(from keras input)

I reference the link: Keras custom loss function: Accessing current input pattern.

But I get error: " TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, you may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model. "

This is the source code: What happened ?

def custom_loss_wrapper(input_tensor):
    def custom_loss(y_true, y_pred):
        return K.binary_crossentropy(y_true, y_pred) + K.mean(input_tensor)
    return custom_loss

input_tensor = Input(shape=(10,))
hidden = Dense(100, activation='relu')(input_tensor)
out = Dense(1, activation='sigmoid')(hidden)
model = Model(input_tensor, out)
model.compile(loss=custom_loss_wrapper(input_tensor), optimizer='adam')

X = np.random.rand(1000, 10)
y = np.random.rand(1000, 1)
model.train_on_batch(X, y)  

Upvotes: 2

Views: 1617

Answers (2)

Abhishek V
Abhishek V

Reputation: 87

When I received a similar error, I performed the following:

del model

Before:

model = Model(input_tensor, out)

It resolved my issue, you can give it a shot. I am eager to know if it solves your problem :) .

Upvotes: -1

J B
J B

Reputation: 440

In the tf 2.0, eager mode is on by default. It's not possible to get this functionality in eager mode as the above example is currently written. I think there are ways to do it in eager mode with some more advanced programming. But otherwise it's a simple matter to turn eager mode off and run in graph mode with:

from tensorflow.python.framework.ops import disable_eager_execution
disable_eager_execution()

Upvotes: 3

Related Questions