Tensorflow Tf.tf.squared_difference 显示密集层的值错误
Tensorflow Tf.tf.squared_difference is showing a value error with dense layer
每当我尝试将两个张量相乘,然后将它们作为输入提供给致密层时,它都能完美运行。但是,当我尝试计算它们之间的平方差时,它向我显示错误。
# working well
out= multiply([user, book])
result = Dense(1, activation='sigmoid', kernel_initializer=initializers.lecun_normal(),
name='prediction')(out)
# error
out= tf.reduce_sum(tf.squared_difference(user, book),1)
result = Dense(1, activation='sigmoid', kernel_initializer=initializers.lecun_normal(),
name='prediction')(out)
这是我得到的错误:
Input 0 is incompatible with layer prediction: expected min_ndim=2, found ndim=1 error
您可能需要将 keepdims=True
参数传递给 reduce_sum
函数以保持长度为 1 的维度(否则,out
的形状将是 (batch_size)
,而 Dense
层需要 (batch_size, N)
):
out= tf.reduce_sum(tf.squared_difference(user, book), axis=1, keepdims=True)
更新: Keras层的输入必须是其他Keras层的输出。因此,如果你想使用 TensorFlow 操作,你需要将它们包装在 Keras 中的一个 Lambda
层中。例如:
from keras.layers import Lambda
out = Lambda(lambda x: tf.reduce_sum(tf.squared_difference(x[0], x[1]), axis=1, keepdims=True))([user, book])
每当我尝试将两个张量相乘,然后将它们作为输入提供给致密层时,它都能完美运行。但是,当我尝试计算它们之间的平方差时,它向我显示错误。
# working well
out= multiply([user, book])
result = Dense(1, activation='sigmoid', kernel_initializer=initializers.lecun_normal(),
name='prediction')(out)
# error
out= tf.reduce_sum(tf.squared_difference(user, book),1)
result = Dense(1, activation='sigmoid', kernel_initializer=initializers.lecun_normal(),
name='prediction')(out)
这是我得到的错误:
Input 0 is incompatible with layer prediction: expected min_ndim=2, found ndim=1 error
您可能需要将 keepdims=True
参数传递给 reduce_sum
函数以保持长度为 1 的维度(否则,out
的形状将是 (batch_size)
,而 Dense
层需要 (batch_size, N)
):
out= tf.reduce_sum(tf.squared_difference(user, book), axis=1, keepdims=True)
更新: Keras层的输入必须是其他Keras层的输出。因此,如果你想使用 TensorFlow 操作,你需要将它们包装在 Keras 中的一个 Lambda
层中。例如:
from keras.layers import Lambda
out = Lambda(lambda x: tf.reduce_sum(tf.squared_difference(x[0], x[1]), axis=1, keepdims=True))([user, book])