我在尝试运行一个我在某个网站上看到的关于用TensorFlow进行线性回归的代码,但它一直报错,我不知道代码哪里出了问题。起初我以为是我的IDE的问题,后来我换到Jupyter Lab,它在这一点上显示了错误
from __future__ import absolute_import, division, print_functionimport tensorflow as tfimport numpy as nprng = np.randomX= np.array([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167, 7.042,10.791,5.313,7.997,5.654, 9.27,3.1])Y=np.array([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.22, 1, 2.827,3.465,1.65,2.904,2.42,2.94,1.3])n_samples = X.shape[0]# 设置超参数learning_rate = 0.01epochs = 1000display_step = 50# 权重和偏置随机初始化W = tf.Variable(rng.randn(), name="weight")b = tf.Variable(rng.randn(), name="bias")# 线性回归 (Wx + b)def linear_regression(x): return W*x + b# 均方误差def mean_square(y_pred, y_true): return tf.reduce_sum(tf.pow(y_pred-y_true, 2) / (2*n_samples))# 随机梯度下降优化器optimizer = tf.optimizers.SGD(learning_rate)# 优化过程def run_optimization():# 使用GradientTape包装计算以进行自动微分 with tf.GradientTape() as g: pred = linear_regression(X) loss = mean_square(pred, Y) # 计算梯度 gradients = g.gradient(loss, [W,b]) # 根据梯度更新W和b optimizer.apply_gradients(zip(gradients, [W,b]))# 运行指定步数的训练for step in range(1, epochs + 1):# 运行优化以更新W和b的值 run_optimization() if step % display_step == 0: pred = linear_regression(X) loss = mean_square(pred, Y) print("step: %i, loss: %f, W:%f, b:%f"% (step, loss, W.numpy(), b.numpy()))import matplotlib.pyplot as plt # 图形显示plt.plot(X, Y, 'ro', label="原始数据")plt.plot(X, np.array(W * X +b), label="拟合线")plt.legend()plt.show()
起初我以为是我的IDE的问题,后来我换到Jupyter Lab,它在这一点上显示了错误
InvalidArgumentError Traceback (most recent call last)<ipython-input-26-794baf7bf908> in <module> 5 # 运行优化以更新W和b的值。 6 ----> 7 run_optimization() 8 9 if step % display_step == 0:<ipython-input-25-53e6e421f909> in run_optimization() 13 pred = linear_regression(X) 14 ---> 15 loss = mean_square(pred, Y) 16 17 # 计算梯度。<ipython-input-24-184c15846bf2> in mean_square(y_pred, y_true) 9 def mean_square(y_pred, y_true): 10 ---> 11 return tf.reduce_sum(tf.pow(y_pred-y_true, 2)) / (2 * n_samples)~\miniconda3\lib\site-packages\tensorflow\python\ops\math_ops.py in binary_op_wrapper(x, y) 1232 # r_binary_op_wrapper使用不同的force_same_dtype值。 1233 x, y = maybe_promote_tensors(x, y, force_same_dtype=False)-> 1234 return func(x, y, name=name) 1235 except (TypeError, ValueError) as e: 1236 # 即使调度操作失败,RHS也可能是张量感知的~\miniconda3\lib\site-packages\tensorflow\python\util\dispatch.py in wrapper(*args, **kwargs) 204 """调用目标,并在出现TypeError时回退到调度器。""" 205 try:--> 206 return target(*args, **kwargs) 207 except (TypeError, ValueError): 208 # 注意:convert_to_eager_tensor当前会引发ValueError,而不是~\miniconda3\lib\site-packages\tensorflow\python\ops\math_ops.py in subtract(x, y, name) 546 @dispatch.add_dispatch_support 547 def subtract(x, y, name=None):--> 548 return gen_math_ops.sub(x, y, name) 549 550 ~\miniconda3\lib\site-packages\tensorflow\python\ops\gen_math_ops.py in sub(x, y, name) 10549 return _result 10550 except _core._NotOkStatusException as e:> 10551 _ops.raise_from_not_ok_status(e, name) 10552 except _core._FallbackException: 10553 pass~\miniconda3\lib\site-packages\tensorflow\python\framework\ops.py in raise_from_not_ok_status(e, name) 6895 message = e.message + (" name: " + name if name is not None else "") 6896 # pylint: disable=protected-access-> 6897 six.raise_from(core._status_to_exception(e.code, message), None) 6898 # pylint: enable=protected-access 6899 ~\miniconda3\lib\site-packages\six.py in raise_from(value, from_value)InvalidArgumentError: 不兼容的形状:[17] vs. [18] [Op:Sub]
回答:
嗯,正如解释器所抱怨的那样 – 你在mean_square
的输入中存在形状不匹配 – 你的X
/样本向量有17个元素,而你的Y
/目标向量有18个元素,你可以验证这一点。