您如何计算线性回归模型的训练误差和验证误差?

时间:2020-04-25 11:35:47

标签: python machine-learning linear-regression mean-square-error

我有一个线性回归模型,我的成本函数是平方和误差函数。我将整个数据集分为三个数据集,即训练,验证和测试。我不确定如何计算训练误差和验证误差(以及两者之间的差异)。

训练误差是使用训练数据集计算出的残差平方和误差吗?

我要问的一个例子:那么,如果我是用Python进行的,并且假设我在训练数据集中有90个数据点,那么这是训练错误的正确代码吗?

y_predicted = f(X_train, theta) #predicted y-value at point x, where y_train is the actual y-value at x
training_error = 0
for i in range(90):
  out = y_predicted[i] - y_train[i] 
  out = out*out 
  training_error+=out

training_error = training_error/2
print('The training error for this regression model is:', training_error)

1 个答案:

答案 0 :(得分:0)

这是在帖子评论中提到的,但是您需要除以样本总数才能得到一个可以在验证集和测试集之间进行比较的数字。

只需将代码更改为:

y_predicted = f(X_train, theta) #predicted y-value at point x, where y_train is the actual y-value at x
training_error = 0
for i in range(90):
  out = y_predicted[i] - y_train[i] 
  out = out*out 
  training_error+=out

#change 2 to 90 
training_error = training_error/90
print('The training error for this regression model is:', training_error)

这样做的目的是让您可以使用同一度量比较两个不同的数据子集。只要您也将样本数除以2,就可以了。

在Python中执行此操作的另一种方法是使用sci-kit学习库,该库已经具有function

请参阅下文。

from sklearn.metrics import mean_squared_error
training_error = mean_squared_error(y_train,y_predicted)

通常,在进行这样的计算时,最好使用矩阵乘法而不是for循环。在此情况下,这个问题的90条记录很小,但是当您开始使用较大的样本量时,可以使用numpy尝试类似的操作。

import numpy as np

training_error = np.mean(np.square(np.array(y_predicted)-np.array(y_train)))

所有3种方法都应该为您带来相似的结果。