![](/img/trans.png)
[英]ValueError: Shape must be rank 2 but is rank 3 for 'MatMul'
[英]ValueError: Shape must be rank 2 but is rank 1 for 'MatMul'
我正在嘗試使用 TensorFlow 運行線性回歸 model。 我已經給出了下面的代碼。 但是,我得到的錯誤是:ValueError: Shape must be at least rank 2 but is rank 1 for 'model_19/MatMul' (op: 'BatchMatMulV2') with input shapes: [1], ?.
從錯誤來看,似乎是 function 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})
tf.matmul
期望 2 階張量,即矩陣。 相反,您有平面向量。 嘗試x.reshape(-1,1)
或x.expand_dims(0)
。 而且您的權重矩陣似乎也需要它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.