运行操作时TensorFlow占位符错误



我在Python&TensorFlow(< 1周(。

现在,我想使用TensorFlow构建线性回归,但是我面临占位符的错误。

我已经通过使用占位符设定了成本,并且我检查了输入变量的形状,形状看起来没有任何问题。我还使用print(type(type(((获取类型,它表明newx和y是类" 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:UsersadminAppDataLocalcondacondaenvstensorflowlibsite-packagestensorflowpythonclientsession.py", line 1350, in _do_call
    return fn(*args)
  File "C:UsersadminAppDataLocalcondacondaenvstensorflowlibsite-packagestensorflowpythonclientsession.py", line 1329, in _run_fn
    status, run_metadata)
  File "C:UsersadminAppDataLocalcondacondaenvstensorflowlibsite-packagestensorflowpythonframeworkerrors_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:UsersadminAppDataLocalcondacondaenvstensorflowlibsite-packagestensorflowpythonframeworkops.py", line 648, in eval
    return _eval_using_default_session(self, feed_dict, self.graph, session)
  File "C:UsersadminAppDataLocalcondacondaenvstensorflowlibsite-packagestensorflowpythonframeworkops.py", line 4758, in _eval_using_default_session
    return session.run(tensors, feed_dict)
  File "C:UsersadminAppDataLocalcondacondaenvstensorflowlibsite-packagestensorflowpythonclientsession.py", line 895, in run
    run_metadata_ptr)
  File "C:UsersadminAppDataLocalcondacondaenvstensorflowlibsite-packagestensorflowpythonclientsession.py", line 1128, in _run
    feed_dict_tensor, options, run_metadata)
  File "C:UsersadminAppDataLocalcondacondaenvstensorflowlibsite-packagestensorflowpythonclientsession.py", line 1344, in _do_run
    options, run_metadata)
  File "C:UsersadminAppDataLocalcondacondaenvstensorflowlibsite-packagestensorflowpythonclientsession.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:UsersadminAppDataLocalcondacondaenvstensorflowlibsite-packagestensorflowpythonopsarray_ops.py", line 1680, in placeholder
    return gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name)
  File "C:UsersadminAppDataLocalcondacondaenvstensorflowlibsite-packagestensorflowpythonopsgen_array_ops.py", line 4105, in _placeholder
    "Placeholder", dtype=dtype, shape=shape, name=name)
  File "C:UsersadminAppDataLocalcondacondaenvstensorflowlibsite-packagestensorflowpythonframeworkop_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "C:UsersadminAppDataLocalcondacondaenvstensorflowlibsite-packagestensorflowpythonframeworkops.py", line 3160, in create_op
    op_def=op_def)
  File "C:UsersadminAppDataLocalcondacondaenvstensorflowlibsite-packagestensorflowpythonframeworkops.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"]()]]

您还需要为eval功能提供feed_dict,因为当您评估成本时,需要x和y的值。 tempCost= cost.eval(feed_dict={Xp: newX, y: Y}) 您还可以参考另一个问题:TensorFlow -eval((错误:您必须为占位符张量

喂养一个值

最新更新