What Is Linear Regression? Simple & Multiple Explained with Python Examples
// outline
Introduction
Linear Regression is one of the most important algorithms in data science and machine learning. Whether you are predicting house prices, analysing business trends, or studying scientific measurements, linear regression provides a simple, powerful, and interpretable way to understand patterns and make informed predictions.
In this guide you will learn how linear regression works, how to build a model on a real dataset, how to evaluate accuracy, and how to avoid common pitfalls like overfitting and multicollinearity — all with working Python code.
Build a Linear Regression Model in 12 Lines
Before diving into the theory, here is a complete end-to-end linear regression model predicting California house prices in under 12 lines:
// CALIFORNIA HOUSING DATASET
Predicts median_house_value from median_income. Download the CSV from Kaggle.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
df = pd.read_csv('housing.csv')
X = df[['median_income']].values
y = df['median_house_value'].values
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
model = LinearRegression().fit(X_train, y_train)
print("R² =", model.score(X_test, y_test)) # → 0.4589
plt.scatter(X_test, y_test, color='#6FB3F2', alpha=0.3, s=8)
plt.plot(X_test, model.predict(X_test), color='#F2A65A', linewidth=2)
plt.xlabel("Median Income"); plt.ylabel("House Value"); plt.show()
// an R² of 0.46 means median income explains about 46% of the variance in house price — a decent single-feature baseline.
What Is Linear Regression?
Linear regression is a supervised machine learning algorithm that predicts a continuous numeric output by finding the best-fit straight line through a scatter of data points. The core idea is to model the relationship between one or more input variables (features) and a target variable.
// the residuals (red dashed lines) are the vertical distances between each data point and the fitted line. The algorithm minimises the sum of their squares — the Least Squares Method.
Key Terms You Must Understand
The value being predicted — what the model outputs. Also called the target or response variable.
The input features used to make the prediction. Also called predictors or explanatory variables.
How much Y changes for every one-unit increase in X. A positive slope means Y increases with X.
The value of Y when X equals 0 — where the regression line crosses the vertical axis.
The difference between the actual Y value and the model's predicted value: residual = Y − Ŷ.
The method used to find the line that minimises the sum of squared residuals (SSR).
Types of Linear Regression
One independent variable (X) predicts one dependent variable (Y). Finds the best-fit straight line between two variables.
Example: predict salary from years of experience.
Two or more independent variables predict a single dependent variable. Finds the best-fit plane (or hyperplane) through the data.
Example: predict house price from area, bedrooms, and location.
How Linear Regression Works (Step by Step)
Collect Your Data
Gather your input features (X) and target values (Y). Each row is one observation, each column one variable.
Visualise with a Scatter Plot
Plot X against Y to check whether a roughly linear pattern exists. If the points form a straight band, linear regression is appropriate.
Apply the Algorithm
The algorithm finds the best-fit line using the formula Y = mX + c, where m is the slope and c is the intercept.
Train the Model
The Least Squares Method minimises the sum of squared residuals to find the optimal slope and intercept. In practice, sklearn handles this automatically.
Make Predictions
Feed new input values into the fitted model to generate predictions: Ŷ = model.predict(X_new).
Evaluate the Model
Measure performance on held-out test data using R², MAE, MSE, and RMSE. Check residual plots for patterns that signal assumption violations.
Assumptions of Linear Regression
Linear regression produces reliable results only when these six assumptions hold. Violating them does not stop the model from running — but it does make the output untrustworthy.
The relationship between X and Y must be linear. Check with scatter plots or residual plots.
Observations must be independent of each other. Violated by time-series data or clustered samples.
The variance of residuals should be constant across all values of X. Fan-shaped residual plots signal violation.
Residuals should be approximately normally distributed. Check with a Q-Q plot.
Independent variables must not be highly correlated with each other. Check with VIF (Variance Inflation Factor).
Extreme outliers disproportionately influence the fitted line. Use leverage plots to detect influential points.
Evaluation Metrics
Never judge a regression model by training performance alone. Always evaluate on a held-out test set using multiple metrics:
Proportion of variance in Y explained by the model. Ranges 0–1; higher is better. R² = 1 is a perfect fit.
Average absolute prediction error in the same units as Y. Robust to outliers — does not penalise large errors more than small ones.
Average squared error. Penalises large errors more heavily. Not in the same units as Y — harder to interpret directly.
Square root of MSE — back in the original units of Y. The most commonly reported metric for regression models.
Python Implementation
Simple Linear Regression — Salary vs Experience
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, root_mean_squared_error
# Example: Years of Experience → Salary
X = np.array([1,2,3,4,5,6]).reshape(-1,1)
Y = np.array([30000,35000,40000,45000,50000,55000])
model = LinearRegression().fit(X, Y)
Y_pred = model.predict(X)
print(f"Slope (m) : {model.coef_[0]:.0f}") # 5000
print(f"Intercept (b₀) : {model.intercept_:.0f}") # 25000
print(f"R² : {model.score(X, Y):.4f}") # 1.0
print(f"MAE : {mean_absolute_error(Y, Y_pred):.0f}")
plt.scatter(X, Y, color='#6FB3F2', label="Actual")
plt.plot(X, Y_pred, color='#F2A65A', label="Predicted")
plt.xlabel("Years of Experience"); plt.ylabel("Salary")
plt.title("Simple Linear Regression"); plt.legend(); plt.show()
Multiple Linear Regression — House Price Prediction
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_squared_error
# Features: [Area(sq ft), Bedrooms, Age]
X = np.array([
[1200,3,10],[1500,4,5],[1800,4,2],
[2400,5,1],[3000,5,20]
])
Y = np.array([200000,250000,300000,400000,450000])
model = LinearRegression().fit(X, Y)
Y_pred = model.predict(X)
print(f"Intercept (b₀) : {model.intercept_:.0f}")
print(f"Coefficients [b1,b2,b3]: {model.coef_}")
print(f"R² : {r2_score(Y, Y_pred):.4f}")
print(f"RMSE : {np.sqrt(mean_squared_error(Y,Y_pred)):.0f}")
# Actual vs predicted visualisation
plt.scatter(range(len(Y)), Y, color='#6FB3F2', label="Actual")
plt.plot(range(len(Y)), Y_pred, color='#5FD9B8', label="Predicted")
plt.xlabel("Sample No."); plt.ylabel("House Price")
plt.title("Multiple LR: Actual vs Predicted"); plt.legend(); plt.show()
Real-World Scenarios
Estimate property values for real estate platforms and mortgage lenders.
HR teams use this to benchmark compensation against market data.
Marketers model how budget allocation drives sales outcomes.
Clinical trials use regression to quantify treatment effects.
When Linear Regression Fails
Linear regression is powerful, but not universal. It will produce unreliable results in these situations:
Non-linear patterns — If the true relationship curves, bends, or follows an exponential pattern, a straight line is a poor fit. Use polynomial regression, decision trees, or neural networks instead.
Outliers — Extreme values exert disproportionate influence on the fitted line because the Least Squares loss squares the errors. Use robust regression or remove outliers after investigation.
Multicollinearity — Highly correlated input features make individual coefficients unstable and uninterpretable. Check with VIF and use Ridge or Lasso regularisation to mitigate.
Very small datasets — With too few samples, the model overfits noise. Use cross-validation to detect this early.
Classification problems — Linear regression predicts continuous values, not classes. Use Logistic Regression or other classifiers for yes/no outcomes.
Best Practices
Use high-quality data — garbage in, garbage out. Handle missing values before fitting.
Remove or investigate outliers — even a single extreme point can shift the regression line substantially.
Normalise features — StandardScaler or MinMaxScaler prevents features with large magnitudes from dominating the fit.
Keep only relevant variables — unnecessary features add noise. Use correlation analysis and VIF to prune.
Avoid multicollinearity — check pairwise correlations and VIF; drop or combine correlated predictors.
Always check residuals — plot residuals vs fitted values and a Q-Q plot to verify assumptions hold.
Validate on held-out test data — split before preprocessing and report metrics on the test set, not the training set.
Linear Regression vs Other Algorithms
| Feature | Linear Regression | Decision Trees | Neural Networks |
|---|---|---|---|
| Interpretability | High | Medium | Low |
| Training speed | Fast | Medium | Slow |
| Non-linear data | Poor | Good | Excellent |
| Overfitting risk | Medium | Medium | High |
| Best for | Trend & relationship analysis | Complex patterns | Deep learning tasks |
FAQs
What is linear regression in simple terms?
Linear regression is a method that draws the best possible straight line through a set of data points to predict a numeric outcome — for example, predicting salary from years of experience or house price from square footage.
What is the formula for simple linear regression?
Y = b₀ + b₁X, where b₀ is the intercept (the value of Y when X is 0) and b₁ is the slope (how much Y changes per one-unit increase in X).
What is the difference between simple and multiple linear regression?
Simple linear regression uses one independent variable (X) to predict Y. Multiple linear regression uses two or more independent variables (X₁, X₂, …, Xₙ) to predict a single dependent variable (Y).
What evaluation metrics are used for linear regression?
The four standard metrics are R² (proportion of variance explained), MAE (mean absolute error), MSE (mean squared error), and RMSE (root mean squared error). R² gives the overall fit; RMSE is the most commonly reported error metric.
When does linear regression fail?
It fails when the data has non-linear patterns, contains significant outliers, has highly correlated features (multicollinearity), is too small for reliable estimates, or when the target is a category rather than a continuous number.
What are the main assumptions of linear regression?
Linearity, independence of observations, homoscedasticity (constant residual variance), normality of errors, no multicollinearity between predictors, and no significant influential outliers.
Does linear regression require feature scaling?
It is not strictly required for predictions, but normalising features (StandardScaler or MinMaxScaler) improves numerical stability, makes coefficients comparable across features, and helps algorithms that use gradient descent converge faster.
Conclusion
Linear regression remains one of the most important and widely used algorithms in data science. Its simplicity, mathematical transparency, and efficiency make it ideal for regression problems, and understanding it deeply makes every more complex algorithm easier to learn.
The key takeaways: always check your assumptions, evaluate on test data with R², MAE, and RMSE, scale your features inside a Pipeline to prevent leakage, and treat linear regression as your first baseline before reaching for more complex models.
Khalid Hussain
Founder of Review Publically. Writes hands-on guides on data science, machine learning and AI tools, testing every model and library before recommending it.
// related reads