keras custom loss with for loop raises exception only when run_eagerly is False

  Kiến thức lập trình

I wrote a simple custom loss function in keras (below here) which uses a for loop .
This function is very stupid, I could avoid the for loop but I wrote it as exercise for me.
I get an exception unless I use model.run_eagerly=True.
I don’t understand why I get the exception and why I get it only when model.run_eagerly is False.

Here is my source code.

from keras.models import Sequential
from keras.layers import Dense
import numpy as np
from sklearn.model_selection import train_test_split
import keras


def my_custom_loss(y_true, y_pred):
    t=0
    for i in range (y_true.shape[0]):
        t+=y_pred[i]

    return t


X=np.random.rand(100,10)
Y=np.random.rand(100)
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.4, random_state=42)
keras.utils.set_random_seed(1)

model = Sequential()
model.add(Dense(1, activation= 'sigmoid' ))
model.compile(loss= my_custom_loss)
# model.run_eagerly=True  # <-- if I uncomment this line, then it works

model.fit(X_train, y_train, epochs=2000,batch_size=15,verbose=1,validation_data=(X_test,y_test))

I get the exception ‘NoneType’ object cannot be interpreted as an integer’ in the following line of the autogenerated source py file.
ag__.for_stmt(ag__.converted_call(ag__.ld(range), (ag__.ld(y_true).shape[0],), None, fscope), None, loop_body, get_state, set_state, (‘t’,), {‘iterate_names’: ‘i’})

Thanks
Asi

New contributor

Asi Dimbez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT