python - Tensorflow 向量的形状为 (col,)

标签 python machine-learning tensorflow python-3.5 linear-regression

我最近一直在学习 Andrew Ng 的类(class),我想我不妨尝试用其他语言(对我来说恰好是 Python)来实现我所学到的东西,但我遇到了障碍。 这是我的代码:

train_x = [[1,2,3,4], [5,6,7,8]]
train_y = [24, 1680]

train_x = np.asarray(train_x)
train_y = np.asarray(train_y)

m = train_x.shape[0]
n = train_x.shape[1]

X = tf.placeholder(tf.float32, [None, n])
Y = tf.placeholder(tf.float32, [None, n])

W = tf.Variable(tf.zeros(n, 1))
b = tf.Variable(tf.zeros(1, 1))

model = tf.add(tf.multiply(X, W), b)
cost = tf.reduce_sum(tf.pow(model-Y, 2)) / (2*m)

然后我使用以下方法训练 GradientDescentOptimizer:

for i in range(1000):
    for x, y in zip(train_x, train_y):
            sess.run(optimizer, feed_dict={X: x, Y: y})

我收到的错误是(在最后一行):

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

任何帮助将不胜感激。有解释就更好了。

最佳答案

您需要将输入 x reshape 为 (some_number, 4) 。还要修复 y 占位符

train_x = [[1, 2, 3, 4], [5, 6, 7, 8]]
train_y = [24, 1680]

train_x = np.asarray(train_x)
train_y = np.asarray(train_y)

m = train_x.shape[0]
n = train_x.shape[1]

X = tf.placeholder(tf.float32, [None, n])
Y = tf.placeholder(tf.float32, [None, 1])

W = tf.Variable(tf.random_normal((n, 1)))
b = tf.Variable(tf.zeros(1, 1))

model = tf.add(tf.matmul(X, W), b)
cost = tf.reduce_sum(tf.pow(model - Y, 2)) / (2 * m)

...
for i in range(1000):
    for x, y in zip(train_x, train_y):
        x = np.reshape(x, (-1, 4))
        y = np.reshape(y, (-1, 1))
        sess.run(optimizer, feed_dict={X: x, Y: y})

关于python - Tensorflow 向量的形状为 (col,),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45985682/

相关文章:

machine-learning - 机器学习,为什么我们需要对数据进行加权

arrays - 数组的转换产生一个空占位符

python - 联邦学习训练期间模型性能没有提高

c++ - Tensorflow C++ YOU_MADE_A_PROGRAMMING_MISTAKE

python - Tensorflow模型输出大于1的概率值

python - 让 Python 的 `warnings.warn()` 不提及自己

python - 如何将此类移动到 python 中的单独文件中?

python - GridSearchCV 不工作?

python - 输入数字500以下的最大幂

python - 更新后 Google Colab 无法连接到本地运行时