1

我正在尝试在 google colab 上使用 Tensorflow 和 Keras API 实施自定义培训。我使用 TensorFlow 2.0.0-beta1。

我的损失函数代码部分是:

model = tf.keras.Sequential([
    tf.keras.layers.Embedding(
        max_features, 32, 
        embeddings_initializer='random_uniform'
    ),
    tf.keras.layers.SimpleRNN(32, kernel_initializer='random_uniform'),  
    tf.keras.layers.Dense(1, activation=tf.nn.sigmoid,),  # input shape is required
])

predictions = model(input_train)
predictions = tf.reshape(predictions,[25000,])

loss_object = tf.keras.losses.binary_crossentropy(
    y_true=y_train, 
    y_pred=predictions
)

def loss(model, x, y):
    y_ = model(x)

    return loss_object(y_true=y, y_pred=y_)

l = loss(model, input_train, y_train)

哪个会产生此错误:

 TypeError  Traceback (most recent call last) <ipython-input-17-675f7c1fd9d0> in <module>()
 return loss_object(y_true=y, y_pred=y_) 
 l = loss(model, input_train, y_train) 
 <ipython-input-17-675f7c1fd9d0> in 
 loss(model, x, y) y_ = model(x) 
return loss_object(y_true=y, y_pred=y_) l = loss(model, input_train, y_train) 
 TypeError: 'tensorflow.python.framework.ops.EagerTensor' object is not callable
4

1 回答 1

3

您想计算model给定输入x、目标输出y和预测的损失y_。所以loss_object应该是一个损失函数(而不是一个预先计算的损失),你可以用它来计算损失。因此,替换这个:

loss_object = tf.keras.losses.binary_crossentropy(y_true=y_train, y_pred=predictions)

有了这个:

loss_object = tf.keras.losses.binary_crossentropy
于 2019-07-26T13:59:32.763 回答