ValueError:形状必须为秩2,但对于“MatMul”为秩1

2024-05-16 08:45:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用TensorFlow运行一个线性回归模型。我已经给出了下面的代码。但是,我得到的错误是:ValueError:Shape必须至少是秩2,但对于输入形状为[1],?“model_19/MatMul”(op:'BatchMatMulV2')的“model_19/MatMul”(op:'BatchMatMulV2'),它的秩1

从错误来看,似乎是函数模型的输入造成了问题。对于解决错误的任何建议,我们将不胜感激

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})

Tags: 模型getmodeltf错误withtrainvariable