我正在尝试使用TensorFlow运行线性回归模型。我给出了下面的代码。然而,我得到的错误是: ValueError: Shape必须至少是等级2,但对于'model_19/MatMul‘(op:'BatchMatMulV2'),输入的shapes: 1,?是等级1。
从错误中看,似乎是函数model_linear的输入造成了问题。对于解决这个错误,任何建议都将受到高度赞赏。
import tensorflow as tf
x_train = [1.0, 2.0, 3.0, 4.0]
y_train = [1.5, 3.5, 5.5, 7.5]
def model_linear(x, y):
with tf.variable_scope('model', reuse=tf.AUTO_REUSE):
W = tf.get_variable("W", initializer=tf.constant([0.1]))
b = tf.get_variable("b", initializer=tf.constant([0.0]))
output = tf.matmul(W, x) + b
loss = tf.reduce_sum(tf.square(output - y))
return loss
optimizer = tf.train.GradientDescentOptimizer(0.01)
with tf.Session():
tf.global_variables_initializer().run()
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
loss = model_linear(x, y)
train = optimizer.minimize(loss)
for i in range(1000):
train.run(feed_dict = {x:x_train, y:y_train})发布于 2020-05-09 01:03:39
tf.matmul期望秩为2的张量,即矩阵。取而代之的是扁平向量。尝试使用x.reshape(-1,1)或x.expand_dims(0)。看起来你的权重矩阵也需要它。
https://stackoverflow.com/questions/61684027
复制相似问题