【发布时间】:2017-07-07 11:07:49
【问题描述】:
我不太了解 TensorFlow 中的广播机制是如何工作的。假设我们有以下代码:
W1_shape = [5, 5, 1, 32]
b1_shape = [32]
x = tf.placeholder(tf.float32)
initial_W1 = tf.truncated_normal(shape=W1_shape, stddev=0.1)
W1 = tf.Variable(initial_W1)
initial_b1 = tf.constant(0.1, shape=b1_shape)
b1 = tf.Variable(initial_b1)
conv1 = tf.nn.conv2d(x, W1, strides=[1, 1, 1, 1], padding='SAME')
conv1_sum = conv1 + b1
y = tf.placeholder(tf.float32)
z = conv1 + y
sess = tf.Session()
# Run init ops
init = tf.global_variables_initializer()
sess.run(init)
while True:
samples, labels, indices = dataset.get_next_batch(batch_size=1000)
samples = samples.reshape((1000, MnistDataSet.MNIST_SIZE, MnistDataSet.MNIST_SIZE, 1))
y_data = np.ones(shape=(1000, 32))
conv1_res, conv1_sum_res, b1_res, z_res=\
sess.run([conv1, conv1_sum, b1, z], feed_dict={x: samples, y: y_data})
if dataset.isNewEpoch:
break
因此,我加载了 MNIST 数据集,该数据集由 28x28 大小的图像组成。卷积算子使用 32 个 5x5 大小的过滤器。我使用 1000 的批量大小,因此数据张量 x 的形状为 (1000,28,28,1)。 tf.nn.conv2d 操作输出形状为 (1000,28,28,32) 的张量。 y 是一个占位符,我添加一个变量来检查 Tensorflow 的广播机制,方法是将其添加到 (1000,28,28,32) 形状的 conv1 张量中。在y_data = np.ones(shape=(1000, 32)) 行中,我尝试了y 的各种张量形状。形状 (28,28)、(1000,28) 和 (1000,32) 不会添加到 conv1,错误类型为:
InvalidArgumentError(有关回溯,请参见上文):不兼容的形状:[1000,28,28,32] 与 [28,28]
形状 (28,32) 和 (28,28,32) 可以正常工作和广播。但是根据https://www.tensorflow.org/performance/xla/broadcasting 中解释的广播语义,前三个形状也必须工作,因为它们通过将尺寸与 4D conv1 张量匹配而具有正确的顺序。例如,(28,28) 匹配维度 1 和 2 中的 (1000,28,28,32),(1000,32) 匹配维度 0 和 3,正如链接中所述。我在这里遗漏或误解了什么吗?在这种情况下,Tensorflow 的正确广播行为是什么?
【问题讨论】:
标签: python tensorflow deep-learning