python - ValueError : Cannot feed value of shape (2, ) 对于张量 'Placeholder:0' ,其形状为 '(1, 2)'

标签 python numpy tensorflow machine-learning linear-regression

我是 tensorflow 新手,正在尝试创建线性回归模型。我的代码是

import numpy as np
import tensorflow as tf

bias = np.ones((50, 1))
trainX = np.arange(0, 10, 0.2).reshape(50, 1)
trainY = (3 * trainX + np.random.rand(trainX.shape[0]) * 20 - 10) + 10
trainX = np.append(bias, trainX, axis=1)

X = tf.placeholder("float", shape=(1, 2))
Y = tf.placeholder("float")
w = tf.Variable([[0.0, 0.0]], name="weights")

model = tf.matmul(X, tf.transpose(w))
cost = tf.pow((Y - model), 2)

init = tf.global_variables_initializer()
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(cost)

with tf.Session() as sess:
    sess.run(init)

    for i in range(50):
        for (x, y) in zip(trainX, trainY):
            sess.run(train_op, feed_dict={X: x, Y: y})

    print(sess.run(w))

我不知道我做错了什么。我认为问题在于初始化权重。这个想法很简单,就是预测两个权重常数,它们可以最好地预测拟合数据的线。

I'm getting this error in colaboratory notebook

最佳答案

这里有几件事正在密谋。我假设您希望 trainY 的形状为 (50,),但由于您仅在 reshape 后添加噪声,广播会导致 trainX + np.random .rand(trainX.shape[0]) 具有形状 (50, 50)。如果将代码的初始部分更改为

bias = np.ones(50)
trainX = np.arange(0, 10, 0.2)
trainY = (3 * trainX + np.random.rand(trainX.shape[0]) * 20 - 10) + 10
trainX = np.vstack([bias, trainX]).T

并确保形状设置正确

sess.run(train_op, feed_dict={X: x.reshape((1, 2)), Y: y})

然后你的代码就会运行。

但是,由于您只处理二维向量的内积,因此您可以通过简单地使用 tf.tensordot 来完全避免 reshape 。 :

X = tf.placeholder("float", shape=(2,))
Y = tf.placeholder("float")
w = tf.Variable([0.0, 0.0], name="weights")

model = tf.tensordot(X, w, 1)

最后,请注意,虽然在将样本传递给优化器之前分割样本的方法(通常称为批处理)对于大型数据集效果很好,但在您的情况下,您也可以将整个样本传递给一次;也就是说,相当于

X = tf.placeholder("float", shape=(50, 2))
Y = tf.placeholder("float", shape=(50, 1))
w = tf.Variable(tf.zeros([2, 1], "float"), name="weights")

model = tf.matmul(X, w)
cost = tf.reduce_sum(tf.pow((Y - model), 2))

init = tf.global_variables_initializer()
train_op = tf.train.GradientDescentOptimizer(0.0001).minimize(cost)

with tf.Session() as sess:
    sess.run(init)
    for i in range(10000):
        sess.run(train_op, feed_dict={X: trainX, Y: trainY.reshape((50, 1))})

关于python - ValueError : Cannot feed value of shape (2, ) 对于张量 'Placeholder:0' ,其形状为 '(1, 2)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51342354/

相关文章:

python - TensorFlow:执行此损失计算

python - Tensorflow:使用不同的 "call"函数创建 LSTM 单元的自定义子类

python - Django 在创建另一个对象时创建并保存模型的许多实例

python - 如何在 Django 中构建电子商务购物车?

python - 如何从文件路径中删除 %20?

python - NumPy: `vectorize` 的替代方案,让我可以访问数组

python - 2.7.10 和 2.7.13 之间 dict.viewkeys() 和元组之间交集行为的差异

python - 在执行操作的单独子数组中获取 numpy 子数组的结果,而不使用 for 循环

Numpy 高级索引困惑

csv - TensorFlow 对象检测 API CSV 文件格式