gpt4 book ai didi

python - Tensorflow Tf.tf.squared_difference 显示密集层的值错误

转载 作者:太空宇宙 更新时间:2023-11-04 04:04:52 26 4
gpt4 key购买 nike

每当我尝试将两个张量相乘,然后将它们作为输入提供给致密层时,它都能完美运行。但是,当我尝试计算它们之间的平方差时,它向我显示错误。

# 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 的形状code> 将是 (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])

关于python - Tensorflow Tf.tf.squared_difference 显示密集层的值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57550935/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com