# 定义损失函数 接下来,我们使用**均方误差**( **MSE** )定义损失函数。 MSE 定义如下: 有关 MSE 的更多详细信息,[请访问此链接](http://www.statisticshowto.com/mean-squared-error/) `y`的实际值和估计值的差异称为**残留**。损失函数计算残差平方的平均值。我们通过以下方式在 TensorFlow 中定义它: ```py loss = tf.reduce_mean(tf.square(model - y_tensor)) ``` * `model - y_tensor`计算残差 * `tf.square(model - y_tensor)`计算每个残差的平方 * `tf.reduce_mean( ... )`最终计算在前一步骤中计算的平方均值 我们还定义**均方误差**( **mse** )和 **r 平方**( **rs** )函数来评估训练模型。我们使用单独的`mse`函数,因为在接下来的章节中,损失函数将改变但`mse`函数将保持不变。 ```py # mse and R2 functions mse = tf.reduce_mean(tf.square(model - y_tensor)) y_mean = tf.reduce_mean(y_tensor) total_error = tf.reduce_sum(tf.square(y_tensor - y_mean)) unexplained_error = tf.reduce_sum(tf.square(y_tensor - model)) rs = 1 - tf.div(unexplained_error, total_error) ```