edSlash Labs  /   Machine Learning Lab   /   Supervised Learning  /   Linear Regression
Algorithm 01 · Supervised learning · Regression

Linear Regression

Learn how a machine finds a straight line that best describes the relationship between two numerical values, then use that line to make predictions.

Beginner friendly

The big idea

Find the line that stays as close as possible to the data points.

ŷ = mx + bprediction = slope × input + intercept

Imagine you know how many hours students study and their exam marks. Linear Regression learns a line from past examples. You can then use that line to estimate marks for a new number of study hours.

At a glance

What kind of problem does it solve?

Input

One or more numerical features, such as study hours.

Output

A number, such as a predicted exam score.

Learning style

Supervised: training examples include the correct answers.

Model shape

A straight line for one input feature.

1. How does it work?

Think of each dot as one real observation.

From examples to a prediction

The blue dots are students from earlier exams. The line is the model's best estimate of the relationship between study time and marks.

Study hours (input X)Exam marks (output Y)0100100
Observed dataFitted line

The model tries to do three things

Look at the training data

It studies pairs of inputs (X) and known outputs (Y).

Find the line

It chooses a slope and intercept that make prediction errors small.

Predict new values

Put a new X into the equation to estimate Y.

Remember: The line shows a pattern in the data. It does not prove that X causes Y.

2. Live Linear Regression Playground

Change the data and watch the line, equation, and model scores update.

Interactive experiment

Scatter plot and best-fit line

Click inside the graph to add a new data point.

Data pointsRegression lineResidual error
Tip: Try adding an outlier. Notice how one unusual point can pull the fitted line toward itself.

Experiment controls

Start with sample data or build your own.

Choose 3 to 1,000 points
ŷ = —Model equation
Slope (m)—Line direction
Intercept (b)—Starting value
R² score—Fit score
Data points—Training examples
Your prediction will appear here.
Dataset ready.

Data table

Observed values and the model's predicted values.

0 rows
#XActual YPredicted ŶResidual

3. The mathematics behind the line

Let's understand where the slope and intercept come from.

The prediction equation

ŷ = mx + b
  • ŷ (y-hat): the value predicted by the model.
  • x: the input feature.
  • m: slope; how much the prediction changes when X increases by 1.
  • b: intercept; the predicted value when X is 0.
Example: if ŷ = 5x + 20, every extra hour of study adds 5 predicted marks. At zero hours, the model predicts 20 marks.

How ordinary least squares finds the line

The model chooses m and b to make the total squared prediction error as small as possible.

SSE = Σ (yᵢ − ŷᵢ)²

For one input feature, the formulas are:

m = Σ[(xᵢ − x̄)(yᵢ − ȳ)] / Σ[(xᵢ − x̄)²]
b = ȳ − m x̄

x̄ is the mean of X values. ȳ is the mean of Y values. These formulas describe simple linear regression with one input feature.

What is a residual?

A residual is the difference between the actual value and the predicted value.

Residual = Actual Y − Predicted Ŷ

If a student's actual mark is 78 and the model predicts 72, the residual is +6. A positive residual means the model predicted too low. A negative residual means it predicted too high.

4. Numerical worked example

Calculate a small model by hand before using a library.

Study hours and exam marks

For this teaching example, use these four observations.

StudentHours (X)Marks (Y)
A12
B23
C35
D44
Mean X = 2.5 and mean Y = 3.5.

Step-by-step result

Find the slope

Numerator = 4.0; denominator = 5.0; therefore m = 0.8.

Find the intercept

b = 3.5 − (0.8 × 2.5) = 1.5.

Write the model

Predicted marks = 0.8 × study hours + 1.5.

Predict for 5 hours

ŷ = (0.8 × 5) + 1.5 = 5.5.

The prediction is 5.5 in this small example's mark scale. The key lesson is how to use the learned line.

5. How do we evaluate the model?

A line can look good but still make poor predictions. We need measurements.

Mean Absolute Error (MAE)

MAE = mean(|y − ŷ|)

Average size of the errors. It is easy to explain and uses the same units as Y. Smaller is better.

Mean Squared Error (MSE)

MSE = mean((y − ŷ)²)

Squares each error, so large mistakes count much more. Smaller is better.

Root Mean Squared Error (RMSE)

RMSE = √MSE

Like MSE, but returns to the same units as Y. Smaller is better.

R-squared (R²)

R² = 1 − SSE / SST

Shows how much of the variation in Y is explained by the model, compared with predicting the mean. Higher is usually better, but it is not proof of a good model.

Important: Check performance on data the model did not train on. A model can fit training data well and still perform badly on new data.

6. Python implementation

Use scikit-learn to train a Linear Regression model.

Simple Linear Regression with scikit-learn

Copy this example into a Python notebook.

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split

# X must be 2D: rows are examples, columns are features
X = np.array([[1], [2], [3], [4], [5], [6]])
y = np.array([2, 3, 5, 4, 6, 7])

# Keep some examples aside for testing
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.33, random_state=42
)

# Create and train the model
model = LinearRegression()
model.fit(X_train, y_train)

# Make predictions on unseen test examples
y_pred = model.predict(X_test)

print("Slope:", model.coef_[0])
print("Intercept:", model.intercept_)
print("Predictions:", y_pred)
print("MAE:", mean_absolute_error(y_test, y_pred))
print("MSE:", mean_squared_error(y_test, y_pred))
print("R2:", r2_score(y_test, y_pred))

# Predict for a new input: 7 study hours
print("New prediction:", model.predict([[7]])[0])

Install the libraries if needed: pip install numpy scikit-learn. This example uses a train/test split so the evaluation is not done on the same rows used for training.

7. Real-life applications

Places where predicting a number can be useful.

House price estimation

Estimate price from size, while remembering that real prices depend on many other things too.

Sales forecasting

Estimate sales from advertising spend or another useful business measure.

Energy use

Estimate electricity use from temperature or operating hours.

Education analysis

Explore how study time relates to exam scores.

Use Linear Regression when a roughly straight-line relationship is a sensible starting point. If the pattern bends or has complex groups, another model may work better.

8. Knowledge check

Answer one question at a time. Your score and explanations will appear after the final question.

0 of 10 answered

Mini challenge

Use the playground. Generate a positive dataset, then increase the noise. Watch what happens to R². Next, add an outlier and observe how the line changes.

Can you explain why the model becomes less certain when the points are spread farther from the line?