Lesson 14: Linear Regression — Predicting Numbers

Explain linear regression intuitively; fit a line to data using scikit-learn.

By • Last updated • 80 min

Linear Regression: Predicting Numbers

Linear Regression is one of the simplest yet most powerful algorithms. It's used when we want to predict a continuous number, such as the price of a house or tomorrow's temperature.

The Best Fit Line

Imagine a scatter plot of house sizes versus house prices. Linear regression tries to draw a straight line through these points that best captures the trend. The equation of this line is y = mx + b, where m is the slope (how much price increases per square foot) and b is the intercept.

The model "learns" by minimizing the distance between its line and the actual data points. This distance is measured using a loss function like Mean Squared Error (MSE).

Fit-a-Line Sandbox

Click on the graph to add data points (up to 20). Toggle between Auto-Fit and Manual Fit. Try to adjust the sliders to minimize the Mean Squared Error (MSE) and see the residual lines shrink!

0123456789100102030405060708090100Study Hours (X-Axis)Test Score % (Y-Axis)Study Hours: 1.5h Actual Score: 48% Predicted: 48.7% Residual: -0.7% (Click to delete)Study Hours: 3h Actual Score: 55% Predicted: 58.0% Residual: -3.0% (Click to delete)Study Hours: 4h Actual Score: 72% Predicted: 64.2% Residual: 7.8% (Click to delete)Study Hours: 5.5h Actual Score: 68% Predicted: 73.6% Residual: -5.6% (Click to delete)Study Hours: 7h Actual Score: 85% Predicted: 82.9% Residual: 2.1% (Click to delete)Study Hours: 8.5h Actual Score: 92% Predicted: 92.2% Residual: -0.2% (Click to delete)Study Hours: 9.5h Actual Score: 98% Predicted: 98.4% Residual: -0.4% (Click to delete)
💡 Hover on points to view details🔴 Click a point to remove it
Model Equationy = 6.21x + 39.42
Mean Squared Error15.07
Active Points7 / 20

Python Challenge: Fit the Line!

Use scikit-learn to train a linear regression model and predict a value.

from sklearn.linear_model import LinearRegression
import numpy as np

# Study hours (features) and test scores (labels)
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([50, 60, 70, 80, 90])

# TODO: Initialize and train the Linear Regression model
# model = ???
# model.???

# TODO: Predict the score for a student who studies 6 hours
# prediction = ???
# print(f"Predicted score: {prediction[0]}")

When you run this code, you'll see the model figures out that each hour of study adds 10 points to the score!

main.py
Run your code to see output here.