How does a company decide how much to spend on advertising, or an agent price a house? Often the tool behind the decision is simple linear regression — a way to describe and predict the relationship between two variables. Think of it as finding the thread that ties advertising spend () to sales ().
Mathematically, that relationship looks like this:
Where:
| Symbol | Meaning |
|---|---|
| Independent variable | |
| Dependent variable | |
| β₀ | Intercept (value of when = 0) |
| β₁ | Slope (how much changes for each unit change in ) |
| ε | Error term |
What Linear Regression Is For#
It does two jobs:
- Verify a relationship — prove statistically whether two variables are actually related, and measure how strong that link is. Does education level really affect income?
- Predict — estimate future values from past data. If we raise the ad budget by , how much more do we sell ()?
Calculating Linear Regression#
Say we want the relationship between advertising cost () and sales (), with this data:
| Advertising Cost | Units |
|---|---|
| 100 | 500 |
| 200 | 700 |
| 300 | 900 |
| 400 | 1100 |
| 500 | 1300 |
To fit the line we need two numbers: the slope and the intercept .
Calculating the Slope ()#
The slope is how much moves for each change in :
Where:
| Symbol | Meaning |
|---|---|
| Individual values of the independent variable | |
| Individual values of the dependent variable | |
| Mean of the independent variable | |
| Mean of the dependent variable |
Start with the two means:
Now the numerator — each :
And the denominator — each :
A slope of 2 means every extra unit of cost () brings 2 more units of sales ().
Calculating the Intercept ()#
With the slope in hand, the intercept is:
Where:
| Symbol | Meaning |
|---|---|
| Mean of the dependent variable | |
| Mean of the independent variable | |
| Slope |
So when advertising cost is 0, predicted sales are 300 units. Put the slope and intercept together and we get the regression line:
To predict, just plug in a value. How many sales from spending 250 on ads?
So 250 in ad spend predicts 800 units. Plotted, the line and the five data points look like this:
Here's the same calculation as a program:
// Sales and advertising data
const sales_data = {
advertising_cost: [100, 200, 300, 400, 500],
units_sold: [500, 700, 900, 1100, 1300]
};
// Calculate average of array
function calculate_mean(data) {
return data.reduce((total, value) => total + value, 0) / data.length;
}
// Calculate slope (β₁) from data
function calculate_slope(data) {
const mean_x = calculate_mean(data.advertising_cost);
const mean_y = calculate_mean(data.units_sold);
let numerator = 0;
let denominator = 0;
// Calculate numerator and denominator for slope formula
for (let i = 0; i < data.advertising_cost.length; i++) {
const diff_x = data.advertising_cost[i] - mean_x;
const diff_y = data.units_sold[i] - mean_y;
numerator += diff_x * diff_y;
denominator += diff_x * diff_x;
}
return numerator / denominator;
}
// Calculate intercept (β₀) from data
function calculate_intercept(data, slope) {
const mean_x = calculate_mean(data.advertising_cost);
const mean_y = calculate_mean(data.units_sold);
return mean_y - (slope * mean_x);
}
// Predict units sold based on advertising cost
function predict_sales(advertising_cost, slope, intercept) {
return intercept + (slope * advertising_cost);
}
// Calculate regression
const slope = calculate_slope(sales_data);
const intercept = calculate_intercept(sales_data, slope);
// Display results
console.log(`Slope (β₁): ${slope}`); // output: 2
console.log(`Intercept (β₀): ${intercept}`); // output: 300
// Example prediction
const new_cost = 250;
const prediction = predict_sales(new_cost, slope, intercept);
console.log(`${prediction} units`);
Classical Assumptions of Linear Regression#
Regression only holds up if a few assumptions do. Worth checking before you trust the result:
- Linearity. The relationship between and should be roughly a straight line. A scatter plot is the quick check — if the points curve instead, transform the data first (a log or square root often helps).
- Independence. Each observation should stand on its own. This bites most with time-series data: today's sales shouldn't depend on yesterday's. Autocorrelation (checked with an ACF plot or the Durbin-Watson test) biases the results.
- Homoscedasticity. The spread of the errors should stay constant across all values of — prediction error shouldn't be tiny for cheap ad spend and huge for expensive. Plot the residuals against predicted values; a funnel shape means the assumption fails.
- Normality. The residuals should follow a normal distribution — a symmetrical bell when you histogram them. This matters most for hypothesis tests and confidence intervals. Check with a Q-Q plot, or a formal test like Shapiro-Wilk.
Testing the Fit with R²#
How well does the line actually explain the data? That's what the coefficient of determination, , measures:
Where:
| Symbol | Meaning |
|---|---|
| Actual value | |
| Predicted value | |
| Mean of actual values |
runs from 0 to 1 and tells you the share of the variation in the model captures — multiply by 100 to read it as a percentage. To compute it, we need the predicted values, the total sum of squares, and the residual sum of squares.
Predicted Values ()#
Run each through :
| Advertising Cost () | Units () | (predicted) |
|---|---|---|
| 100 | 500 | 300 + 2(100) = 500 |
| 200 | 700 | 300 + 2(200) = 700 |
| 300 | 900 | 300 + 2(300) = 900 |
| 400 | 1100 | 300 + 2(400) = 1100 |
| 500 | 1300 | 300 + 2(500) = 1300 |
Total Sum of Squares ()#
This is the spread of the actual values around their mean, :
Residual Sum of Squares ()#
This is what the model misses — the gap between actual and predicted, :
Putting It Together#
An of 1 means:
- the model explains 100% of the variation in the data,
- every point lies exactly on the line, and
- predictions are perfect for this data.
That happens here because the data is perfectly linear — every residual is zero. Real-world data almost never lands this cleanly. Here's the calculation in code:
// Calculate coefficient of determination (R²)
function calculate_r_squared(data, slope, intercept) {
const mean_y = calculate_mean(data.units_sold);
let ss_total = 0; // Sum of squares total
let ss_residual = 0; // Sum of squares residual
for (let i = 0; i < data.advertising_cost.length; i++) {
const y_predicted = intercept + (slope * data.advertising_cost[i]);
const y_actual = data.units_sold[i];
ss_total += Math.pow(y_actual - mean_y, 2);
ss_residual += Math.pow(y_actual - y_predicted, 2);
}
return 1 - (ss_residual / ss_total);
}
// Usage
const r_squared = calculate_r_squared(sales_data, slope, intercept);
console.log(`R² (Coefficient of Determination): ${r_squared.toFixed(4)}`); // Output: 1.0000