Search code examples
tensorflowinputbatchsize

TensorFlow's placeholder size


I am getting confused in how to use placeholder for batch training. In my code, input image is of size 3 x 3. In order to do batch training, I am setting tf.placeholder(tf.float32,shape=[None,3,3]).

When I try to give batches of 3x3 as an input, TensorFlow gives an error that

Cannot feed value of shape (3, 3) for Tensor u'Placeholder_1:0', which has shape '(?, 3, 3).

Below is the code

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})

Solution

  • Your placeholder is of shape None x 3 x 3 so you need to feed in data that has 3 dimensions, even if the first dimension just has size 1 (i.e. a 1 x 3 x 3 in your case instead of a 3 x 3). One easy way to add an extra dimension (of size 1) to to an array is to do array[None]. If array has shape 3 x 3 then array[None] has shape 1 x 3 x 3. So you can update your code to

    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]})
    

    (I changed input to inputs because input is a keyword in Python and shouldn't be used as a variable name)

    Note that you won't want to do inputs[None] if inputs is already 3D. If it might be 2D or 3D, you'll need a condition like inputs[None] if inputs.ndim == 2 else inputs.