Linear Regression Explained for Beginners with Worked Examples

A beginner notices that students spending more time practising often achieve higher scores on an exercise. Can a mathematical line describe the pattern? If an individual practises for three hours, what score might a fitted model predict? And if the prediction is wrong, how can we measure that error? These questions introduce linear regression—a statistical method for describing how a numerical outcome relates to one or more predictors and producing numerical predictions under specified assumptions.

A visually attractive line is not enough. A reliable regression analysis needs a precise equation, correctly estimated slope and intercept, real residual calculations, appropriate evaluation metrics and careful attention to data collection. A model may fit the observations used to build it while performing poorly on previously unseen cases. Even a very accurate model cannot automatically demonstrate that changing its predictor would cause the predicted improvement.

This full beginner tutorial starts with five fictional pairs and verifies every calculation by hand before checking the same values with Excel, Google Sheets and Python. It then moves to a reproducible dataset containing 240 fictional student records, where 192 are used to fit the model and 48 are deliberately held out for testing. You can also complete thirty original practice exercises with separate expandable hints and answers, ten practical capstone tasks, and a research report using the downloadable resources.

First worked result: For X = 1, 2, 3, 4, 5 weekly practice hours and Y = 2, 3, 5, 4, 6 fictional skill scores, the ordinary least-squares fitted line is predicted Y = 1.3 + 0.9X. The in-sample residual sum of squares is 1.9, R² is 0.81, and RMSE is approximately 0.6164. These are not estimates of performance on unseen students.

What is linear regression?

Linear regression is a family of methods that models a numerical response as a function that is linear in its coefficients. The simplest form fits a straight line to observations with one predictor; simple linear regression is therefore a practical extension of the straight-line equation from elementary algebra. Multiple linear regression uses two or more predictors, although the core teaching calculation in this article deliberately uses just one.

The response (dependent variable) is the number we want to model or predict, while the explanatory (independent or predictor) variable supplies information used in the equation. For our five-point illustration, X is weekly practice hours and Y is an educational skill score on a small fictional numerical scale—not a real percentage or official test. Calling X “independent” defines a modelling role; it does not mean X is statistically independent of Y or scientifically established as Y’s cause.

Five verified fictional paired scores and least squares fitted line with slope 0.9 and intercept 1.3.
Figure 1. The fitted straight line summarizes a trend in five observations; its predictions need not pass through every point.

Predictor X and response Y: why their roles matter

In a scatterplot, conventionally place the predictor X on the horizontal axis and the response Y on the vertical axis. Each dot represents one matched pair from the same observation. The horizontal coordinate might be hours practised, and the vertical coordinate the recorded score. Interchanging the axis roles changes the regression question: predicting hours from marks is not the same mathematical least-squares fit as predicting marks from hours, even though the correlation coefficient is symmetric.

Practice hours correctly displayed on the horizontal X axis and score on vertical Y axis.
Figure 2. A scatterplot’s axis roles reflect the modelled question, not an established causal direction.

For example, scientific researchers might predict a measured response from temperature, or a business analyst might predict monthly sales from a measured marketing variable. Those examples can be useful without presuming the observed association is causal. When units change, the slope value changes accordingly, so always identify the measurement scale before interpreting a coefficient. The model’s usefulness depends on the quality, range, timing and representativeness of its input observations.

Understand the regression equation: predicted value, slope and intercept

The fitted simple regression line is written ŷ = b₀ + b₁x, where ŷ (“y-hat”) is the predicted outcome, b₀ is the estimated intercept, b₁ is the estimated slope, and x is the predictor value. The statistical population model may be expressed Y = β₀ + β₁X + ε, where β₀ and β₁ are unknown parameters and ε is an unobserved model error. By contrast, a residual is calculated after fitting from the actual observed value minus its fitted prediction; these two notions should not be confused.

Fitted regression line:
  predicted Y (ŷ) = b₀ + b₁ × X

For the five fictional scores:
  predicted score = 1.3 + 0.9 × practice hours

Population statistical model (conceptual):
  Y = β₀ + β₁X + ε

Interpret the slope correctly

Slope indicates how much the fitted outcome changes when X increases by one unit. In our illustration b₁ = +0.9 score units per practice hour. The line therefore rises by 0.9 units for every one-hour increment within the assumed linear model. A negative slope would indicate a declining fitted outcome, whereas a zero slope would produce a flat fitted line. Its units are units of Y divided by units of X, unlike a unitless correlation coefficient.

The slope is an observational model coefficient. It is not proof that deliberately adding an hour of practice would cause an actual learner’s score to rise by exactly 0.9 units. Differences in prior knowledge, resources, exercise difficulty and selection into practice can alter observed relationships. This causal distinction builds on the previous Correlation vs. Causation guide.

Interpret the intercept without overclaiming

The intercept is the line’s fitted Y when X equals zero. Here b₀ = +1.3, so mathematically ŷ = 1.3 at zero hours. But the five observations have X between one and five; zero lies outside that observed range. An intercept can be necessary for the best-fitting equation even when evaluating it at X=0 is unsupported by the available data. Never automatically treat a statistical intercept as a verified baseline score for people who did no practice.

Regression line showing slope +0.9 and intercept 1.3 while observed hours range from one to five.
Figure 3. Regression coefficients have distinct numerical roles and distinct limitations.

What does “line of best fit” actually mean?

The word “best” needs a mathematical criterion. In ordinary least squares (OLS), we choose the intercept and slope that minimize the sum of squared vertical residuals between observed Y values and fitted Y values. It is not the geometric shortest perpendicular distance from each point to the line; that belongs to other fitting problems. Squaring makes positive and negative errors contribute nonnegative amounts and places relatively greater weight on large errors. A different loss function, such as absolute error, could select a different line.

OLS gives a clear calculation and works well as a mathematical baseline, but its coefficients are not automatically suitable for every dataset. A curved relationship, extremely influential observations, changing variability, biased measurements or repeated observations can require modified methods or careful caution. Before any modeling, draw the points, check whether X varies and determine whether a straight line is a reasonable approximation for the purpose.

Step-by-step calculation of the regression slope

Write out the full set of paired observations before calculating anything. The practice hours are 1, 2, 3, 4, 5 and the scores are 2, 3, 5, 4, 6, so there are five independent rows in this fictional example, not ten separate observations. Calculate the means: x̄ = (1+2+3+4+5)/5 = 3, and ȳ = (2+3+5+4+6)/5 = 4. Then center both values in each pair. The slope numerator is the sum of the paired centered products, and the denominator is the sum of squared centered X values.

Slope formula:
b₁ = Σ[(xᵢ−x̄)(yᵢ−ȳ)] / Σ(xᵢ−x̄)²

x̄ = 3; ȳ = 4
Σ[(x−3)(y−4)] = 9
Σ(x−3)² = 10
b₁ = 9 / 10 = 0.9
ObservationXYX−3Y−4Cross product(X−3)²
A12−2−244
B23−1−111
C350100
D441001
E562244
Sum152000910
Calculated numerator crossproduct contributions sum to nine and squared X deviations sum to ten.
Figure 4. The verified centered-product calculation supplies the OLS slope; the summation is not guessed from a trendline.

The fact that centered X values sum to zero is not the slope calculation; that cancellation holds by construction. The numerator instead adds paired products, which are positive when X and Y deviate in the same direction and negative when their directions differ. For this example the cross-products total nine and the X squared-deviation total ten, giving 0.9. If every X value were identical, the denominator would be zero and the simple slope would be undefined.

Calculate the intercept and write the complete equation

Once slope b₁ is known, the OLS intercept is calculated as b₀ = ȳ − b₁x̄. Substituting the actual sample means gives 4 − 0.9×3 = 4−2.7 = 1.3. Thus the line is ŷ = 1.3+0.9X. An ordinary least-squares regression with a freely fitted intercept passes through the point (x̄,ȳ) = (3,4), which you can verify directly: 1.3+0.9×3=4. This algebraic property does not mean every observation lies on the line.

Intercept: b₀ = ȳ − b₁ x̄
          = 4 − 0.9×3 = 1.3

Fitted equation:
ŷ = 1.3 + 0.9X
At X=3: ŷ = 1.3+2.7 = 4.0

Use the regression equation to make fitted predictions

For each observed practice-hour value, substitute that X into the fitted equation. At one hour, the model predicts 1.3+0.9 = 2.2; at two hours it predicts 3.1; at three, 4.0; at four, 4.9; and at five, 5.8. Some of those predictions disagree with the actual fictional outcomes. That disagreement is expected for an imperfect line. A predicted score describes the fitted conditional pattern, not a guaranteed individual result.

Hours XObserved YFitted ŷResidual Y−ŷResidual squared
122.2−0.20.04
233.1−0.10.01
354+1.01
444.9−0.90.81
565.8+0.20.04
Totals202001.9
Five observed fictional scores compared against exact predictions 2.2, 3.1, 4.0, 4.9 and 5.8.
Figure 5. Observed values and fitted predictions are different quantities even when computed at the same X.

What is a residual? Interpret its sign

A residual is observed Y minus predicted Y. At three hours the actual score is five and the model predicts four, so the residual is +1.0, meaning the point lies one score unit above the line. At four hours the observed score is four and predicted score 4.9, so the residual is −0.9, meaning the observation lies below the fitted line. Residuals are calculated from known fitted observations; in contrast, the statistical model’s unobserved error term ε is a theoretical quantity and should not be treated as identical to a residual.

Dashed vertical lines show observed minus predicted differences for the five example points.
Figure 6. Ordinary least squares minimizes squared vertical residuals in the response direction.

In simple OLS with a freely estimated intercept, the fitted-data residuals sum to approximately zero because the least-squares normal equations enforce this property. The signed residuals here total −0.2−0.1+1.0−0.9+0.2 = 0. That is not proof of a good model—positive and negative errors could cancel even when large. The corresponding squared or absolute errors avoid such cancellation and provide useful information about fit.

Sum of squared errors: SSE = 1.90

Ordinary least squares chooses its coefficients to minimize SSE = Σ(Y−ŷ)² on the fitting observations. Our squared residuals are 0.04, 0.01, 1.00, 0.81, 0.04, and their sum is 1.90 squared score units. The two largest errors contribute 1.81 of the total, illustrating the extra influence of large residuals under squared-error loss. Squaring is a deliberate criterion, not the only possible way to fit a model; alternatives can focus on other loss functions and assumptions.

Five verified squared residual contributions 0.04,0.01,1.00,0.81,0.04 sum to SSE 1.9.
Figure 7. The least-squares objective gives larger residuals larger squared contributions.

Total sum of squares and R-squared

To compare the fitted model with predicting the sample mean, calculate the total sum of squares SST = Σ(Y−ȳ)². The outcome mean is four, so the squared deviations of Y=2,3,5,4,6 from four are 4,1,1,0,4. Thus SST=10. For an intercept-containing OLS model evaluated on its fitting observations, R² = 1−SSE/SST = 1−1.9/10 = 0.81. It represents the fraction of observed variance around the training mean accounted for by the fitted line in that setting.

SST = (2−4)² + (3−4)² + (5−4)² + (4−4)² + (6−4)²
    = 4 + 1 + 1 + 0 + 4 = 10
SSE = 1.90
In-sample R² = 1 − SSE/SST = 1 − 1.9/10 = 0.81
Pearson r = +0.90; in-sample simple OLS R² = r² = 0.81
SST ten split into model-accounted 8.1 and residual 1.9 for in-sample simple OLS R squared 0.81.
Figure 8. The 81% figure refers to in-sample variation explained, not 81% of individual predictions correct.

A large R² does not prove causation, nor does it guarantee accuracy on data not used for fitting. Test-set R² can even be negative when predictions are worse than the mean of the test outcomes under the usual definition. With only one predictor and a fitted intercept evaluated on the same observations, R² equals squared Pearson correlation; that identity should not be applied indiscriminately to nonlinear models, held-out test metrics or algorithms with different definitions.

Calculate MAE, MSE and RMSE without mixing denominators

Mean absolute error (MAE) averages absolute residual magnitudes: (0.2+0.1+1.0+0.9+0.2)/5 = 0.48 score units. Mean squared error (MSE), as a prediction metric, is SSE divided by five: 1.9/5 = 0.38 squared score units. Root mean squared error (RMSE) is √0.38 ≈ 0.6164 score units. RMSE reacts more strongly to large residuals because it squares them before averaging. None of these in-sample figures estimates future predictive accuracy without a proper evaluation design.

The prediction MSE denominator n=5 is not the classical simple-regression residual-variance estimator, which divides SSE by n−2=3 when estimating error variance under appropriate assumptions. Those two quantities answer different questions. Likewise, MAE and RMSE are in the original outcome units but emphasize errors differently; choose reporting metrics based on the decision context and the actual data scale.

MeasureFormulaWorked in-sample valueUnits
MAEΣ|Y−ŷ| / n0.48Score units
MSEΣ(Y−ŷ)² / n0.38Squared score units
RMSE√MSE0.6164Score units
R²1−SSE/SST0.81Dimensionless
Verified in-sample MAE 0.48, RMSE 0.6164, and MSE 0.38 with different units labelled.
Figure 9. Error metrics answer different questions and cannot be compared directly when units differ.

Linear regression versus correlation

Correlation and regression can examine the same paired data while answering different questions. Pearson’s r measures the direction and linear strength of the paired association in a symmetric and unitless manner. Simple linear regression makes a directional modelling choice: it fits Y from X, producing a slope with units and numerical predictions. Reversing X and Y generally produces a different least-squares equation. For the five observations, Pearson r is +0.90 and the fitted-data R² is 0.81; their square relationship holds in this special simple OLS-with-intercept setting.

FeaturePearson correlationSimple linear regression
PurposeSummarize paired linear associationModel expected Y and make fitted predictions
Formular between −1 and +1ŷ=b₀+b₁x
Symmetryr(X,Y)=r(Y,X)Y-on-X differs from X-on-Y
UnitsNo unitsIntercept: Y units; slope: Y units / X unit
Predict fitted Y?Not aloneYes, using estimated coefficients
Causal effect?Not identified by rNot identified by slope alone

Interpolation is not extrapolation

Interpolation means using the equation for a predictor value inside the observed 1–5-hour range. At X=3.5, the line predicts 1.3+0.9×3.5 = 4.45. Extrapolation uses values outside that range: at X=6, the arithmetic yields 6.70, but the assumption that the relationship remains linear is less supported. At X=0 the intercept of 1.3 is also an extrapolation. An extrapolated prediction can be mathematically correct while scientifically unreliable.

When numerical outcomes are bounded, an unrestricted straight-line equation can even predict impossible values outside the scale—for example, negative exam percentages or scores above 100. Such outputs do not prove that every linear model is useless; they reveal the limitations of extrapolation or an unsuitable outcome model. Decisions should rely on realistic predictor ranges, domain constraints and performance on relevant held-out observations.

How influential observations change a line of best fit

An outlier is unusual relative to a distribution or model; a high-leverage point has an extreme X value; and an influential point substantially changes the fitted coefficients when included. These ideas overlap but are not identical. To illustrate, add one synthetic observation (X,Y)=(12,0) to the five original pairs. The original slope is +0.9 and R²=0.81. After adding that one high-leverage point, the verified new slope becomes approximately −0.2710, intercept 4.5527, and fitted-data R² ≈ 0.2439.

Comparison of original five-point line and new six-point line after inserting one documented influential point at twelve hours, zero score.
Figure 10. An extreme observation changes regression coefficients; investigate its provenance rather than deleting it automatically.

The added point is a deliberately constructed sensitivity demonstration, not a valid extra real student record. If a high-leverage observation arises in authentic research, check whether it represents an error, an overlooked subgroup or a legitimate rare case. Document any exclusion and compare results with and without the point where appropriate. Ordinary least squares is sensitive to squared vertical errors, but influence depends on predictor leverage as well as residual size. One numerical diagnostic alone does not establish what data treatment is justified.

Understand the assumptions of simple linear regression

For a simple statistical regression model, a suitable linear form is often expressed as E[Y|X=x] ≈ β₀+β₁x. Inference about coefficients additionally requires assumptions about errors and the sampling process. A key condition for interpreting the fitted slope as a meaningful conditional association is that the model’s error has a suitable zero conditional expectation. Independence or properly modelled dependence matters for uncertainty calculations; equal conditional error variance supports classical standard-error formulas; and normal error assumptions can be used for some exact small-sample tests. These assumptions serve different purposes and should not be treated as an all-or-nothing checklist.

Neither X nor Y must be normally distributed just to compute an OLS line. Numerical optimizers can fit a line to skewed or non-normal measurements, although the resulting model may still be poor for prediction or inference. A constant X variable prevents estimation of its slope, and repeated records from one student could invalidate ordinary independence assumptions. Penn State’s regression-assumptions lesson explains how residual patterns, variance and model form relate to inferential reasoning.

Residual plots and model diagnostics

A residual-versus-fitted plot places each fitted outcome on the horizontal axis and its residual on the vertical axis. Ideally, when a simple linear form is appropriate, the plot shows no obvious systematic curve. A U-shaped pattern may suggest that straight-line mean structure misses curvature; increasing spread may signal nonconstant error variance; distinct clusters may suggest subgroup differences; and isolated extreme residuals deserve inspection. But an apparently random cloud—especially for only five points—does not prove every modelling assumption.

Actual residual versus fitted plot from 48 held-out fictional assessment scores, with a horizontal zero reference line.
Figure 11. Real computed held-out residuals can reveal model weaknesses; this plot does not by itself validate causality.

Underfitting, overfitting and the meaning of generalization

A model underfits when its form is too restrictive to capture important features in the data. A single straight line can underfit a genuinely curved pattern. A model overfits when its choices adapt too closely to quirks of the fitting observations and fail to generalize. Even a simple two-coefficient regression can have unstable results when the sample is tiny or influential points dominate. Fitting a more complicated polynomial can raise training R² while producing worse future predictions if the added flexibility mainly captures noise.

The most important response is to evaluate on observations that played no role in fitting or tuning the model. Compare the results with a sensible baseline and inspect residuals. A suspiciously impressive test score may reflect leakage of test information; an ordinary score may accurately represent limited predictability. Neither training fit nor held-out predictive skill is equivalent to identifying the causal effect of additional practice.

Training and test sets: prevent data leakage

For the 240 fictional observations, a documented 80/20 random split allocates 192 to training and 48 to testing, with scikit-learn random_state=78. Fit the coefficients using only the training subset. The test outcomes must remain untouched during fitting, feature selection or hyperparameter decisions if they are to provide an honest final holdout. If preprocessing learns parameters from data—such as an imputation value or normalization scale—it must learn those from training observations only, then apply them to test rows.

Verified 192 training versus 48 test allocation for the 240-record synthetic regression project.
Figure 12. A documented split protects a meaningful test evaluation, provided no test information leaks into fitting.

A random row split is appropriate here because the generator provides one fictional row per independent student-level observation in a fixed synthetic period. Real datasets can differ: multiple rows from the same learner may require group-aware splitting, and chronological forecasting should use appropriately ordered training and test periods. A fixed random seed makes an illustration reproducible, not automatically representative or robust. Repeating cross-validation inside training can help when choosing a model, but the final test should remain held out.

Build and honestly evaluate a 240-record fictional regression project

The project title is Predicting Assessment Scores from Weekly Practice Hours. The generator uses NumPy default_rng(78078) to create exactly 240 unique codes and eight fields: StudentCode, WeeklyPracticeHours, PriorAssessmentScore, AttendancePercentage, StudyLevel, Subject, FictionalRegion and AssessmentScore. Hours are nonnegative and assessment scores are constrained to the fictional 0–100 scale. Missingness is absent by design; this makes it an introductory modelling exercise rather than a realistic audit of every challenge in educational data.

The simulated outcome formula deliberately combines a positive coefficient for practice hours, a contribution from earlier scores, attendance and subject effects, plus normally distributed numerical noise. After generation, scores are rounded to one decimal and clipped to the scale. These choices influence the observed relationship and can change residual patterns. Crucially, the training model uses only WeeklyPracticeHours to predict AssessmentScore, even though the source includes other contextual variables. The fitted coefficient therefore describes a single-predictor statistical association within the simulation—not the independent causal effect of practice.

Verified dataset propertyValueInterpretation
Synthetic records240 uniqueOne row per fictional learner
Mean hours3.6265Weekly practice hours across 240
Sample SD hours1.6925Observed hour variation
Mean score51.0179Synthetic numerical assessment points
Sample SD score12.1735Observed score variation
Full-data Pearson r+0.6784Descriptive linear association, not a treatment effect
Training observations192Used to fit model
Test observations48Held out before fitting

Verified model equation and held-out accuracy

The line fitted on the 192 training records is predicted score = 32.9489 + 4.9728 × practice hours. Within the simulation, each additional hour corresponds to approximately 4.97 higher fitted score points; this is not a real educational intervention estimate. At five practice hours, which lies within the observed synthetic data range of 0–8.2 hours, the model predicts approximately 57.8128 points. A single fitted value is not an assurance that one learner will earn exactly that amount.

The previously unseen 48 test records produce MAE 7.9784, RMSE 9.6863 and R² 0.3516. For context, predicting the training-set average score of 50.8703 for every test row yields test MAE 9.7208, RMSE 12.0522 and R² approximately −0.0038. The fitted model outperforms this baseline on these particular held-out observations, but a different split, population or learning environment could yield different results. No model selection or tuning was performed against the final test in this demonstration.

Full fictional 240-row scatter plot marked by 192 training and 48 held-out test points with training-fit regression line.
Figure 13. Training data establish the model; held-out points are used only for final evaluation.
Held-out metricRegression modelTraining-mean baseline
Test MAE7.9784 score points9.7208 score points
Test RMSE9.6863 score points12.0522 score points
Test R²0.3516−0.0038

Calculate linear regression in Microsoft Excel

Enter practice hours X into A2:A6 and the five scores Y into B2:B6. Excel’s SLOPE(known_y,known_x) gives the fitted slope, INTERCEPT gives b₀, and RSQ returns squared Pearson correlation for the given pairs. Thus the expected values are 0.9, 1.3 and 0.81. Excel’s LINEST can return a broader set of regression outputs and is useful for advanced exercises. A scatter chart with a linear trendline can display the fit, but rounded chart labels are not a substitute for precise calculations.

=SLOPE(B2:B6,A2:A6)
=INTERCEPT(B2:B6,A2:A6)
=RSQ(B2:B6,A2:A6)
=INTERCEPT($B$2:$B$6,$A$2:$A$6)+SLOPE($B$2:$B$6,$A$2:$A$6)*A2

The downloadable Excel workbook includes the five-observation deviation table, prediction and residual formulas, independent Python reference values, the source 240-record dataset, frozen train and held-out test tabs, and a formula-driven validation dashboard. The workbook calculations are not just screenshots: its regression and evaluation cells are live formulas, and the checked dashboard results match the independently executed Python calculations. Before interpreting your own data, verify that the X and Y ranges align, the cells are numeric, and any missing or invalid records are handled under a stated rule.

Google Sheets: fit the same line and verify predictions

Google Sheets supports the same SLOPE, INTERCEPT and RSQ formulas for paired numeric arrays. After importing the compatible XLSX workbook, select the X and Y columns, insert a scatter chart, and explore the chart editor’s linear trendline and equation options where available in your version. Check the sheet locale and argument separators. The Google Sheets SLOPE documentation and LINEST documentation explain supported formulas. The supplied workbook was prepared for import; it has not been executed as a native online Google Sheet.

=SLOPE(B2:B6,A2:A6)
=INTERCEPT(B2:B6,A2:A6)
=RSQ(B2:B6,A2:A6)

Python and scikit-learn: reproduce the five-point fit

The Python LinearRegression estimator fits ordinary least-squares coefficients when used with standard unregularized settings. The input feature X is an array with one column because scikit-learn expects two-dimensional predictors, even when the model has only one feature. The fit() method estimates coefficients, and predict() calculates fitted values. NumPy and scikit-learn then compute MAE, MSE, RMSE and R². The following example has been executed against the five source values, so the displayed reference results are independently confirmed.

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

x = np.array([1,2,3,4,5]).reshape(-1,1)
y = np.array([2,3,5,4,6])
model = LinearRegression().fit(x,y)
p = model.predict(x)
print(model.coef_[0], model.intercept_) # 0.9, 1.3
print(mean_absolute_error(y,p))          # 0.48
print(mean_squared_error(y,p))           # 0.38
print(np.sqrt(mean_squared_error(y,p)))  # 0.61644...
print(r2_score(y,p))                     # 0.81

This short script evaluates its training observations because it is intended to verify hand arithmetic, not to establish out-of-sample generalization. For actual predictive evaluation, first split data and then fit only on training observations. On recent scikit-learn versions, root_mean_squared_error is also available; taking the square root of mean_squared_error remains a transparent compatible approach. Consult the official LinearRegression API for current details.

Python: train/test evaluation against a baseline

For the full CSV, the goal is to predict AssessmentScore from WeeklyPracticeHours alone. The following core steps show the honest split; the downloadable notebook contains the complete loading, checks, scatterplots and residual visualizations. Set random_state=78 so the same 192/48 split can be reconstructed. Calculate the baseline from the training-set outcome mean only; using the test-set mean to construct the baseline would leak information. This code assumes the CSV is present in the working directory and its two chosen fields are valid numeric data.

import pandas as pd, numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

df = pd.read_csv('linear-regression-student-practice-data.csv')
X = df[['WeeklyPracticeHours']].to_numpy()
y = df['AssessmentScore'].to_numpy()
X_train,X_test,y_train,y_test = train_test_split(
    X,y,test_size=0.20,random_state=78)
reg = LinearRegression().fit(X_train,y_train)
pred = reg.predict(X_test)
baseline = np.full(len(y_test),y_train.mean())
for title,p in [('regression',pred),('baseline',baseline)]:
    print(title,mean_absolute_error(y_test,p),
          np.sqrt(mean_squared_error(y_test,p)),r2_score(y_test,p))

Optional statsmodels: analysis and inference are not the same

statsmodels offers detailed inferential regression output under its statistical assumptions. Its ordinary OLS interface typically requires adding the intercept column explicitly using sm.add_constant. In contrast, scikit-learn generally includes an intercept by default. The coefficient estimates can agree while the software emphasizes different workflows: predictive modelling and validation versus coefficient inference and diagnostics. Neither software package turns an observational coefficient into a causal effect; p-values and intervals still require careful assumption checking.

import statsmodels.api as sm
X_design = sm.add_constant(X_train)
ols = sm.OLS(y_train,X_design).fit()
print(ols.params)  # intercept and weekly-practice slope
# The same observational association is not automatically causal.

When should you choose a different modelling method?

Consider other methods when the outcome is binary rather than numerical, when the relationship is markedly nonlinear, when values are counts with special distributional properties, or when repeated measurements demand explicit dependence modelling. Logistic regression is commonly used for binary classification probabilities, while ordinary linear regression targets numerical outcomes without intrinsically bounding predictions. A more elaborate model is not automatically better: test against baselines and judge whether added complexity improves meaningful held-out performance without introducing leakage or inappropriate claims.

At least 25 common mistakes to correct before reporting regression

MistakePractical correction
Treating correlation as regressionPearson r is symmetric and unitless; fitted regression assigns predictor and outcome.
Calling the fitted slope causalConfounding and selection can remain.
Reversing X and Y casuallyOLS minimizes vertical Y residuals, so direction matters.
Using an incorrect X meanCompute x̄ from all matched X observations.
Dividing slope numerator by SyyUse Sxx = Σ(X−x̄)².
Confusing intercept and slopeIntercept predicts at X=0; slope is change per unit X.
Leaving off unitsSlope units are outcome units per predictor unit.
Miscalculating centred productsMultiply paired deviations, not their separate totals.
Confusing observed and predicted scoreObserved comes from source; predicted comes from equation.
Changing residual sign unconsciouslyDefine residual as observed minus fitted.
Forgetting to square for SSESSE sums squared residuals.
Calling SSE equal to MSEFor the stated prediction loss MSE=SSE/n.
Mixing MSE and residual variance estimateThe standard simple-regression error-variance estimator uses n−2.
Calling R² prediction accuracyIt summarizes variation explained under a definition.
Believing R² proves causationPredictive fit does not identify intervention effects.
Treating in-sample metrics as held-outReport train and test separately.
Skipping the baselineCompare against a simple training-mean predictor.
Missing curved patternsInspect the scatterplot and residual plot.
Ignoring residual diagnosticsLook for shape, changing spread and outliers.
Deleting outliers automaticallyInvestigate provenance and influence.
Equating high leverage and high residualOne concerns X, the other Y relative to the model.
Extrapolating without qualificationForecasts outside training X range are less supported.
Ignoring bounded outcomesA straight line may predict outside 0–100.
Treating missing records as zeroDocument missingness and valid values.
Leaking test data into trainingFit transforms and model only on training rows.
Random row splits for repeated studentsGroup-level splits may be necessary.
Assuming X,Y normality required for fittingOLS computation does not require normal marginal variables.
Confusing significance and importanceUncertainty and domain relevance need distinct interpretation.
Equating confidence and prediction intervalsIntervals target different uncertain quantities.
Claiming a plotted line guarantees good predictionsValidate on appropriate held-out records.

Complete capstone: Predicting fictional assessment scores

The capstone combines data quality, descriptive analysis, model fitting and evaluation into one reproducible report. Students should work from the included linear-regression-student-practice-data.csv, keeping the 240 records intact unless a documented quality rule requires a change. Since there are no missing required values in the generated source, the most important challenge is understanding what was actually fitted and what was held out. The answer guide presents numerical references, but a high-quality report must also explain the meaning of each statistic and any limitation on real-world interpretation.

Capstone 1 — Dataset quality

Objective and method: Inspect the eight columns, uniqueness and allowed numeric ranges. Verified reference: 240 unique fictional StudentCodes; 240 complete rows; hours 0–8.2; scores 19.6–84.6. Student extension: Show the exact formula or code, explain its units, and state one conclusion the design cannot justify.

Capstone 2 — Descriptive statistics

Objective and method: Calculate sample mean and sample SD of X and Y. Verified reference: Hours mean 3.6265, SD 1.6925; scores mean 51.0179, SD 12.1735. Student extension: Show the exact formula or code, explain its units, and state one conclusion the design cannot justify.

Capstone 3 — Correlation

Objective and method: Calculate full-data Pearson association between the two numerical columns. Verified reference: r = +0.6784; descriptive association only. Student extension: Show the exact formula or code, explain its units, and state one conclusion the design cannot justify.

Capstone 4 — Fit training regression

Objective and method: Split at 80/20, random_state=78, then fit one predictor. Verified reference: 192 train, 48 test; training slope 4.9728 and intercept 32.9489. Student extension: Show the exact formula or code, explain its units, and state one conclusion the design cannot justify.

Capstone 5 — Predict score at five hours

Objective and method: Apply the training-fitted equation to X=5. Verified reference: Ŷ ≈57.8128 score points; within the synthetic observed X range. Student extension: Show the exact formula or code, explain its units, and state one conclusion the design cannot justify.

Capstone 6 — Calculate test residuals

Objective and method: Use real 48 held-out rows; residual=observed−predicted. Verified reference: Positive residual indicates a score above prediction, negative below; inspect the test residual CSV. Student extension: Show the exact formula or code, explain its units, and state one conclusion the design cannot justify.

Capstone 7 — Evaluate test predictions

Objective and method: Compute MAE, RMSE and R² using only held-out outcomes. Verified reference: Test MAE 7.9784; RMSE 9.6863; R² 0.3516. Student extension: Show the exact formula or code, explain its units, and state one conclusion the design cannot justify.

Capstone 8 — Use a training-derived baseline

Objective and method: Predict the training Y mean for the 48 held-out cases. Verified reference: Baseline MAE 9.7208; RMSE 12.0522; R² −0.0038. Student extension: Show the exact formula or code, explain its units, and state one conclusion the design cannot justify.

Capstone 9 — Check assumptions and limitations

Objective and method: Examine scatterplot, held-out residuals, and synthetic design. Verified reference: Other sources of variation remain; no causal or population-generalizability claim follows. Student extension: Show the exact formula or code, explain its units, and state one conclusion the design cannot justify.

Capstone 10 — Write a complete research report

Objective and method: State question, data, generation, split, coefficients, predictions, evaluation and caveats. Verified reference: Report seed 78078, split seed 78 and one-feature model; suggest more validation before operational use. Student extension: Show the exact formula or code, explain its units, and state one conclusion the design cannot justify.

Thirty original practice exercises with hidden hints and worked answers

These questions move from algebraic definitions to verified numerical calculations and finally model-validation reasoning. Attempt each question before opening its answer. One point may be awarded per correctly solved question, giving a maximum of 30. Compare the nature of your mistakes rather than treating a score band as an official academic qualification. The printable question-only PDF and detailed answer guide contain the same exercise sequence for offline revision.

Level 1 — Regression foundations (1–10)

Question 1: Define simple regression

What type of outcome and how many predictors define simple linear regression?

Show a hint

One numerical outcome and one predictor.

Show worked solution

Verified answer: A numerical response Y is modelled using one predictor X and a fitted line linear in its coefficients.

Common mistake: A predictor role does not prove cause.

Question 2: Identify model variables

Which is X and which is Y in the five-observation exercise?

Show a hint

Hours are the explanatory variable.

Show worked solution

Verified answer: X is weekly practice hours; Y is fictional skill score.

Common mistake: The model does not prove practice causes marks.

Question 3: Interpret fitted slope

Explain b1=+0.9 with units.

Show a hint

Think one-hour increase.

Show worked solution

Verified answer: The fitted score rises 0.9 fictional score units per additional hour of X.

Common mistake: Slope is an association, not a treatment effect.

Question 4: Interpret intercept

What does b0=1.3 mean, and what is the caution?

Show a hint

Consider X=0.

Show worked solution

Verified answer: The line predicts 1.3 at zero hours, outside observed X range 1–5.

Common mistake: Unsupported interpretation at x=0.

Question 5: Positive slope

Interpret yhat=2+3X.

Show a hint

Read sign of 3.

Show worked solution

Verified answer: Predicted Y rises three units per extra X unit.

Common mistake: Do not confuse change with causation.

Question 6: Negative slope

Interpret yhat=12−2X.

Show a hint

Negative sign.

Show worked solution

Verified answer: Predicted Y declines two units per additional X unit.

Common mistake: Negative slope does not imply harm.

Question 7: Substitution

Find fitted score when X=1 for yhat=1.3+.9X.

Show a hint

Substitute X.

Show worked solution

Verified answer: Predicted score 1.3+0.9=2.2.

Common mistake: Do not use observed score 2 instead.

Question 8: Calculate prediction

Predict at X=4.

Show a hint

Use the given line.

Show worked solution

Verified answer: Predicted score 1.3+0.9×4=4.9.

Common mistake: The fitted value need not match Y=4.

Question 9: Residual sign

Observed=5, predicted=4 at X=3. Residual?

Show a hint

Observed−fitted.

Show worked solution

Verified answer: Residual = +1.0, above the line.

Common mistake: Wrong subtraction reverses sign.

Question 10: Regression vs correlation

Why is regression different from Pearson r?

Show a hint

One makes outcome predictions.

Show worked solution

Verified answer: OLS predicts fitted Y from X with units; r is symmetric and unitless.

Common mistake: Neither alone identifies causation.

Level 2 — Manual calculations (11–20)

Question 11: Means

Find xbar and ybar for X=1..5, Y=2,3,5,4,6.

Show a hint

Divide totals by five.

Show worked solution

Verified answer: X sum 15 gives mean 3; Y sum 20 gives mean 4.

Common mistake: Avoid dividing by four.

Question 12: Centered values

Find deviations for first and last observations.

Show a hint

Subtract means (3,4).

Show worked solution

Verified answer: A: (−2,−2); E: (+2,+2).

Common mistake: Keep pair order intact.

Question 13: Crossproduct sum

Compute Σ(X−3)(Y−4).

Show a hint

Products 4,1,0,0,4.

Show worked solution

Verified answer: The sum is 9.

Common mistake: It is not the sum of signed deviations.

Question 14: Slope computation

Use crossproduct=9, Sxx=10.

Show a hint

Take ratio.

Show worked solution

Verified answer: b1 = 9/10 = 0.9.

Common mistake: Use X squared deviations, not Y squared deviations.

Question 15: Intercept computation

Given mean Y=4, mean X=3, slope=.9, find b0.

Show a hint

Use ybar−b1 xbar.

Show worked solution

Verified answer: 4−0.9×3=1.3.

Common mistake: Intercept is not slope.

Question 16: State fitted line

Write the full estimated regression equation.

Show a hint

Intercept plus slope times X.

Show worked solution

Verified answer: Ŷ = 1.3+0.9X.

Common mistake: Use Y-hat for predictions.

Question 17: All five predictions

Compute Ŷ for 1,2,3,4,5 hours.

Show a hint

Add .9 repeatedly.

Show worked solution

Verified answer: 2.2, 3.1, 4.0, 4.9, 5.8.

Common mistake: Do not copy observed scores.

Question 18: Square residuals

Square −.2, −.1, 1, −.9, .2.

Show a hint

Square every signed value.

Show worked solution

Verified answer: 0.04, 0.01, 1.00, 0.81, 0.04.

Common mistake: Squared negatives are positive.

Question 19: Calculate SSE

Sum the five squared residuals.

Show a hint

Add all five.

Show worked solution

Verified answer: 0.04+0.01+1+0.81+0.04 = 1.90.

Common mistake: Signed residual sum is zero, not SSE.

Question 20: Calculate R-squared

Given SSE=1.9 and SST=10, find R².

Show a hint

1−SSE/SST.

Show worked solution

Verified answer: R²=0.81 in-sample, equivalent to 81% modelled training variance.

Common mistake: Not 81% correct predictions.

Level 3 — Diagnostics and research judgement (21–30)

Question 21: Find MAE

Use residuals −.2,−.1,1,−.9,.2.

Show a hint

Average absolute values.

Show worked solution

Verified answer: MAE=(.2+.1+1+.9+.2)/5=0.48.

Common mistake: Do not cancel opposite signs.

Question 22: Find RMSE

Given SSE 1.9 and n=5, find RMSE.

Show a hint

Square root of SSE/n.

Show worked solution

Verified answer: MSE=.38; RMSE=√.38=0.6164.

Common mistake: Do not confuse prediction MSE with n−2 variance estimate.

Question 23: Compare model metrics

A test MAE=4 versus another test MAE=5; which is lower?

Show a hint

Lower MAE means lower observed absolute error.

Show worked solution

Verified answer: The first has one unit less MAE on the same test outcomes; also consider context.

Common mistake: No causal inference follows.

Question 24: Outlier influence

Add documented (12,0) to five original pairs. What happens?

Show a hint

It is high leverage.

Show worked solution

Verified answer: OLS slope shifts from +0.9 to about −0.2710, so inspect the point’s validity.

Common mistake: Do not automatically erase it.

Question 25: Residual curve

Why is a U-shaped residual pattern important?

Show a hint

Consider model form.

Show worked solution

Verified answer: It can indicate missed nonlinearity or another modelling issue.

Common mistake: The pattern alone does not identify one cause.

Question 26: Interpolation vs extrapolation

Use X=3.5 and 6. State which extrapolates.

Show a hint

Known X range 1–5.

Show worked solution

Verified answer: At 3.5 predicted 4.45 (interpolation); at 6 predicted 6.7 (extrapolation).

Common mistake: Arithmetic does not guarantee extrapolative reliability.

Question 27: Model assumptions

Must X or Y be normal just to compute OLS?

Show a hint

Fitting vs statistical inference.

Show worked solution

Verified answer: No; marginal normality is not required merely to fit OLS. Certain exact tests use error assumptions.

Common mistake: Do not present a universal normality rule.

Question 28: Train/test leakage

Why fit a data imputer on training rows only?

Show a hint

Test must stay unseen.

Show worked solution

Verified answer: An imputer fitted to all rows can leak test information and overstate performance.

Common mistake: Do not use test outcomes during training.

Question 29: Prediction vs causation

Does fitted slope +0.9 identify a causal effect?

Show a hint

Recall Topic 77.

Show worked solution

Verified answer: No. Confounding and other biases may remain without justified causal design.

Common mistake: Regression coefficient ≠ intervention effect.

Question 30: Full result synthesis

Report slope, intercept, SSE, SST, MAE, RMSE, R² for five cases.

Show a hint

Keep the in-sample label.

Show worked solution

Verified answer: Slope .9; intercept 1.3; SSE 1.9; SST 10; MAE .48; RMSE .6164; R² .81 (in-sample).

Common mistake: Do not call five training observations an unseen test.

Student self-assessment: diagnose the skill, not just the score

Use one point per fully correct exercise, for a possible 30. Record separate totals for foundational understanding (Questions 1–10), mathematical calculations (11–20), and validation or interpretation (21–30). A high overall total can still hide an important weakness if all errors involve train/test leakage or causal overclaiming. The skills checklist is intended for personal revision and is not an official grading scale. Attempt the same questions again after correcting errors and compare the explanation, not just the answer.

A four-week learning roadmap

WeekMain learning objectivesEvidence of completion
Week 1 — Regression foundationsUnderstand X and Y, scatterplots, slopes, intercepts and fitted equations.Recreate all five original pairs and interpret the fitted line.
Week 2 — Manual mathematicsCompute b1, b0, predictions, residuals, SSE, SST and R².Verify 0.9, 1.3, 1.9, 10 and 0.81 by hand.
Week 3 — Software and validationUse Excel, import to Sheets, run Python and distinguish train/test results.Calculate live formulas, inspect scatter/residual plots and baseline metrics.
Week 4 — Capstone and reportingComplete ten tasks, 30 exercises and a reproducible findings report.Submit methods, checked calculations, figures and limitations.

This four-week sequence is flexible: learners comfortable with basic algebra can move faster, while those unfamiliar with squared deviations may need additional practice before moving to prediction metrics. The most useful outcome is the ability to reproduce a model, identify questionable reasoning and explain why its coefficients are descriptive rather than automatically causal. Students should preserve their formulas and source rows, since a result without a verifiable method is difficult to audit or improve.

Download the regression learning resources

The WordPress media library contains two formula-driven workbook variants, seven printable PDFs and an editable Word research template. The full ZIP supplied with this lesson additionally includes the small and large CSV datasets, train/test IDs, Python notebook, verified statistical graphics, generator code and a README explaining seeds and limitations. The resources use fictional values only. The Google Sheets-compatible XLSX may be imported into Google Sheets; it is not claimed to have been tested in the native cloud editor.

Optional guided courses on statistics and regression

After working through these free materials, learners who prefer additional instruction can review current offerings such as Basic Statistics on Coursera and Microsoft Excel: Essential Statistics for Data Analysis on Udemy. These are informational destinations, not claimed affiliate-tracked links: no approved tracking URLs or advertising images were verifiable for this specific article. Any course prerequisites, price, enrollment availability or certificate conditions should be checked on the provider page before use.

Frequently asked questions

What is simple linear regression?

It fits a model linear in intercept and slope for a numerical outcome using one predictor, enabling fitted-value calculations.

What is the basic regression formula?

The fitted line is ŷ=b0+b1x, where b0 is intercept, b1 slope and x the predictor.

How is the least-squares slope calculated?

Divide the sum of paired centered X-Y products by the sum of squared centered X deviations, provided X varies.

How do I find the intercept?

Compute sample mean Y minus estimated slope multiplied by sample mean X.

What is a regression residual?

Observed Y minus fitted Y, interpreted as the vertical difference from the fitted line.

Why do ordinary least squares methods square residuals?

Squaring prevents sign cancellation and gives larger vertical errors disproportionately greater contribution to the optimized loss.

What does R-squared mean?

For intercept-containing OLS evaluated on fitted data, R²=1−SSE/SST summarizes variation explained relative to the sample mean. Test R² can be negative.

How are MAE and RMSE different?

MAE averages absolute errors; RMSE is the square root of mean squared error and is more sensitive to large deviations.

Do the regression variables have to be normally distributed?

No. OLS can be fitted without normal X or Y. Error distribution assumptions matter for certain statistical inference procedures.

Can a high R-squared prove causation?

No. Confounding and study design affect whether a coefficient can be interpreted causally.

Can Excel and Google Sheets calculate regression?

Yes. Their SLOPE, INTERCEPT and RSQ functions work on paired numerical ranges; check native application behavior and locale.

What is the difference between interpolation and extrapolation?

Interpolation uses predictor values within the observed range; extrapolation ventures outside and may be substantially less reliable.

Conclusion: a fitted line is a starting point, not a finished investigation

You have followed the full workflow from a question and scatterplot to a fitted equation, predictions, residuals and model evaluation. With five fictional observations, the least-squares line is ŷ=1.3+0.9X. Its calculations produce SSE 1.9, SST 10, MAE 0.48, MSE 0.38, RMSE approximately 0.6164 and R²=0.81. Those figures are meaningful because the observation pairs, formulas and error definitions are explicit. Equally important, they are training-data calculations and cannot themselves establish how well the model predicts unfamiliar observations.

The larger fictional project takes the next step by withholding test data before fitting. There, the held-out MAE is approximately 7.98 compared with baseline MAE 9.72; held-out R² is approximately 0.35 rather than the small worked example’s 0.81. This is not a contradiction: different datasets, model fits and evaluation contexts produce different results. When documenting a model, always specify what was measured, how the split was made, which variables entered the equation and what uncertainty or structural limitations remain.

The main skill to retain is critical statistical judgement. A slope is not automatically causal, a good training plot is not validation, and extrapolation should not be presented as certain. Reproduce the five-row exercise in the workbook, work through the 30 original questions, and then complete the separate 240-record capstone. These foundations will support the next topic on probability distributions, later hypothesis testing and more substantial predictive machine-learning projects.

Academic and official references

Related Notes for SHS data science lessons