用Python(使用Scikit Learn)计算线性回归的均方误差

3
我正在尝试用Python进行简单的线性回归,其中x变量是项目描述的字数,y值是资金筹集速度(以天为单位)。
我有点困惑,因为测试数据的均方根误差(RMSE)为13.77,训练数据为13.88。首先,RMSE不应该在0和1之间吗?其次,测试数据的RMSE不应该比训练数据高吗?所以我猜我做错了什么,但不确定错误在哪里。
此外,我需要知道回归的权重系数,但不幸的是不知道如何打印它,因为它在sklearn方法中有点隐藏。有人可以帮忙吗?
以下是我目前的代码:
import numpy as np
import matplotlib.pyplot as plt
import sqlite3
from sklearn.model_selection import train_test_split
from sklearn import linear_model

con = sqlite3.connect('database.db')
cur = con.cursor()

# y-variable in regression is funding speed ("DAYS_NEEDED")    
cur.execute("SELECT DAYS_NEEDED FROM success")
y = cur.fetchall()                  # list of tuples
y = np.array([i[0] for i in y])     # list of int   # y.shape = (1324476,)

# x-variable in regression is the project description length ("WORD_COUNT")
cur.execute("SELECT WORD_COUNT FROM success")
x = cur.fetchall()
x = np.array([i[0] for i in x])     # list of int   # x.shape = (1324476,)

# Get the train and test data split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)

# Fit a model
lm = linear_model.LinearRegression()
x_train = x_train.reshape(-1, 1)    # new shape: (1059580, 1)
y_train = y_train.reshape(-1, 1)    # new shape: (1059580, 1)
model = lm.fit(x_train, y_train)
x_test = x_test.reshape(-1, 1)      # new shape: (264896, 1)
predictions_test = lm.predict(x_test)
predictions_train = lm.predict(x_train)

print("y_test[5]: ", y_test[5])     # 14
print("predictions[5]: ", predictions_test[5]) # [ 12.6254537]

# Calculate the root mean square error (RMSE) for test and training data
N = len(y_test)
rmse_test = np.sqrt(np.sum((np.array(y_test).flatten() - np.array(predictions_test).flatten())**2)/N)
print("RMSE TEST: ", rmse_test)     # 13.770731326

N = len(y_train)
rmse_train = np.sqrt(np.sum((np.array(y_train).flatten() - np.array(predictions_train).flatten())**2)/N)
print("RMSE train: ", rmse_train)   # 13.8817814595

非常感谢您的帮助!谢谢!


RMSE不一定在0到1之间。它取决于你所拥有的y的范围。如果y的范围更大,那么RMSE可以大于1。 - Umang Gupta
请参见http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression.get_params以获取参数。或者您可以使用`model.coef_`和`model.intercept_`。 - Umang Gupta
1
如果因变量(即 y)在 0 和 1 之间,且所有预测值也在 0 和 1 之间,则 RMSE 只会在 0 和 1 之间。如果您有一个训练良好的模型,则测试数据的 RMSE 将更接近于训练 RMSE(并且更低)。如果您有一个过度拟合的模型,则它将更高。如果您的测试数据对模型来说太简单,则可能会更低。您可以在这里找到有用的信息。 - Autonomous
1个回答

3
  1. RMSE(均方根误差)的单位与因变量相同。这意味着,如果你要预测的变量在0到100之间变化,那么RMSE为99就非常糟糕!如果说你的数据在0到100之间,其RMSE为5,那么RMSE为5就非常好。但是,如果数据在1到10之间,RMSE也为5的话,那么就有问题了!希望这能让你明白这个观点。

  2. 如果你的训练集和测试集的RMSE相似,那么恭喜你!你做得很好!如果测试集的RMSE > 训练集的RMSE,那么你可能有些过拟合。

根据Umang在评论中提到的,你可以使用 model.coef_model.intercept_ 打印出模型计算出的最优权重。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接