运行操作时的Tensorflow占位符错误

时间:2018-02-06 17:02:45

标签: python tensorflow linear-regression

我在python和amp;中都是全新的张量流(< 1周)。

现在我想通过使用tensorflow构建线性回归,但是我遇到了占位符错误。

我已经使用占位符设置了成本,并且我已经检查了输入变量的形状,它看起来没有任何形状问题。我还使用print(type())来获取类型,它显示newX和Y都是 class' numpy.ndarray'

这是我的代码: 更新:(粘贴类的完整代码)

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)

以下是错误代码:

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"]()]]

1 个答案:

答案 0 :(得分:0)

您还需要向eval函数提供feed_dict,因为在评估成本时,您需要X和y的值。 tempCost= cost.eval(feed_dict={Xp: newX, y: Y}) 您还可以参考其他问题:Tensorflow - eval() error: You must feed a value for placeholder tensor