ValueError: Cannot feed value of shape (1,) for Tensor u'Placeholder:0', which has shape '(1, 1)'

时间:2022-05-14 13:47:30

这里x_,y_是两个数字,当我运行时

        sess.run(train_op , feed_dict = {x_data:np.array([x_]) ,
            y_data:np.array([y_])}) 

遇到了
Traceback (most recent call last):
File “linear.py”, line 71, in
y_data:np.array([y_])})
File “/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py”, line 889, in run
run_metadata_ptr)
File “/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py”, line 1096, in _run
% (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (1,) for Tensor u’Placeholder:0’, which has shape ‘(1, 1)’

其实原因很简单,我这里的feed需要(1,1)的矩阵,也就是一维的且只有一个元素的矩阵,但[x_]和[y_]在tensorflow里会被认为是一维的但元素个数不知的数组。所以加个方括号, 即[[x_]]和[[y_]]就搞定了

因为在给函数传参数shape时需要传递形状,如shape=[2,2],表示2维矩阵,每个维度有两个元素,只是代表形状,不是具体的矩阵
当传递给feed里面的占位符时,需要实际具体的矩阵而不是形状,如传二维的矩阵:x_data:[[1,1],[1,1]]

总之形状和实际具体矩阵不要弄混