12. Simple Linear Regression
Course Administration and Examination Guidelines
Proctoring software behavior and environment controls:
Automated examination proctoring systems (such as the Lockdown Browser / "Rotter Brothers" environment) flag visual irregularities during monitoring.
Backlighting scenarios—where intense illumination originates from behind the student—darken facial skin tones on camera, triggering system warnings that the test-taker cannot be seen or has been cut out of frame.
Incidental room decor can trigger false violations; an incident occurred where a wall poster displaying a face-like mask shape was flagged by the software as an unauthorized secondary person in the room before manual verification cleared the incident.
Optimal examination setups require a well-lit testing environment with direct, front-facing illumination to eliminate automated software flags.
Examination curriculum structure:
Future examination questions and formats will be reshuffled from prior course offerings and historical question banks.
The scope of the final examination is non-cumulative regarding earlier foundational content; all topics evaluated on the midterm are completed, and the final exam exclusively tests concepts introduced from simple linear regression onward.
Fundamentals of Simple Linear Regression
Motivation and predictive modeling objectives:
Observed trends—such as plotting midterm exam grades against total hours invested in studying—illustrate that increased study duration corresponds to higher exam point totals.
The goal of statistical modeling is to summarize empirical data into a formal framework capable of producing deterministic predictions (e.g., forecasting an exact score or grade based on a prospective student's planned study hours).
Model definition and specifications:
Simple linear regression models the relationship between a single independent predictor variable and a continuous quantitative response variable .
The population relationship is formulated as a rigid straight-line equation:
Predictor variable (): The known input measurement.
Response variable (): The quantitative output to be estimated.
Parameters (): Unknown population coefficients that dictate the geometric location and slope of the regression line in Euclidean space.
Application to advertising data:
Sales forecasting can be structured by linking revenue to marketing investments:
If the television advertising budget is known alongside estimates of and , an exact sales prediction can be calculated.
Parameter estimation framework:
The true parameters and represent the unobservable underlying data-generating relationship.
Empirical estimates are designated as and , yielding the fitted prediction value :
Training datasets consist of discrete paired observations: .
Parameter discovery approaches include:
Heuristic search / iterative fitting: Initializing arbitrary coefficient values, computing prediction errors, and updating coefficients iteratively until convergence.
Analytical closed-form solutions: Applying mathematical minimization techniques via the least squares criterion.
Least Squares Optimization and Coefficient Derivation
Residual definition and Residual Sum of Squares (RSS):
The prediction discrepancy for each observation is termed the residual ():
The least squares approach identifies parameter values that minimize the Residual Sum of Squares (RSS):
Generative data framework with stochastic noise:
The empirical generative relationship includes a stochastic error component:
The random disturbance represents intrinsic system noise drawn from a normal distribution with a mean of zero and variance :
Derivation of the intercept through expectations:
Applying the mathematical expectation operator across the generative model yields:
Because is a constant parameter, its expected value is itself (). By comparison, rolling a balanced six-sided die with faces produces variable outcomes with an expected value equal to the mean: A deterministic constant sequence consistently evaluates to that constant value.
Because the random error has a mean of zero, its expected value vanishes:
Factoring the constant slope out of the expectation gives:
The expectation identity simplifies to:
Rearranging provides the formula for the intercept:
Derivation of the slope through covariance:
Expanding the covariance between the predictor and the response :
Covariance evaluates how two variables vary together; because is an invariant constant, it exhibits zero covariance with :
The random noise is an intrinsic systemic component independent of the predictor , resulting in zero covariance:
Factoring out leaves the covariance of with itself, which equals the variance of :
Equating terms yields:
Solving for the optimal slope parameter :
Sample-level estimator formulas:
For a sample of observations, the sample variance of is:
The sample covariance between and is:
Taking the ratio cancels the factor , yielding the standard least squares estimators:
In these equations, and denote the empirical sample means of the predictor and response variables.
Interpretation of Regression Coefficients
Empirical results from the advertising dataset:
Estimated intercept ():
Estimated slope ():
Physical interpretation of the intercept ():
Represents the baseline expected value of when the predictor variable is zero ().
In the context of marketing expenditure, investing in television advertising results in a baseline sales volume of (i.e., sold by default).
Physical interpretation of the slope ():
Represents the rate of change or marginal difference in resulting from a single unit increase in .
Because expenditure is measured in thousands of dollars, an additional of investment (, such as shifting budget from to , or from to ) results in an increase in sales of .
Expressed in individual product quantities, every additional invested yields an increase of sold.
Structural constraints of linear modeling:
Linear regression is a rigid model that imposes a straight-line assumption on data distributions.
Real-world data points inevitably scatter around this straight line, producing unavoidable residual errors.
Optimization Landscapes and Gradient Descent
Geometric properties of the loss surface:
In an iterative optimization framework, all possible parameter pairings of form a two-dimensional domain plane.
Computing the Residual Sum of Squares (RSS) for each coordinate defines a third dimension, creating a three-dimensional bowl-shaped surface.
Optimization mechanics of gradient descent:
Parameters are initialized arbitrarily (e.g., , ), which initially produces high RSS values.
The algorithm calculates the negative gradient using differential functions to establish the steepest path down the surface.
Iterative parameter updates move the system downward until settling at the global minimum (the base of the bowl), identifying the optimal coefficients and .
Sampling Variability, Standard Errors, and Confidence Intervals
Population line versus sample fits:
The theoretical population regression line represents the true underlying data-generating model (e.g., ).
Real-world datasets represent finite samples from this population; fitting a model to a sample produces an estimated line that deviates from the true population line.
Drawing different random subsets of data yields an ensemble of distinct regression lines.
Analogy to the Central Limit Theorem:
Consider estimating a population bivariate mean vector using three separate random samples (e.g., sample 1 marked by red crosses, sample 2 marked by blue squares, and sample 3 marked by yellow diamonds).
Each individual sample yields a different sample mean, but the average across many sample means converges to the population mean.
Estimator variance and standard errors:
The dispersion of an estimator around the true population mean is captured by its standard error squared:
The sampling variance of the regression coefficients is given by:
Residual Standard Error (RSE) as an estimate of :
The true variance of the error term () is typically unknown and is estimated from the sample data using the Residual Standard Error (RSE):
The denominator accounts for the degrees of freedom lost by estimating two parameters ( and ).
Construction and interpretation of confidence intervals:
Coefficient estimates are commonly reported across a range rather than as isolated point values.
The 95% confidence interval for the slope parameter is approximated by:
An example confidence interval for is .
Interpretation: If 100 independent models were constructed using distinct samples from the population, 95 of the resulting confidence intervals would contain the true parameter value.
Hypothesis Testing and Statistical Significance
Formulation of statistical hypotheses:
Null Hypothesis (): Predictor variable has no linear relationship with response variable :
Alternative Hypothesis (): A non-zero relationship exists between and :
Mathematical implication of the null hypothesis:
Setting cancels the predictor term (), reducing the model to a constant intercept ().
Under , variation in does not influence .
The -statistic:
Evaluates how many standard errors the estimated slope lies away from zero:
When is close to zero, the numerator approaches zero, driving toward zero. Larger deviations from zero increase the magnitude of .
Derivation of the -value and decision thresholds:
The -value represents the probability of observing a test statistic equal to or greater in magnitude than under the assumption that the null hypothesis () holds true.
Lower -values indicate a low probability that the observed coefficient occurred by chance under the null hypothesis, providing evidence to reject .
Standard significance cutoffs include , , or .
When , the null hypothesis is rejected, establishing that the linear relationship between and is statistically significant.
A significance level of implies that if 100 models were evaluated under , an estimate of that magnitude would occur purely by chance only of the time (or 5 times out of 1,000).
Model Evaluation Metrics: RSE and R-squared
Residual Standard Error (RSE) evaluation:
Measures the absolute average deviation between observed outcomes and the fitted regression line:
In the TV advertising dataset, an indicates that model predictions deviate from actual sales by an average of ().
Scale dependence and contextual interpretation of RSE:
For a small firm selling to monthly, a forecasting error of represents an error rate of roughly to , which indicates poor predictive performance.
For large-scale enterprises (e.g., Amazon) moving millions or billions of units, an error of is negligible, making an an acceptable fit.
Because RSE is measured in the units of the response variable, its magnitude cannot be evaluated without direct knowledge of the scale of the dataset.
Coefficient of Determination ( Statistic):
Provides a standardized, unitless metric bounded strictly between and :
Total Sum of Squares (TSS) measures the total inherent variability in the response variable around its mean:
Informational interpretation:
Variance represents information; an invariant variable contains no information.
TSS represents the total variance present in the response variable, while RSS represents the variance left unexplained by the regression model.
If the model performs poorly, the residual errors approach the total variability (), driving the ratio toward and yielding .
If the model fits the data well, the residual sum of squares is small relative to total variation (), driving the ratio toward and yielding .
An value of indicates that the regression model explains of the variance present in the response variable.
Questions & Discussion
Prompt regarding parameter nullity:
Question: If while remains a non-zero value, what does this state about the relationship between and ?
Student proposal 1:
Student Response: Does it mean that the covariance of and is zero?
Instructor Clarification: Covariance is not the direct answer; the inquiry focuses on the model equation itself.
Student proposal 2:
Student Response: There is no relationship between them.
Instructor Explanation: Setting removes the predictor term (), meaning contributes nothing to the computation of . Consequently, equals the constant intercept regardless of the value taken by , establishing that is completely independent of .
Computational Implementation and Laboratory Work
Scope of the laboratory assignment:
Part 1: Implement simple linear regression from scratch by coding closed-form formulas to compute and .
Part 2: Extend the manual implementation to multiple linear regression, supporting multiple simultaneous predictor variables () and their corresponding coefficients.
Integration with
scikit-learn:Models must also be fitted using the
LinearRegressionimplementation in thescikit-learnlibrary.The automated library output reports model parameters, the score, -statistics, and -values.
Students are required to compare and contrast the numerical outputs of their manual implementations against the fitted results produced by
scikit-learn.