对我来说,Tensorflow的一个神秘之处是:一个变量何时代表单个张量,而不是批处理?下面是一个具有连续输出值(不是分类器)的网络示例。在以loss
开头的行中,我通过从真值中减去预测值并将这些差值的绝对值相加来计算损失。在这一行中,Tensorflow为truthValues_placeholder
插入了一批真值,因此truthValues_placeholder
是一个"批"张量,即它对批中的每个项都有一个条目。但是,前一行将prediction
计算为单个值(而不是批处理)。我的问题:我是否正确,Tensorflow神奇地将prediction
更改为"批张量",因此它也为批处理中的每个项目计算一个条目?
graph = tf.Graph()
with tf.Graph().as_default():
...
# Network layers here
...
# Final layer
prediction = tf.matmul(inputsToLastLayer, weightsOutputLayer) + biasesOutputLayer
loss = tf.nn.l2_loss(tf.sub(prediction, truthValues_placeholder))
...
global_step = tf.Variable(0, name='global_step', trainable=False)
train_op = optimizer.minimize(loss, global_step=global_step)
...
sess = tf.Session()
init = tf.initialize_all_variables()
sess.run(init)
for step in xrange(maxSteps):
feed_dict = fill_feed_dict(..., truthValues_placeholder,...)
Tensorflow的行为方式与numpy相同,因为它将单个单元的基本操作广播到整个矩阵,如
In [3]: np.zeros([10, 10]) - 1
Out[3]:
array([[-1., -1., -1., -1., -1., -1., -1., -1., -1., -1.],
[-1., -1., -1., -1., -1., -1., -1., -1., -1., -1.],
[-1., -1., -1., -1., -1., -1., -1., -1., -1., -1.],
[-1., -1., -1., -1., -1., -1., -1., -1., -1., -1.],
[-1., -1., -1., -1., -1., -1., -1., -1., -1., -1.],
[-1., -1., -1., -1., -1., -1., -1., -1., -1., -1.],
[-1., -1., -1., -1., -1., -1., -1., -1., -1., -1.],
[-1., -1., -1., -1., -1., -1., -1., -1., -1., -1.],
[-1., -1., -1., -1., -1., -1., -1., -1., -1., -1.],
[-1., -1., -1., -1., -1., -1., -1., -1., -1., -1.]])
所以,没什么好惊讶的。如果你想确定的话,你可以先用NumPy测试你的操作。