1. Home
  2. Explore
  3. Computer Science
  4. Linear Regression Overview

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

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 (yyy) and one independent variable (xxx) using a straight line:

y=β0+β1xy = \beta_0 + \beta_1 xy=β0​+β1​x

or equivalently

y=mx+cy = mx + cy=mx+c

where:

  • β0\beta_0β0​ (or ccc) is the intercept – the value of yyy when x=0x = 0x=0.

  • β1\beta_1β1​ (or mmm) is the slope – the change in yyy for a one‑unit change in xxx.

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 (yiy_iyi​) and the value predicted by the line (y^i\hat{y}_iy^​i​):

ei=yi−y^ie_i = y_i - \hat{y}_iei​=yi​−y^​i​

To determine the best fit line, the Residual Sum of Squares (RSS) is minimized:

RSS=∑i=1n(yi−y^i)2\text{RSS} = \sum_{i=1}^n (y_i - \hat{y}_i)^2RSS=∑i=1n​(yi​−y^​i​)2

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\beta_1 = 6.8β1​=6.8

  • intercept β0=261\beta_0 = 261β0​=261

For a student with CGPA = 8.32, the predicted GRE score is:

y^=261+6.8×8.32=317\hat{y} = 261 + 6.8 \times 8.32 = 317y^​=261+6.8×8.32=317

Multiple Linear Regression

When there are two or more independent variables, the model becomes multiple linear regression:

y=β0+β1x1+β2x2+⋯+βpxpy = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \dots + \beta_p x_py=β0​+β1​x1​+β2​x2​+⋯+βp​xp​

This equation represents a hyperplane in ppp‑dimensional space. Each coefficient βj\beta_jβj​ quantifies the change in yyy for a one‑unit change in xjx_jxj​, 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:

price=β0+β1×carat+β2×length+β3×width+β4×depth\text{price} = \beta_0 + \beta_1 \times \text{carat} + \beta_2 \times \text{length} + \beta_3 \times \text{width} + \beta_4 \times \text{depth}price=β0​+β1​×carat+β2​×length+β3​×width+β4​×depth

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 (R2R^2R2)

R2R^2R2 measures the proportion of variance in the dependent variable that is explained by the model:

R2=1−SSresSStotR^2 = 1 - \frac{\text{SS}_{\text{res}}}{\text{SS}_{\text{tot}}}R2=1−SStot​SSres​​
  • SSres=∑(yi−y^i)2\text{SS}_{\text{res}} = \sum (y_i - \hat{y}_i)^2SSres​=∑(yi​−y^​i​)2 (residual sum of squares)

  • SStot=∑(yi−yˉ)2\text{SS}_{\text{tot}} = \sum (y_i - \bar{y})^2SStot​=∑(yi​−yˉ​)2 (total sum of squares)

R2R^2R2 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 R2R^2R2. Adjusted R2R^2R2 penalizes the inclusion of useless variables:

Radj2=1−(1−R2)(n−1)n−p−1R^2_{\text{adj}} = 1 - \frac{(1 - R^2)(n - 1)}{n - p - 1}Radj2​=1−n−p−1(1−R2)(n−1)​

where nnn is the number of observations and ppp is the number of predictors. Adjusted R2R^2R2 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:

RMSE=1n∑i=1n(yi−y^i)2\text{RMSE} = \sqrt{\frac{1}{n} \sum_{i=1}^n (y_i - \hat{y}_i)^2}RMSE=n1​∑i=1n​(yi​−y^​i​)2​

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:

  1. Linearity – The relationship between each independent variable and the dependent variable is linear.

  2. Independence of Errors – Residuals are not correlated with each other (e.g., no autocorrelation in time series).

  3. Homoscedasticity – The variance of residuals is constant across all levels of the independent variables.

  4. Normality of Residuals – For hypothesis testing and confidence intervals, residuals should be approximately normally distributed.

  5. No Multicollinearity – Independent variables are not highly correlated with each other.

  6. 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 (rrr)

Before building a model, it is useful to examine the strength of linear relationships between pairs of variables using Pearson’s correlation coefficient rrr:

r=∑(xi−xˉ)(yi−yˉ)∑(xi−xˉ)2∑(yi−yˉ)2r = \frac{\sum (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum (x_i - \bar{x})^2}\sqrt{\sum (y_i - \bar{y})^2}}r=∑(xi​−xˉ)2​∑(yi​−yˉ​)2​∑(xi​−xˉ)(yi​−yˉ​)​
  • Range: −1≤r≤1-1 \le r \le 1−1≤r≤1.

    • r=1r = 1r=1: perfect positive linear relationship.

    • r=−1r = -1r=−1: perfect negative linear relationship.

    • r=0r = 0r=0: no linear correlation (but a nonlinear relationship may exist).

Variables with ∣r∣|r|∣r∣ close to 0 are poor linear predictors; those with ∣r∣|r|∣r∣ above 0.7 (or below -0.7) are strong candidates for inclusion. However, a small rrr 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:

  1. 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).

  2. 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.

  3. 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.

  4. 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.

  5. 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:

  1. Load and explore the data.

  2. Preprocess: handle missing values, encode categoricals, remove low‑variance columns.

  3. Split: separate into training and testing sets.

  4. Train: fit the model on the training data using ordinary least squares (or gradient descent).

  5. Predict: generate predictions on the test set.

  6. Evaluate: compute RMSE, R2R^2R2, adjusted R2R^2R2.

  7. 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 R2R^2R2 (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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent