【问题标题】:Tensorflow Tf.tf.squared_difference is showing a value error with dense layerTensorflow Tf.tf.squared_difference 显示密集层的值错误
【发布时间】:2019-12-24 07:56:16
【问题描述】:

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

# 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

【问题讨论】:

  • 两天前您问了一个非常相似的问题:stackoverflow.com/questions/57520942/… 请不要多次发布问题,您可以随时编辑您的问题以添加新信息
  • 是的,兄弟,但没有解决方案。这篇文章帮助了我。我的问题现在解决了
  • 没关系,正如我所说,不要转发问题。改进它们。

标签: python tensorflow keras tensor


【解决方案1】:

您可能需要将keepdims=True 参数传递给reduce_sum 函数以保持长度为1 的尺寸(否则,out 的形状将是(batch_size),而Dense 层需要@987654327 @):

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])

【讨论】:

  • 我做了,但是它仍然显示错误。但是,这一次的错误有点不同。 AttributeError:“NoneType”对象没有属性“_inbound_nodes”
  • @tauhidullah 您还需要将此操作放在Lambda 层中。例如,请参阅this answer
  • 非常感谢您的友好回应和帮助。非常感谢兄弟
猜你喜欢
  • 1970-01-01
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
  • 2017-07-31
  • 1970-01-01
相关资源
最近更新 更多