![](/img/trans.png)
[英]ValueError: Dimensions must be equal, but are 784 and 500 for 'Mul' (op: 'Mul') with input shapes: [?,784], [784,500]
[英]ValueError: Dimensions must be equal, but are 4096 and 9 for 'mul'. Why no broadcasting here?
我有一个非常简单的示例:
import tensorflow as tf
import pdb
number_features = tf.random_uniform((4096,22))
probs = number_features
probs_L = probs[:,:3]
probs_S1 = probs[:,3:12]
probs_S2 = probs[:,12:22]
confidence_no_digits = probs_L[:,0]
confidence_single_digit = probs_L[:,1] * probs_S1
with tf.Session() as sess:
result = sess.run([confidence_single_digit])
但这给出了:
ValueError:尺寸必须相等,但对于输入形状为[4096],[4096,9]的“ mul”(操作:“ Mul”),尺寸必须为4096和9。
为什么不能将元素大小为[4096]的向量和大小为[4096,9]的矩阵相乘。 为什么广播在这里不起作用?
张量流中的广播遵循与NumPy广播相同的模式。 当对两个数组进行运算时,它会从最后一个维度开始逐个元素地比较它们的形状,然后一直到第一个维度。 在以下情况下,两个维度兼容:
在这种情况下,根据上述规则,从最后一个尺寸开始,尺寸4096(第一个数组的最后一个尺寸)和9(第二个数组的最后一个尺寸)不兼容,因此会出现错误。
为了修复它以获得所需的广播效果,可以将第一个数组转换为具有兼容的形状:
confidence_single_digit = tf.expand_dims(probs_L[:,1],1) * probs_S1
因此形状分别为(4096,1)和(4096,9)。
这样您能得到理想的结果吗?
confidence_single_digit = tf.expand_dims(probs_L[:,1],1) * probs_S1
现在的形状是这些。
<bound method Tensor.get_shape of <tf.Tensor 'ExpandDims_1:0'
shape=(4096, 1) dtype=float32>>
<bound method Tensor.get_shape of <tf.Tensor 'strided_slice_2:0'
shape=(4096, 9) dtype=float32>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.