scikit-learn
Python
linear regression
intercept and slope
machine learning

How to print intercept and slope of a simple linear regression in Python with scikit-learn?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In scikit-learn, the intercept and slope of a simple linear regression model are available after fitting LinearRegression. The main details to remember are that X must be two-dimensional and that the slope is stored in coef_, which is still an array even when there is only one feature.

Fit a Simple Linear Regression Model

For simple linear regression, you have one input feature and one target value. Scikit-learn still expects X to have shape n_samples x n_features, so a single feature must be written as a column.

python
1import numpy as np
2from sklearn.linear_model import LinearRegression
3
4X = np.array([[1], [2], [3], [4], [5]], dtype=float)
5y = np.array([3, 5, 7, 9, 11], dtype=float)
6
7model = LinearRegression()
8model.fit(X, y)
9
10print("intercept:", model.intercept_)
11print("slope:", model.coef_[0])

In this example, the fitted line is close to y = 2x + 1, so the intercept prints near 1.0 and the slope prints near 2.0.

Understand Where the Values Live

After fitting, scikit-learn stores:

  • 'intercept_ for the constant term'
  • 'coef_ for the feature coefficients'

With one feature, coef_ contains a single value, so you usually print model.coef_[0]. With multiple features, coef_ contains one coefficient per feature.

python
print(type(model.intercept_))
print(model.coef_)

That is why a lot of examples look slightly inconsistent at first glance. The intercept is usually scalar, while the coefficients are array-like.

Write the Fitted Equation

Once you have the numbers, it is easy to print the regression equation itself.

python
1intercept = model.intercept_
2slope = model.coef_[0]
3
4print(f"y = {slope:.3f} * x + {intercept:.3f}")

That is often more useful than printing the raw attributes because it makes the result easier to interpret and report.

Plot the Data and Fitted Line

If you want to verify the result visually, plot the original points and the predicted line.

python
1import matplotlib.pyplot as plt
2
3predictions = model.predict(X)
4
5plt.scatter(X, y, label="data")
6plt.plot(X, predictions, color="red", label="fit")
7plt.xlabel("x")
8plt.ylabel("y")
9plt.legend()
10plt.show()

This is especially helpful when you want to confirm that the model is actually linear enough to justify printing a slope and intercept in the first place.

Why Shape Matters

One of the most common beginner errors is passing a one-dimensional array for X, like this:

python
X = np.array([1, 2, 3, 4, 5])

Scikit-learn will reject that because it expects a matrix, not a flat vector. The fix is to reshape:

python
X = X.reshape(-1, 1)

That one line solves a large percentage of "why does LinearRegression.fit fail" questions.

Multiple Features Change the Meaning

The title says simple linear regression, which means one feature. If you later add more predictors, the model still has one intercept_, but coef_ becomes a list of slopes, one per feature.

python
1X = np.array([
2    [1, 10],
3    [2, 20],
4    [3, 30],
5    [4, 40],
6], dtype=float)
7y = np.array([5, 9, 13, 17], dtype=float)
8
9model = LinearRegression().fit(X, y)
10print("intercept:", model.intercept_)
11print("coefficients:", model.coef_)

At that point, you are no longer talking about a single slope in the usual classroom sense. You are talking about one coefficient per feature.

Common Pitfalls

The biggest mistake is passing X as a one-dimensional array. Reshape it to (-1, 1) for a single feature.

Another common issue is printing model.coef_ directly and being surprised that it is an array. For simple linear regression, the slope is usually model.coef_[0].

People also sometimes print coefficients before calling fit, which fails because the attributes do not exist until the model has been trained.

Finally, remember that a slope and intercept describe the fitted line, not proof that the relationship is truly linear or causally meaningful.

Summary

  • Fit LinearRegression first, then read intercept_ and coef_.
  • In simple linear regression, the slope is usually model.coef_[0].
  • Keep X two-dimensional, even when you have only one feature.
  • Printing the fitted equation often makes the result easier to understand.
  • Use a plot when you want to sanity-check the regression visually.

Course illustration
Course illustration

All Rights Reserved.