Machine Learning with scikit-learn

Linear Regression in Python with scikit-learn

Fit the best straight line through your data, read its slope and intercept, and predict new values.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • LinearRegression fit and predict
  • coef_ and intercept_
  • Measuring the fit with R^2 and MAE
Hours studied to score
  1. 1hours = 9New input
  2. 24.48 x 9 + 46.86Slope times input plus intercept
  3. 387.1Predicted score

The best straight line

The problem

You have pairs of measurements (hours studied and exam score, size and price) and want to know how one changes with the other, and to predict values you did not measure.

Think of it like this

Linear regression is like laying a ruler across a scatter of points so it passes as close as possible to all of them. The ruler's tilt is the slope, where it crosses zero is the intercept, and reading off the ruler gives a prediction.

From a ruler on a chart to code
model.fit(hours, scores)📏 Lay the ruler through the points
model.coef_↗️ The tilt: 4.48 points per hour
model.intercept_📍 Where the ruler starts: 46.86
model.predict([[9]])🔮 Read a new value off the ruler
The line that is closest to all the points.
In one sentence

Linear regression models the target as a weighted sum of the features plus a constant, choosing the weights that make the squared errors as small as possible.

Key points

  1. hours must be 2D (one row per sample, one column per feature); scores is 1D.
  2. The fitted line is score = 4.48 x hours + 46.86.
  3. r2_score of 0.992 means the line explains almost all of the variation.
  4. mean_absolute_error says predictions are 0.82 points off on average.

When should you use it?

  • Predicting a number: price, score, temperature, sales.
  • Measuring how strongly one variable changes with another.
  • A simple baseline before trying more complex models.

When not to use it

  • Clearly curved relationships: add polynomial features or use another model.
  • Yes/no targets: use logistic regression.

Example code

Open in editor →
main.py
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score

# Hours studied and exam score for 8 students
hours = np.array([[1], [2], [3], [4], [5], [6], [7], [8]])
scores = np.array([52, 55, 61, 64, 70, 72, 79, 83])

model = LinearRegression()
model.fit(hours, scores)

print(f"Slope (coef_):  {model.coef_[0]:.2f} points per hour")
print(f"Intercept:      {model.intercept_:.2f}")

predicted = model.predict(hours)
print(f"R^2:            {r2_score(scores, predicted):.3f}")
print(f"MAE:            {mean_absolute_error(scores, predicted):.2f} points")

new_students = np.array([[2.5], [9]])
for h, p in zip(new_students.ravel(), model.predict(new_students)):
    print(f"{h} hours -> predicted score {p:.1f}")
Get a Run button for this example

Result of running the code

Slope (coef_):  4.48 points per hour
Intercept:      46.86
R^2:            0.992
MAE:            0.82 points
2.5 hours -> predicted score 58.0
9.0 hours -> predicted score 87.1

Code explanation

hours is a 2D array with one column because scikit-learn always expects rows and columns of features, and scores holds the targets. fit finds the line score = 4.48 x hours + 46.86, stored in coef_ and intercept_. r2_score of 0.992 means the line explains almost all of the variation, and mean_absolute_error says predictions are off by 0.82 points on average. predict then gives 58.0 for 2.5 hours and 87.1 for 9 hours, which is outside the measured range, so treat it with care.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Run in the Python compiler →

Common mistakes

Passing a 1D array as the features

scikit-learn expects a 2D array of features and raises an error for a flat list.

Problem
model.fit([1, 2, 3], [52, 55, 61])
Fix
model.fit([[1], [2], [3]], [52, 55, 61])

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges

Tools for this lesson