0

I am totally new in both python & tensorflow (<1 week).

Now i want to build a linear regression by using tensorflow, however i am facing an error of placeholder.

I have set the cost by using placeholder, and i have checked the shape of the input variables, it looks no any problem about the shape. I have also use print(type()) to get the type, it shows both newX and Y are class 'numpy.ndarray' .

here is my code: UPDATE:(paste the full code of the class)

class RegByNN(object):

def __init__(self, learning_rate=0.001):
    self.learning_rate= learning_rate

def fit(self, X, Y, Xtest, Ytest, TrainLoop=30):
    # function try to fit the target to Y
    # call forward and loop here
    plt.plot(X,Y)
    plt.show()

    costs = []

    # make shape of Y to [?, 1]
    shapeOfY = Y.shape
    shapeOfY = shapeOfY[0]
    Y = Y.reshape(shapeOfY,1)

    shapeOfX = X.shape
    shapeOfX= int(shapeOfX[0])
    # add bise term
    B= np.ones(shapeOfX)        

    newX= np.stack([X, B])
    newX = newX.T
    m, shapeOfNewX = newX.shape

    Xp = tf.placeholder(tf.float32, shape=(m, shapeOfNewX), name='Xp')
    y = tf.placeholder(tf.float32, shape=(None,1), name='y')

    W1 = tf.Variable(tf.random_normal([shapeOfNewX, m])) 

    cost = tf.reduce_mean(tf.square(tf.matmul(Xp, W1) - y))
    train_op =  tf.train.GradientDescentOptimizer(self.learning_rate).minimize(cost)

    with tf.Session() as sess:
        init = tf.global_variables_initializer()
        sess.run(init)
        print(type(newX))
        print(type(Y))
        for step in range(TrainLoop):
            sess.run(train_op, feed_dict={Xp: newX, y: Y} )
            tempCost= cost.eval()
            costs.append(tempCost)
            if int(step % (TrainLoop/2)) == 0 :
                tempW1= W1.eval()
                #tempW2= W2.eval()
                print("i = ",step ,"new W1 is: ", tempW1,"new W2 is: ", tempW2.T , "cost: ", tempCost)

        tempW1= W1.eval()
        tempW2= W2.eval()

    print("final W1 is: ", tempW1)
    print("new W2 is: ", tempW2.T )
    print("cost: ", tempCost)

The following is the error code:

Traceback (most recent call last):
  File "C:\Users\admin\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 1350, in _do_call
    return fn(*args)
  File "C:\Users\admin\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 1329, in _run_fn
    status, run_metadata)
  File "C:\Users\admin\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 473, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_1' with dtype float and shape [?,1]
         [[Node: Placeholder_1 = Placeholder[dtype=DT_FLOAT, shape=[?,1], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "~~.py", line 87, in <module>
    main()
  File "~~.py", line 84, in main
    model.fit(X, Y, Xtest, Ytest, learning_rate, 40000,20)
  File "~~.py", line 47, in fit
    tempCost= cost.eval()
  File "C:\Users\admin\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 648, in eval
    return _eval_using_default_session(self, feed_dict, self.graph, session)
  File "C:\Users\admin\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 4758, in _eval_using_default_session
    return session.run(tensors, feed_dict)
  File "C:\Users\admin\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 895, in run
    run_metadata_ptr)
  File "C:\Users\admin\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 1128, in _run
    feed_dict_tensor, options, run_metadata)
  File "C:\Users\admin\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 1344, in _do_run
    options, run_metadata)
  File "C:\Users\admin\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 1363, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_1' with dtype float and shape [?,1]
         [[Node: Placeholder_1 = Placeholder[dtype=DT_FLOAT, shape=[?,1], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

Caused by op 'Placeholder_1', defined at:
  File "~~.py", line 87, in <module>
    main()
  File "~~.py", line 84, in main
    model.fit(X, Y, Xtest, Ytest, learning_rate, 40000,20)
  File "~~.py", line 33, in fit
    y = tf.placeholder(tf.float32, shape=(None,1))
  File "C:\Users\admin\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\array_ops.py", line 1680, in placeholder
    return gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name)
  File "C:\Users\admin\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 4105, in _placeholder
    "Placeholder", dtype=dtype, shape=shape, name=name)
  File "C:\Users\admin\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "C:\Users\admin\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 3160, in create_op
    op_def=op_def)
  File "C:\Users\admin\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 1625, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_1' with dtype float and shape [?,1]
         [[Node: Placeholder_1 = Placeholder[dtype=DT_FLOAT, shape=[?,1], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
Tony Ho
  • 37
  • 1
  • 6

1 Answers1

0

You need to provide a feed_dict to the eval function as well because when you evaluate the cost, you need the values of X and y. tempCost= cost.eval(feed_dict={Xp: newX, y: Y}) You can also refer to this other question: Tensorflow - eval() error: You must feed a value for placeholder tensor

AlCorreia
  • 532
  • 4
  • 12