Linear Regression Overview
Linear Regression
Need for Regression Analysis
Regression analysis helps understand the relationship between two or more variables by creating a predictive model. In a typical scenario, one variable is identified as the dependent variable (the target to predict) and one or more variables as independent variables (the predictors). For example, to predict a student’s GRE score from their CGPA, the GRE score is the dependent variable and CGPA is the independent variable.
A scatter plot can reveal whether a linear relationship exists. If the points trend upward (as CGPA increases, GRE increases), there is a positive correlation. However, a scatter plot alone cannot give an exact prediction for a specific input value. Regression analysis provides a mathematical equation to estimate the dependent variable for any given independent variable.
Simple Linear Regression
Simple linear regression models the relationship between one dependent variable (y) and one independent variable (x) using a straight line:
or equivalently
where:
β0 (or c) is the intercept – the value of y when x=0.
β1 (or m) is the slope – the change in y for a one‑unit change in x.
The dependent variable must be continuous numerical. The goal is to find the line that best fits the observed data points.
Residuals and Best Fit Line
A residual is the difference between an actual observed value (yi) and the value predicted by the line (y^i):
To determine the best fit line, the Residual Sum of Squares (RSS) is minimized:
The line with the smallest RSS is called the best fit line. This is the line that passes as close as possible to all data points. The process of finding the optimal slope and intercept is done using optimization methods such as gradient descent.
Key Definition: The best fit line minimizes the sum of squared residuals, thereby maximizing the model’s ability to explain the variability in the dependent variable.
Example: Predicting GRE Score from CGPA
Given a scatter plot of GRE vs. CGPA, the best fit line might have coefficients:
slope β1=6.8
intercept β0=261
For a student with CGPA = 8.32, the predicted GRE score is:
Multiple Linear Regression
When there are two or more independent variables, the model becomes multiple linear regression:
This equation represents a hyperplane in p‑dimensional space. Each coefficient βj quantifies the change in y for a one‑unit change in xj, holding all other variables constant.
Example: Predicting Diamond Price
Consider predicting diamond price from features like carat, length, width, and depth. The model might be:
Multiple linear regression allows using several predictors simultaneously to improve prediction accuracy.
Model Evaluation Metrics
Once a model is built, its performance must be assessed. Key metrics include:
R‑squared (R2)
R2 measures the proportion of variance in the dependent variable that is explained by the model:
SSres=∑(yi−y^i)2 (residual sum of squares)
SStot=∑(yi−yˉ)2 (total sum of squares)
R2 ranges from 0 to 1. A value close to 1 indicates that the model explains most of the variability in the target.
Adjusted R‑squared
Adding irrelevant predictors artificially inflates R2. Adjusted R2 penalizes the inclusion of useless variables:
where n is the number of observations and p is the number of predictors. Adjusted R2 can decrease when unnecessary variables are added, making it a more reliable metric for model selection.
Root Mean Squared Error (RMSE)
RMSE gives the average prediction error in the same units as the dependent variable:
Lower RMSE indicates better predictive accuracy. Comparing RMSE across different models helps choose the best one.
Core Assumptions of Linear Regression
For the model to produce reliable coefficient estimates and valid inferences, several assumptions must hold:
Linearity – The relationship between each independent variable and the dependent variable is linear.
Independence of Errors – Residuals are not correlated with each other (e.g., no autocorrelation in time series).
Homoscedasticity – The variance of residuals is constant across all levels of the independent variables.
Normality of Residuals – For hypothesis testing and confidence intervals, residuals should be approximately normally distributed.
No Multicollinearity – Independent variables are not highly correlated with each other.
No or Little Measurement Error – The predictors are measured accurately.
Violations of these assumptions can lead to biased estimates, inflated standard errors, and poor predictions. Diagnostic plots (residuals vs. fitted, Q‑Q plot) are used to check them.
The Correlation Coefficient (r)
Before building a model, it is useful to examine the strength of linear relationships between pairs of variables using Pearson’s correlation coefficient r:
Range: −1≤r≤1.
r=1: perfect positive linear relationship.
r=−1: perfect negative linear relationship.
r=0: no linear correlation (but a nonlinear relationship may exist).
Variables with ∣r∣ close to 0 are poor linear predictors; those with ∣r∣ above 0.7 (or below -0.7) are strong candidates for inclusion. However, a small r does not mean no relationship – only that the relationship is not linear.
Multicollinearity
When independent variables are highly correlated with each other, multicollinearity exists. This can cause:
Unstable coefficient estimates (small changes in data cause large changes in coefficients).
Difficulty in isolating the individual effect of each predictor.
Inflated standard errors, making coefficients statistically insignificant even if they are important.
Detection: Variance Inflation Factor (VIF). A VIF > 5 or 10 indicates problematic collinearity.
Remedies:
Remove one of the correlated variables.
Combine them into a single composite variable (e.g., using Principal Component Analysis).
Use regularized regression (Ridge or Lasso).
Outliers and Their Impact
Outliers are data points that deviate markedly from the overall pattern. Linear regression is highly sensitive to outliers because they can pull the best fit line toward themselves, increasing RSS and distorting coefficients.
Detection:
Scatter plots and box plots.
Standardized residuals (Z‑scores > 3 often considered outliers).
Cook’s distance (measures influence on coefficients).
Treatment:
Remove if data entry error.
Transform (e.g., log transformation) to reduce impact.
Use robust regression methods (e.g., Huber regression) that are less affected by outliers.
Data Preprocessing Steps
Before fitting a linear regression model, data must be prepared:
Handle Missing Values:
If missing at random, replace with median (robust to outliers) or mean after outlier removal.
For systematic missingness, use advanced imputation techniques like MICE (Multiple Imputation by Chained Equations).
Convert Categorical Variables:
Ordinal categories (e.g., Low, Medium, High) can be label‑encoded as 0, 1, 2.
Nominal categories (e.g., color red, green, blue) must be one‑hot encoded (create dummy binary columns). Avoid introducing artificial order.
Low Variance Filter:
Remove columns that have very little variation (e.g., 99% of values are the same). Such columns cannot help predict the target.
Train‑Test Split:
Divide the data into a training set (e.g., 70–80%) and a testing set (remainder). This prevents overfitting and gives an honest estimate of model performance.
Scaling (Optional):
Linear regression coefficients are scale‑dependent. Scaling (standardization) is not required but can help with interpretation and comparison of coefficients when variables are in different units.
Model Building Process
A typical workflow for building a linear regression model:
Load and explore the data.
Preprocess: handle missing values, encode categoricals, remove low‑variance columns.
Split: separate into training and testing sets.
Train: fit the model on the training data using ordinary least squares (or gradient descent).
Predict: generate predictions on the test set.
Evaluate: compute RMSE, R2, adjusted R2.
Refine: consider adding or removing variables, checking assumptions, and comparing alternative models.
Optimization: Gradient Descent
Gradient descent is an iterative algorithm used to minimize the RSS (or any cost function). It works by:
Starting with random initial values for coefficients.
Computing the partial derivative of RSS with respect to each coefficient (the gradient).
Updating the coefficients in the direction that reduces RSS, using a learning rate to control step size.
The algorithm continues until the change in RSS is negligible or a maximum number of iterations is reached. For linear regression, the cost function is convex (bowl‑shaped), so gradient descent is guaranteed to find the global minimum.
Comparison of Simple and Multiple Linear Regression
Simple linear regression: one independent variable. The model is a line. Easy to visualize and interpret.
Multiple linear regression: multiple independent variables. The model is a hyperplane. More flexible and potentially more accurate, but interpretation becomes more complex, especially with correlated predictors.
Model comparison is typically done using adjusted R2 (to account for number of predictors) and RMSE on a held‑out test set.
Limitations of Linear Regression
Assumption‑heavy: violations can lead to poor performance.
Sensitive to outliers: they can skew the best fit line.
Assumes linear relationships: fails if the true relationship is nonlinear (though transformations can sometimes help).
Prone to overfitting: when many irrelevant predictors are included, the model may fit noise in the training data.
Cannot capture complex interactions unless explicitly encoded (e.g., product terms).
Despite these limitations, linear regression remains a foundational algorithm in data science due to its simplicity, interpretability, and speed. Many advanced methods (e.g., logistic regression, support vector machines with linear kernels) build upon the same principles.

Ask anything
We've read this whole study set, so questions about it get the best answers.