This code generates a graph of the regression line but the y-intercept taken from the LR model does not match the y-intercept on the graph. What am I missing? The script prints the y-intercept, taken from the model, as 152 but the graph shows it to be less than 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()
Ouptut of the script:
y-intercept:
152.91886182616167
CodePudding user response:
Your X axis goes negative so the intercept is correct at 0 in the middle of the graph.