【问题标题】:TensorFlow's placeholder sizeTensorFlow 的占位符大小
【发布时间】:2019-04-12 15:47:22
【问题描述】:

我对如何使用占位符进行批量训练感到困惑。在我的代码中,输入图像的大小为 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})

【问题讨论】:

    标签: tensorflow input batchsize


    【解决方案1】:

    您的占位符的形状为 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 这样的条件。

    【讨论】:

    • 占位符不应该是 tf.placeholder(tf.float32,shape=[3,3,None]) 因为批量训练会增加第三维的输入大小,比如第一个输入将是 3 x 3 x 1,第二批输入将使输入为 3 x 3 x 2。为什么首先是 tf.placeholder(tf.float32,shape=[None, 3, 3])。这表明第 3 维固定为 3。对此有何解释?
    • 通常的约定是将批次维度放在首位
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 2016-10-02
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    相关资源
    最近更新 更多