我试图找出一个线性方程的斜率和y轴截距系数。我创建了一个测试域和范围来确保我得到的数字是正确的。方程应该是y = 2x + 1,但模型显示斜率为24,y轴截距为40.3125。尽管模型准确预测了我给出的每一个值,但我怀疑如何才能得到正确的数值。
import matplotlib.pyplot as pltimport numpy as npfrom sklearn import datasets, linear_modelfrom sklearn.metrics import mean_squared_error, r2_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScalerX = np.arange(0, 40)y = (2 * X) + 1X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=0)X_train = [[i] for i in X_train]X_test = [[i] for i in X_test]sc = StandardScaler()X_train = sc.fit_transform(X_train)X_test = sc.transform(X_test)regr = linear_model.LinearRegression()regr.fit(X_train, y_train)y_pred = regr.predict(X_test)print('Coefficients: \n', regr.coef_)print('Y-intercept: \n', regr.intercept_)print('Mean squared error: %.2f' % mean_squared_error(y_test, y_pred))print('Coefficient of determination: %.2f' % r2_score(y_test, y_pred))plt.scatter(X_test, y_test, color='black')plt.plot(X_test, y_pred, color='blue', linewidth=3)print(X_test)plt.xticks()plt.yticks()plt.show()
回答:
出现这种情况是因为你对训练和测试数据进行了缩放。因此,尽管你生成了y
作为X
的线性函数,但你通过标准化(减去均值并除以标准差)将X_train
和X_test
转换到了另一个尺度上。
如果我们运行你的代码但省略缩放数据的行,你会得到预期的结果。
X = np.arange(0, 40)y = (2 * X) + 1X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=0)X_train = [[i] for i in X_train]X_test = [[i] for i in X_test]# Skip the scaling of X_train and X_test#sc = StandardScaler()#X_train = sc.fit_transform(X_train)#X_test = sc.transform(X_test)regr = linear_model.LinearRegression()regr.fit(X_train, y_train)y_pred = regr.predict(X_test)print('Coefficients: \n', regr.coef_)> Coefficients: [2.]print('Y-intercept: \n', regr.intercept_)> Y-intercept: 1.0