Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the y-intercept from the model not match the graph?

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

Here is the graph. The y-intercept appears to be about 80.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your X axis goes negative so the intercept is correct at 0 in the middle of the graph.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading