Tensorflow: How to feed a placeholder variable with a tensor?

前端 未结 4 1157
南旧
南旧 2020-12-10 10:47

I have a placeholder variable that expects a batch of input images:

input_placeholder = tf.placeholder(tf.float32, [None] + image_shape, name=\'input_images         


        
相关标签:
4条回答
  • 2020-12-10 11:00

    One way of solving the problem is to actually remove the Placeholder tensor and replace it by your "myInputTensor".

    You will use the myInputTensor as the source for the other operations in the graph and when you want to infer the graph with your np array as input data, you will feed a value to this tensor directly.

    Here is a quick example:

    import tensorflow as tf 
    import numpy as np
    
    # Input Tensor
    myInputTensor = tf.ones(dtype=tf.float32, shape=1) # In your case, this would be the results of some ops
    
    output = myInputTensor * 5.0
    
    with tf.Session() as sess:
        print(sess.run(output)) # == 5.0, using the Tensor value
        myNumpyData = np.zeros(1)
        print(sess.run(output, {myInputTensor: myNumpyData}) # == 0.0 * 5.0 = 0.0, using the np value
    
    0 讨论(0)
  • 2020-12-10 11:02

    This works for me in latest version...maybe you have older version of TF?

    a = tf.Variable(1)
    sess.run(2*a, feed_dict={a:5}) # prints 10
    
    0 讨论(0)
  • 2020-12-10 11:04

    You can use feed_dict to feed data into non-placeholders. So, first, wire up your dataflow graph directly to your myInputTensor tensor data source (i.e. don't use a placeholder). Then when you want to run with your numpy data you can effectively mask myImportTensor with myNumpyData, like this:

    mLoss, = sess.run([loss], feed_dict={myImportTensor: myNumpyData})
    

    [I'm still trying to figure out how to do this with multiple tensor data sources however.]

    0 讨论(0)
  • 2020-12-10 11:05

    This has been discussed on GitHub in 2016, and please check here. Here is the key point by concretevitamin:

    One key thing to note is that Tensor is simply a symbolic object. The values of your feed_dict are the actual values, e.g. a Numpy ndarry.

    The tensor as a symbolic object is flowing in the graph while the actual values are outside of it, then we can only pass the actual values into the graph and the symbolic object can not exist outside the graph.

    0 讨论(0)
提交回复
热议问题