TensorFlow 线性回归模型维度不匹配错误分析与解决

错误信息:

InvalidArgumentError: {{function_node _wrapped__MatMul_device/job:localhost/replica:0/task:0/device:CPU:0}} Matrix size-incompatible: In[0]: [424,10], In[1]: [424,10] [Op:MatMul]

代码分析:

该代码使用 TensorFlow 实现了线性回归模型,错误发生在计算训练集预测值的第 14 行代码 PRED_train = tf.matmul(X_train,W)

错误原因:

tf.matmul() 函数要求两个矩阵的最后一维相等,才能进行矩阵乘法运算。代码中 X_train 的维度为 [424, 10]W 的维度为 [10, 10],它们的最后一维分别为 1010,不相等,因此出现了维度不匹配的错误。

解决方法:

W 的维度改为 [10, 1],使 X_trainW 的最后一维都为 1,这样就可以进行矩阵乘法运算。

**修改后的代码:**pythonimport tensorflow as tfimport numpy as np

超参数learning_rate = 0.01iter = 1000

生成随机数据X_train = np.random.randn(424, 10)Y_train = np.random.randn(424, 1)X_test = np.random.randn(106, 10)Y_test = np.random.randn(106, 1)

模型参数W = tf.Variable(tf.random.normal([10, 1]), name='weight') # 修改 W 的维度b = tf.Variable(tf.zeros([1]), name='bias')

模型函数def linear_regression(X): return tf.matmul(X, W) + b

损失函数def mean_square(y_pred, y_true): return tf.reduce_mean(tf.square(y_pred - y_true))

优化器optimizer = tf.optimizers.SGD(learning_rate)

初始损失PRED_train = linear_regression(X_train)Loss_train = mean_square(PRED_train, Y_train)print('Initial loss: {:.3f}'.format(Loss_train))

训练模型for i in range(iter + 1): with tf.GradientTape() as tape: PRED_train = linear_regression(X_train) Loss_train = mean_square(PRED_train, Y_train) PRED_test = linear_regression(X_test) Loss_test = mean_square(PRED_test, Y_test)

# 计算梯度    gradients = tape.gradient(Loss_train, [W, b])

# 更新模型参数    optimizer.apply_gradients(zip(gradients, [W, b]))

if i % 100 == 0:        print('Iter {:03d}: Train loss: {:.3f}, Test loss: {:.3f}'.format(i, Loss_train, Loss_test))

总结:

通过修改 W 的维度,解决了 TensorFlow 线性回归模型中的维度不匹配错误,并成功训练了模型

TensorFlow 线性回归模型维度不匹配错误: InvalidArgumentError: Matrix size-incompatible

原文地址: https://www.cveoy.top/t/topic/f1Uz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录