我正在尝试使用Tensorflow和Keras API在Google colab上实施自定义培训。我使用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
答案 0 :(得分:1)
您要在给定输入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