TensorFlow 的占位符大小
TensorFlow's placeholder size
我对如何使用占位符进行批量训练感到困惑。在我的代码中,输入图像的大小为 3 x 3。为了进行批量训练,我设置了 tf.placeholder(tf.float32,shape=[None,3,3])
。
当我尝试将 3x3 的批次作为输入时,TensorFlow 给出了一个错误
Cannot feed value of shape (3, 3) for Tensor u'Placeholder_1:0', which has shape '(?, 3, 3).
下面是代码
input = np.array([[1,1,1],[1,1,1],[1,1,1]])
placeholder = tf.placeholder(tf.float32,shape=[None,3,3])
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
sess.run(placeholder, feed_dict{placeholder:input})
您的占位符的形状为 None x 3 x 3
,因此您需要输入具有 3 维度的数据,即使第一个维度的大小仅为 1(即 1 x 3 x 3
在你的情况下而不是 3 x 3
)。向数组添加额外维度(大小为 1)的一种简单方法是执行 array[None]
。如果 array
的形状为 3 x 3
,则 array[None]
的形状为 1 x 3 x 3
。因此,您可以将代码更新为
inputs = np.array([[1, 1 ,1], [1, 1, 1], [1, 1, 1]])
placeholder = tf.placeholder(tf.float32,shape=[None, 3, 3])
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
sess.run(placeholder, feed_dict{placeholder: inputs[None]})
(我把input
改成inputs
因为input
是Python中的关键字,不应该用作变量名)
请注意,如果 inputs
已经是 3D,您将不想执行 inputs[None]
。如果它可能是 2D 或 3D,则需要像 inputs[None] if inputs.ndim == 2 else inputs
.
这样的条件
我对如何使用占位符进行批量训练感到困惑。在我的代码中,输入图像的大小为 3 x 3。为了进行批量训练,我设置了 tf.placeholder(tf.float32,shape=[None,3,3])
。
当我尝试将 3x3 的批次作为输入时,TensorFlow 给出了一个错误
Cannot feed value of shape (3, 3) for Tensor u'Placeholder_1:0', which has shape '(?, 3, 3).
下面是代码
input = np.array([[1,1,1],[1,1,1],[1,1,1]])
placeholder = tf.placeholder(tf.float32,shape=[None,3,3])
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
sess.run(placeholder, feed_dict{placeholder:input})
您的占位符的形状为 None x 3 x 3
,因此您需要输入具有 3 维度的数据,即使第一个维度的大小仅为 1(即 1 x 3 x 3
在你的情况下而不是 3 x 3
)。向数组添加额外维度(大小为 1)的一种简单方法是执行 array[None]
。如果 array
的形状为 3 x 3
,则 array[None]
的形状为 1 x 3 x 3
。因此,您可以将代码更新为
inputs = np.array([[1, 1 ,1], [1, 1, 1], [1, 1, 1]])
placeholder = tf.placeholder(tf.float32,shape=[None, 3, 3])
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
sess.run(placeholder, feed_dict{placeholder: inputs[None]})
(我把input
改成inputs
因为input
是Python中的关键字,不应该用作变量名)
请注意,如果 inputs
已经是 3D,您将不想执行 inputs[None]
。如果它可能是 2D 或 3D,则需要像 inputs[None] if inputs.ndim == 2 else inputs
.