Simple Linear Regression with Scikit-Learn
Simple Linear Regression is one of the most fundamental algorithms in machine learning. It helps us understand the relationship between two variables and predict a numerical value using a straight line.
Imagine you're a company manager. You know how many years of experience an employee has, but you don't know their expected salary. Could you use information from other employees to make a reasonable prediction?
That's exactly what Simple Linear Regression does. It learns the relationship between two variables from existing data and uses that relationship to predict unknown values.
In this tutorial, you'll learn how it works, the simple math behind it, and how to build one in Python using Scikit-learn.
0. Where This Fits: Regression Models
Before learning Simple Linear Regression, let's understand where it belongs in machine learning.
Machine learning problems can involve predicting different kinds of things. For example:
- Predicting an employee's salary.
- Predicting tomorrow's temperature.
- Predicting the price of a house.
- Predicting whether an email is spam.
The first three examples involve predicting numerical values. The last one involves predicting a category.
This distinction gives us two important types of supervised learning:
| Type | What it predicts | Examples |
|---|---|---|
| Regression | Continuous numerical values | Salary, temperature, house price |
| Classification | Categories or classes | Spam or not spam, cat or dog |
Regression is the family of algorithms we use when we want to predict numerical values. Here's the family of regression algorithms we'll explore:
- Simple Linear Regression ← You are here
- Multiple Linear Regression
- Polynomial Regression
- Support Vector Regression (SVR)
- Decision Tree Regression
- Random Forest Regression
Each algorithm approaches prediction differently. We'll start with the simplest one and gradually explore more complex approaches.
1. What Is Simple Linear Regression?
Simple Linear Regression is a supervised machine learning algorithm that predicts a numerical value using one independent variable.
Let's understand this with an example. Imagine a company collects information about its employees. It records their years of experience and corresponding salaries.
Here's a small sample of that data:
| Years of Experience | Salary |
|---|---|
| 1 | 30,000 |
| 2 | 40,000 |
| 3 | 50,000 |
| 4 | 60,000 |
| 5 | 70,000 |
Look at the pattern:
- An employee with 1 year of experience earns 30,000.
- An employee with 2 years earns 40,000.
- An employee with 3 years earns 50,000.
As experience increases, salary also increases. This is a positive linear relationship because the two variables increase together in an approximately straight-line pattern.
Our goal is to teach a model this relationship so that it can predict the salary of someone whose experience we already know.
For example: What would be the predicted salary of an employee with 6 years of experience?
We don't have that information in our dataset, but perhaps we can estimate it using the existing pattern. That's where Simple Linear Regression comes in.
1.1 Understanding the Two Variables
In Simple Linear Regression, we work with two variables:
- Independent variable (X): The input variable we use to make predictions.
- Dependent variable (y): The target variable we want to predict.
In our salary example:
| Variable | Meaning | Example |
|---|---|---|
| X | Independent variable | Years of experience |
| y | Dependent variable | Salary |
Why are they called independent and dependent? The independent variable is the input we provide to the model. The dependent variable is the value we're trying to predict based on that input.
Memory trick: X is what you know; y is what you want to find out.
1.2 Visualizing the Relationship
A scatter plot helps us see how two numerical variables are related.
Each dot represents one employee:
- The horizontal axis (X-axis) represents years of experience.
- The vertical axis (Y-axis) represents salary.
If we plot our sample data, we'll see that the dots form a straight-line pattern. The goal of Simple Linear Regression is to find a straight line that represents this relationship as closely as possible.
2. The Mathematical Equation
Now that we understand the problem, let's see how Simple Linear Regression represents the relationship mathematically.
A straight line can be represented using this equation:
Don't let the mathematical symbols scare you. Let's understand each one.
| Symbol | Meaning | In our example |
|---|---|---|
| ŷ | Predicted value of y | Predicted salary |
| x | Input variable | Years of experience |
| b₀ | Intercept — where the line starts | Starting salary at 0 years |
| b₁ | Slope — how steep the line is | Salary increase per year |
2.1 Understanding the Intercept (b₀)
The intercept is the predicted value of y when x is zero. In our salary example, it represents the predicted salary of an employee with zero years of experience.
For example, if b₀ = 20,000, the model predicts: 0 years of experience → 20,000 salary.
Mathematically: ŷ = b₀ + b₁(0)
Since anything multiplied by zero is zero: ŷ = b₀
2.2 Understanding the Slope (b₁)
The slope tells us how much the predicted value of y changes when x increases by one unit.
In our salary example, suppose b₁ = 10,000. This means every additional year of experience increases the predicted salary by 10,000.
For example:
- 1 year → 10,000 increase from the intercept.
- 2 years → 20,000 increase.
- 3 years → 30,000 increase.
The slope also tells us the direction of the relationship:
| Slope | Relationship | Meaning |
|---|---|---|
| Positive (b₁ > 0) | Positive relationship | y increases as x increases |
| Negative (b₁ < 0) | Negative relationship | y decreases as x increases |
| Zero (b₁ = 0) | No linear change | Predicted y remains constant |
2.3 A Worked Example
Let's return to our salary example. Our data follows a perfect straight-line pattern. The equation of that line is:
ŷ = 20,000 + 10,000x
Therefore:
- b₀ = 20,000
- b₁ = 10,000
What does this tell us?
- At zero years of experience, the predicted salary is 20,000.
- Every additional year of experience increases the predicted salary by 10,000.
Let's make a prediction for someone with 5 years of experience.
ŷ = 20,000 + (10,000 × 5) = 70,000 ✓ (matches the table)
Now let's predict the salary for someone with 6 years of experience.
ŷ = 20,000 + (10,000 × 6) = 80,000
We now have an estimated salary even though our original dataset didn't contain an employee with 6 years of experience.
That's the basic idea behind regression: learning a relationship from existing data and using it to predict unknown numerical values.
Reality check: Our example is intentionally simple. Real-world data rarely follows a perfectly straight line. Actual observations usually scatter around the line, which means predictions won't always be exact. That's why we need an algorithm to find the best-fitting line.
2.4 Seeing It in Code
Let's visualize our example using Python.
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 2, 3, 4, 5])
y = np.array([30000, 40000, 50000, 60000, 70000])
plt.scatter(x, y, color="red", label="Actual data") # the actual data points
plt.plot(x, 20000 + 10000 * x, color="blue", label="Regression line") # our line
plt.title("Salary vs Experience (Toy Example)")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
plt.legend()
plt.show()The graph shows:
- Red dots: The actual observations from our dataset.
- Blue line: The straight line representing the relationship between experience and salary.
Notice how every red dot sits exactly on the blue line. That's because we deliberately created a dataset with a perfect linear relationship. But what happens when the data points don't sit perfectly on a straight line? That's what we'll explore next.
3. How Does the Algorithm Find the Best Line?
Imagine you have a scatter plot containing many data points. You could draw several different straight lines through the same plot. Some lines would pass close to most points, while others would be far away.
But how does the algorithm decide which line is the best? It needs a way to measure how well a line fits the actual data.
Simple Linear Regression commonly uses a method called Ordinary Least Squares (OLS).
The basic idea is:
- Draw a candidate straight line through the data.
- Use that line to predict the value of every observation.
- Compare each predicted value with its actual value.
- Calculate the difference between them.
- Square each difference.
- Add all the squared differences together.
The algorithm finds the line that makes this total as small as possible.
Let's understand each part.
3.1 Understanding Residuals
A residual is the difference between an actual value and the value predicted by our model.
The formula is: eᵢ = yᵢ − ŷᵢ
Where:
- eᵢ = Residual for observation i
- yᵢ = Actual value
- ŷᵢ = Predicted value
Let's look at an example:
| Actual Salary | Predicted Salary | Residual |
|---|---|---|
| 40,000 | 38,000 | 2,000 |
| 50,000 | 52,000 | −2,000 |
| 60,000 | 57,000 | 3,000 |
Let's calculate the first residual: 40,000 − 38,000 = 2,000. The model predicted 38,000, but the actual salary was 40,000. So the prediction was 2,000 too low.
Now look at the second observation: 50,000 − 52,000 = -2,000. The model predicted 52,000, but the actual salary was 50,000. So the prediction was 2,000 too high.
Therefore:
- Positive residual: The model predicted too low (underprediction).
- Negative residual: The model predicted too high (overprediction).
- Zero residual: The prediction was exactly correct.
A residual is simply the vertical distance between an actual data point and the regression line, with a sign indicating which side of the line the point is on.
Memory trick: Residual = Actual − Predicted.
3.2 Why Do We Square the Residuals?
Now imagine we have five residuals: 2,000, -2,000, 3,000, -1,000, 4,000
What happens if we simply add them? 2,000 − 2,000 + 3,000 − 1,000 + 4,000 = 6,000
The problem is that positive and negative errors can cancel each other out. We might end up with a small total even when individual predictions are quite far from their actual values.
To avoid this, we square every residual.
For example:
| Residual | Squared Residual |
|---|---|
| 2,000 | 4,000,000 |
| -2,000 | 4,000,000 |
| 3,000 | 9,000,000 |
| -1,000 | 1,000,000 |
| 4,000 | 16,000,000 |
Squaring gives us two benefits:
- All squared errors become non-negative, so they cannot cancel each other out.
- Larger errors receive a much bigger penalty than smaller errors.
For example:
- Error of 2 → Squared error of 4.
- Error of 5 → Squared error of 25.
- Error of 10 → Squared error of 100.
A mistake ten times larger produces a squared error one hundred times larger.
3.3 Sum of Squared Residuals (SSR)
Once we've squared every residual, we add them together. This is called the Sum of Squared Residuals (SSR).
The formula is: SSR = Σ (yᵢ − ŷᵢ)²
Where:
- yᵢ = Actual value
- ŷᵢ = Predicted value
- Σ = Add everything together
The algorithm tries to minimize this total. Think about it this way:
- A line with large prediction errors produces a large SSR.
- A line with small prediction errors produces a small SSR.
- The best-fitting line is the one with the smallest possible SSR.
This is the central idea behind Ordinary Least Squares.
3.4 How Does It Calculate the Best Slope and Intercept?
We've established that the algorithm needs to find the line with the smallest SSR. But how does it actually calculate the slope and intercept?
For Simple Linear Regression, OLS has a direct mathematical solution. The formulas are:
- b₁ = Σ (xᵢ − x̄)(yᵢ − ȳ) / Σ (xᵢ − x̄)²
- b₀ = ȳ − b₁x̄
Let's understand the symbols:
| Symbol | Meaning |
|---|---|
| xᵢ | An individual X value |
| yᵢ | An individual y value |
| x̄ | Average of all X values |
| ȳ | Average of all y values |
| Σ | Sum of the calculated values |
You don't need to memorize these formulas right now. The important thing is to understand that the algorithm calculates the slope and intercept using the relationship between the input and target values.
Let's verify these formulas using our salary example.
| X (Experience) | y (Salary) |
|---|---|
| 1 | 30,000 |
| 2 | 40,000 |
| 3 | 50,000 |
| 4 | 60,000 |
| 5 | 70,000 |
First, calculate the averages:
x̄ = (1 + 2 + 3 + 4 + 5) / 5 = 3
ȳ = (30,000 + 40,000 + 50,000 + 60,000 + 70,000) / 5 = 50,000
Now calculate the numerator of the slope formula: Σ[(xᵢ − x̄)(yᵢ − ȳ)]
= (-2 × -20,000) + (-1 × -10,000) + (0 × 0) + (1 × 10,000) + (2 × 20,000)
= 40,000 + 10,000 + 0 + 10,000 + 40,000
= 100,000
Next, calculate the denominator: Σ(xᵢ − x̄)² = (-2)² + (-1)² + 0² + 1² + 2² = 4 + 1 + 0 + 1 + 4 = 10
Now calculate the slope: b₁ = 100,000 / 10 = 10,000
Finally, calculate the intercept: b₀ = ȳ − b₁x̄ = 50,000 − (10,000 × 3) = 20,000
We get the same equation: ŷ = 20,000 + 10,000x
That's how Ordinary Least Squares calculates the best-fitting line for this example.
Good news: You don't need to calculate these values manually in real projects. Scikit-learn handles the calculations for you. But understanding what's happening underneath helps you understand what the model is actually learning.
4. Understanding the Dataset
Now that we understand the mathematical foundation, let's move to a real dataset. We'll use a dataset called slr-salary-data.csv. It contains information about employees, including:
- 30 observations: Each row represents one employee.
- One independent variable: Years of Experience.
- One dependent variable: Salary.
Our goal is to train a model using this historical data and predict salaries for employees with different years of experience.
Before writing the code, let's understand a few terms:
- Dataset: A collection of data used for machine learning.
- Observation: One individual record or row in the dataset.
- Feature: An input variable used by the model to make predictions.
- Target: The variable the model is trying to predict.
In our example, Years of Experience is the feature, and Salary is the target.
5. Building Simple Linear Regression in Python
Now let's implement everything using Python and Scikit-learn. We'll follow these steps:
- Import the libraries.
- Load the dataset.
- Separate the input and target variables.
- Split the data into training and test sets.
- Train the model.
- Make predictions.
- Evaluate the model.
Step 1: Import the Libraries
First, let's import the libraries we'll need.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pdWhat does each library do?
- NumPy: Helps us work with numerical data and mathematical operations.
- Pandas: Helps us load, organize, and manipulate datasets.
- Matplotlib: Helps us create graphs and visualize data.
We'll also use Scikit-learn to build and evaluate our machine learning model.
Step 2: Load the Dataset
First, download the dataset we'll use throughout this tutorial: Download slr-salary-data.csv
If you're using Google Colab with Google Drive, download the CSV file and upload it to your Google Drive. For this example, we'll assume you've uploaded it to the Colab Notebooks folder.
First, connect your Google Drive:
from google.colab import drive
drive.mount('/content/drive')Now load the CSV file:
PATH = "/content/drive/MyDrive/Colab Notebooks/slr-salary-data.csv"
dataset = pd.read_csv(PATH)
dataset.head()What's happening here:
pd.read_csv()reads the CSV file and loads it into a Pandas DataFramedataset.head()shows the first five rows so you can check it loaded correctly.
A DataFrame is simply a table containing rows and columns, similar to an Excel spreadsheet.
If you're running Python locally, you can skip the Google Drive mounting step and provide the path to your CSV file directly.
Step 3: Separate the Input and the Target
Our dataset contains two columns:
- Years of Experience: The input feature.
- Salary: The target we want to predict.
We need to separate them before training the model.
target_column = "Salary"
X = dataset.drop(columns=[target_column]).values
y = dataset[target_column].valuesLine by line:
dataset.drop(columns=[target_column])removes the Salary column, leaving just Years of Experience..valuesconverts that table into a NumPy array (a plain list of numbers Python can work with easily).ystores the Salary values.
Now you have two arrays: X (the input) and y (the answer we want to predict).
Step 4: Split Into Training and Test Sets
This is one of the most important steps in machine learning. Before training the model, we divide our dataset into two parts:
- Training set: The data used to teach the model.
- Test set: The data used to evaluate how well the model performs on previously unseen observations.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=0
)| Parameter | What it does |
|---|---|
X |
The input variable |
y |
The target variable |
test_size=0.2 |
Keeps 20% of the data for testing |
random_state=0 |
Makes the random split the same every time you run it |
With 30 observations, we get 24 for training (80%) and 6 for testing (20%).
Let's check the resulting shapes:
print(X_train.shape, y_train.shape)
print(X_test.shape, y_test.shape)Expected output:
(24, 1) (24,)
(6, 1) (6,)
Why is X_train two-dimensional? Scikit-learn expects features in the shape (number_of_rows, number_of_columns). Even with a single feature, X must stay 2D. This trips up a lot of beginners — just remember: X is always a table, y is always a single column.
Step 5: Train the Model
Now comes the actual machine learning part. We'll use Scikit-learn's LinearRegression class.
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)LinearRegression()creates an empty model — like buying a blank notebook.fit()trains it — the model finds the best intercept and slope by minimizing the sum of squared residuals.
Let's See What the Model Learned
After training, we can access the learned parameters:
print("Intercept:", regressor.intercept_)
print("Coefficient:", regressor.coef_)These two numbers are your trained equation: ŷ = b₀ + b₁x. That's the entire model.
Step 6: Predict on the Test Set
Our model has learned the relationship between experience and salary. Now let's see how well it predicts salaries for observations it hasn't seen before.
y_pred = regressor.predict(X_test)
y_predThe predict() method takes input values and returns predicted salaries. Now compare predictions with the actual values:
comparison = pd.DataFrame({
"Actual Salary": y_test,
"Predicted Salary": y_pred
})
comparisonSince the test data wasn't used during training, this comparison shows how well the model generalizes — how it handles new, unseen data.
Step 7: Make a Single Prediction
Remember our original question: what's the predicted salary for someone with 6 years of experience?
regressor.predict([[6]])Watch the double square brackets! predict() expects a 2D input, just like fit(). [6] gives you an error; [[6]] works.
Step 8: Evaluate the Model
We've trained the model and made predictions. But how do we know whether it's performing well? Looking at a comparison table is useful, but we also need numerical metrics to measure prediction errors.
For regression, three commonly used metrics are:
- Mean Squared Error (MSE).
- Root Mean Squared Error (RMSE).
- R-squared (R²).
Let's calculate them using Scikit-learn.
from sklearn.metrics import mean_squared_error, r2_score
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)
print("MSE:", mse)
print("RMSE:", rmse)
print("R-squared:", r2)Here's what each metric means:
- MSE (Mean Squared Error): MSE measures the average of the squared differences between actual and predicted values. Lower is better, but the units are "salary squared," which is hard to interpret.
- RMSE (Root Mean Squared Error): Simply the square root of MSE. This is in the same units as salary, so it reads as "typical prediction error." If RMSE is 5,000, your model is typically off by about 5,000. A lower RMSE generally indicates better predictions.
- R-squared: Measures how much of the variation in salary the model explains. 1.0 = perfect fit, 0.0 = no better than guessing the average. Higher is better.
Beginner tip: If you only remember one metric, remember R-squared. It's the most intuitive — "my model explains X% of the variation in salary."
6. Visualizing the Results
Numbers are useful, but pictures are often clearer. Let's make two plots: one for training data and one for test data.
Training Set
plt.scatter(X_train, y_train, color="red")
plt.plot(X_train, regressor.predict(X_train), color="blue")
plt.title("Salary vs Experience (Training Set)")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
plt.show()- Red dots: the actual training observations.
- Blue line: the line the model learned.
Test Set
plt.scatter(X_test, y_test, color="red")
plt.plot(X_train, regressor.predict(X_train), color="blue")
plt.title("Salary vs Experience (Test Set)")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
plt.show()- Red dots: the actual test observations (data the model never saw during training).
- Blue line: the same line from the training plot.
Important: We deliberately keep the same line — we don't train a new model on the test set. The point of a test set is to see how the existing line fits points it hasn't seen. If the red test dots sit close to the line, the model generalizes well. If they're scattered far away, the model doesn't generalize.
7. The Complete Workflow
Here's the entire process in seven simple steps:
- Load the data: Read the CSV file using Pandas.
- Separate X and y: Identify the input features and target variable.
- Split the data: Keep separate training and test sets.
- Train the model: Use
fit()to learn the slope and intercept. - Make predictions: Use
predict()on unseen data. - Evaluate: Calculate MSE, RMSE, and R-squared.
- Visualize: Compare the actual points with the fitted line.
That's it. Every regression project follows roughly this same recipe.
8. Key Concepts at a Glance
| Concept | What it means |
|---|---|
| Independent variable (X) | The input feature |
| Dependent variable (y) | The target we want to predict |
| Intercept (b₀) | Predicted y when x is zero |
| Slope (b₁) | Change in y for a one-unit increase in x |
| Residual | Actual value minus predicted value |
| OLS | The method that finds parameters minimizing squared residuals |
fit() |
Trains the model |
predict() |
Generates predictions |
| Training set | Data used to learn the model |
| Test set | Data used to evaluate the model |
| R-squared | Share of variation in y the model explains |
9. Assumptions and Limitations
Simple Linear Regression is easy to understand and implement, but it doesn't work equally well for every dataset. Before relying on a linear regression model, we should understand its assumptions and limitations.
9.1 Core Assumptions
- Linearity: the relationship between X and y is roughly a straight line. If the data curves, a straight line won't fit well.
- Independence: the errors (residuals) are independent of each other. One prediction's error shouldn't tell you about another's.
- Constant variance (homoscedasticity): the spread of residuals is roughly the same across all values of X. (Don't worry about the fancy name — it just means "errors are equally scattered everywhere.")
- Normally distributed residuals: the residuals roughly follow a bell curve. This mainly matters for confidence intervals and hypothesis tests, not for basic predictions.
9.2 Limitations
- Only one input variable: it uses a single feature to predict the target.
- Sensitive to outliers: a single extreme point can pull the whole line off course.
- Extrapolation risk: predictions outside the range of your training data may be unreliable. If your data covers 1–10 years of experience, don't trust a prediction for 40 years.
- Correlation ≠ causation: just because two variables move together doesn't mean one causes the other. Ice cream sales and shark attacks rise together — but ice cream doesn't cause shark attacks.
9.3 When Should We Use Another Regression Algorithm?
Different regression algorithms are designed to handle different types of relationships.
| Situation | Algorithm to Explore |
|---|---|
| One input variable with an approximately linear relationship | Simple Linear Regression |
| Multiple input variables with a linear relationship | Multiple Linear Regression |
| A curved relationship | Polynomial Regression |
| A flexible model with a margin-based approach | Support Vector Regression |
| Non-linear patterns using decision rules | Decision Tree Regression |
| More robust predictions using multiple decision trees | Random Forest Regression |
We'll explore these algorithms in the upcoming tutorials.
10. Final Takeaways
You've now learned Simple Linear Regression, from the basic intuition and mathematics to implementing and evaluating a model in Python. Here are the key points to remember:
- It predicts a continuous number using one input variable.
- It represents the relationship with a straight-line equation (ŷ = b₀ + b₁x).
- It learns the intercept and slope using Ordinary Least Squares (minimizing squared residuals).
- Residuals measure the gap between actual and predicted values.
- Training data teaches the model; test data checks how well it learned.
- Scikit-learn makes it easy with just three tools:
LinearRegression(),fit(), andpredict().
The big idea: Simple Linear Regression finds the best-fitting straight line through historical data and uses that line to predict unknown numbers.
Next up: Multiple Linear Regression
Simple Linear Regression uses one input variable to make predictions. But what if an employee's salary depends on several factors, such as experience, education, and job position?
That's where Multiple Linear Regression comes in. It follows the same fundamental idea but uses multiple input variables instead of just one.