【问题标题】:Custom loss function problem: using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution自定义损失函数问题:Graph 执行中不允许使用 `tf.Tensor` 作为 Python `bool`
【发布时间】:2020-10-11 11:06:12
【问题描述】:

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

这是为我的模型使用真正的自定义损失函数的第一步。数据集是 Keras Cifar10。实现似乎正确,但我收到此错误:

OperatorNotAllowedInGraphError: using a tf.Tensoras a Pythonbool 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)

【问题讨论】:

  • 您在寻找经典的 MSE 吗? en.wikipedia.org/wiki/Mean_squared_error
  • @MarcoCerliani 对不起我的错误。我所有的问题是实现一个 custom_loss,即使是简单的预定义的。公式就是这种损失的一个例子。

标签: keras tensorflow2.0 loss-function


【解决方案1】:

你使用的公式是 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 2020-03-18
    • 1970-01-01
    相关资源
    最近更新 更多