自定义损失函数问题:在图形执行中不允许将tf.Tensor作为Python bool使用

时间:2020-06-21 14:35:37

标签: keras tensorflow2.0 loss-function

我正在尝试通过以下公式实现自定义损失:

enter image description here 这是对模型使用真实的自定义损失函数的第一步。数据集是Keras Cifar10。实现似乎是正确的,但出现此错误:

OperatorNotAllowedInGraphError: using a tf.Tensor as a Python bool is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.

def custom_loss(y_true, y_pred):

  #  −(?log(?)+(1−?)log(1−?))

  return tf.sqrt(tf.divide(tf.reduce_sum(tf.pow(tf.subtract(y_true, y_pred),2.0)),tf.cast(tf.size(y_true), tf.float32)))

我什至尝试过转换train_labels(unit8到float32),但这没有帮助。 任何帮助将不胜感激。

我的模型是一个简单的5层CNN模型:

model = keras.models.Sequential([keras.layers.Conv2D(filters= 3,kernel_size=(3,3),activation= keras.activations.relu, input_shape= (32,32,3)),
                                 keras.layers.MaxPool2D(pool_size= (2,2)),
                                 keras.layers.Conv2D(filters= 3,kernel_size=(3,3),activation= keras.activations.relu),
                                 keras.layers.MaxPool2D(pool_size= (2,2)),
                                 keras.layers.Flatten(),
                                 keras.layers.Dense(units= 64, activation= keras.activations.relu),
                                 keras.layers.Dense(units= 10, activation= keras.activations.softmax)])

model.compile(loss= classification_loss(train_labels,model.layers[-1].output),optimizer= keras.optimizers.Adam(), metrics=['accuracy'])
model.fit(x= train_images, y= train_labels,epochs=10)

1 个答案:

答案 0 :(得分:0)

您使用的公式是ROOT MSE(RMSE)

def RMSE(y_true, y_pred):
    
    return tf.sqrt(tf.reduce_mean(tf.square(y_true-y_pred)))

这是一个可行的示例...

def RMSE(y_true, y_pred):
    
    return tf.sqrt(tf.reduce_mean(tf.square(y_true-y_pred)))

X = np.random.uniform(0,1, (1000,10))
y = np.random.uniform(0,1, 1000)

inp = Input((10,))
x1 = Dense(32, activation='relu')(inp)
x2 = Dense(16, activation='relu')(x1)
out = Dense(1)(x2)

m = Model(inp, out)
m.compile('adam', RMSE)
m.fit(X,y, epochs=5)