matplotlib 为什么模型的y轴截距与图形不匹配?

tyg4sfes  于 2023-01-31  发布在  其他
关注(0)|答案(1)|浏览(158)

此代码生成回归线的图形,但从LR模型获取的y截距与图形上的y截距不匹配。我错过了什么?脚本将从模型获取的y截距打印为152,但图形显示它小于100。

# Adapted from https://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html#sphx-glr-auto-examples-linear-model-plot-ols-py

# Code source: Jaques Grobler
# License: BSD 3 clause

import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score

diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y = True)

diabetes_X = diabetes_X[:, np.newaxis, 2]   

diabetes_X_train = diabetes_X[:-20]
diabetes_X_test = diabetes_X[-20:]

diabetes_y_train = diabetes_y[:-20]
diabetes_y_test = diabetes_y[-20:]

regr = linear_model.LinearRegression()
regr.fit(diabetes_X_train, diabetes_y_train)

diabetes_y_pred = regr.predict(diabetes_X_test)

# The y-intercept
print("y-intercept: \n", regr.intercept_)

plt.scatter(diabetes_X_test, diabetes_y_test, color="black")
plt.plot(diabetes_X_test, diabetes_y_pred, color="blue", linewidth=3)
plt.xlabel('x')
plt.ylabel('y')

plt.show()

脚本的输出:

y-intercept: 
 152.91886182616167

jtw3ybtb

jtw3ybtb1#

您的X轴变为负值,因此截距正确地位于图形中间的0处。

相关问题