DSA LABData Science Applications
Experiment 05 · CO3

What the Leftovers
Reveal

Regression analysis and residual plots. Fit a line, then look at what's left over — the residuals. Their pattern tells you whether the model is right. Switch the data shape and watch the residual plot give the verdict.

Course IT416
Outcome CO3
Tools OLS · residuals
Metrics R² · RMSE

Diagnostics at a glance

LIVE FIT
0
Data shapes
0
Linked plots
0
Key metrics
0
Concept videos
01

Lab Manual

Aim
To write a program that performs regression analysis on a given dataset and demonstrates residual plots, using them to judge how well the regression model fits.
Objectives
  • Fit a linear regression model (ordinary least squares) to data.
  • Compute residuals — the differences between observed and predicted values.
  • Draw a residual plot (residual vs fitted value) and interpret its shape.
  • Evaluate the fit with R² and RMSE, and check the regression assumptions.
Software
Python 3.x · Jupyter / Colab · NumPy, Pandas, Matplotlib / Seaborn, scikit-learn (or statsmodels).
Theory
A regression line predicts ŷ for each x. The residual is e = y − ŷ. If the model is appropriate, residuals should scatter randomly around zero with constant spread. Systematic patterns reveal problems: a curve means the relationship isn't linear; a funnel means the variance isn't constant (heteroscedasticity); a lone far-off point is an outlier.
Outcome
CO3 — building a regression model and evaluating it with diagnostic plots.
02

What Is a Residual?

Observed − Predicted

For every point, the model predicts a value on the line. The vertical gap between the real point and the line is the residual.

residual ei = yi − ŷi

Least squares finds the line that makes the sum of squared residuals as small as possible.

Why plot them?

The scatter plot shows how good the fit is. The residual plot shows what's wrong with it. A healthy residual plot is a shapeless cloud centred on zero. Any structure is the data telling you the model is missing something.

R² = fraction of variation explained · RMSE = typical prediction error (same units as y)
03

Fit & Diagnose, Live

Pick a data shape. The left plot fits the regression line (sky blue) and draws each residual (orange). The right plot is the residual plot. Tap the left plot to add your own point and watch both update. Read the diagnosis at the bottom.

Regression & residual plottap left plot to add a point
Regression fit
data + line + residuals
Residual plot
residual vs fitted value
Slope
Intercept
RMSE
03a

How to Read a Residual Plot

Three shapes to recognise. Only the first one means "all good".

✓ Random cloud
Good. Points scatter evenly above and below zero with no pattern — the linear model fits well.
⌣ Curve / U-shape
Wrong shape. A smile or frown means the true relationship is non-linear — try a polynomial or transform.
◁ Funnel / fan
Unequal variance. Spread grows with the fitted value (heteroscedasticity) — consider a log transform or weighted regression.
04

Watch the Concepts

Two clear explainers from StatQuest with Josh Starmer covering least-squares fitting, residuals and R² — the foundations of this experiment.

StatQuestFitting a Line to Data (Least Squares)How residuals are measured and minimised to fit the best line.
StatQuestLinear Regression, Clearly ExplainedLeast squares, residuals and how R² measures the quality of a fit.

Videos are embedded from YouTube and belong to their creators. If a frame is blank, your network may block YouTube — search the titles on youtube.com.

05

The Program

Fit the model, then produce the residual plot and the metrics. Swap in any CSV with one predictor and one target.

1 — fit_regression.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_squared_error

df = pd.read_csv("data.csv")        # columns: x, y
X = df[["x"]].values
y = df["y"].values

model = LinearRegression().fit(X, y)
y_pred = model.predict(X)
residuals = y - y_pred

print("slope:", model.coef_[0], "intercept:", model.intercept_)
print("R2  :", r2_score(y, y_pred))
print("RMSE:", np.sqrt(mean_squared_error(y, y_pred)))
2 — residual_plot.py
# Residual plot: residual vs fitted value
plt.figure(figsize=(6,4))
plt.scatter(y_pred, residuals, color="#f0743f", edgecolor="k", alpha=0.7)
plt.axhline(0, color="#2b7fb5", linestyle="--")   # the zero line
plt.xlabel("Fitted value (ŷ)"); plt.ylabel("Residual")
plt.title("Residual Plot"); plt.tight_layout(); plt.show()

# Quick one-liner with seaborn:
# import seaborn as sns; sns.residplot(x=y_pred, y=y)
3 — full_diagnostics.py (statsmodels)
import statsmodels.api as sm

Xc = sm.add_constant(X)          # add intercept term
ols = sm.OLS(y, Xc).fit()
print(ols.summary())             # R2, coefficients, p-values

# residuals vs fitted, with a Q-Q plot for normality
sm.qqplot(ols.resid, line="s"); plt.show()
06

Procedure & Result

Steps followed

1 · Load
Read the dataset (x, y) from CSV.
2 · Fit
Fit a least-squares regression line.
3 · Predict
Compute fitted values ŷ.
4 · Residuals
e = y − ŷ for every point.
5 · Plot
Scatter residuals vs fitted; add zero line.
6 · Interpret
Read the pattern; report R² and RMSE.

Result

A regression model was fitted to the dataset and its residual plot was produced. The model quality was reported using R² and RMSE, and the residual plot was used to check the regression assumptions, demonstrating CO3.

ConclusionA high R² alone doesn't prove a good model — the residual plot is the real test. Random, evenly-spread residuals around zero confirm the linear fit; curves, funnels or far-off points warn that the model needs a different shape, a transform, or a closer look at outliers.
07

Viva Questions

What is a residual?
A residual is the difference between an observed value and the value predicted by the model: e = y − ŷ. It measures the error left over for each data point after fitting.
What does a good residual plot look like?
Points scattered randomly around the horizontal zero line with roughly constant spread and no visible pattern. That indicates the linear model is appropriate.
What does a curved pattern in the residual plot indicate?
That the true relationship is non-linear, so a straight line is the wrong model. A polynomial term or a transformation of the variables is usually needed.
What is heteroscedasticity and how does the residual plot show it?
Heteroscedasticity is non-constant variance of the errors. In the residual plot it appears as a funnel/fan shape where the spread grows (or shrinks) with the fitted value. A log transform or weighted least squares can help.
Difference between R² and RMSE?
R² is the proportion of variance in y explained by the model (0–1, unitless). RMSE is the typical size of the prediction error in the original units of y. R² judges relative fit; RMSE judges absolute error.
What is the least-squares method?
It chooses the line that minimises the sum of squared residuals, Σ(yᵢ − ŷᵢ)², giving the unique slope and intercept that best fit the data in that sense.
What are the key assumptions of linear regression?
Linearity, independence of errors, constant error variance (homoscedasticity), and approximately normal residuals. Residual and Q-Q plots are used to check them.
How do outliers affect a regression line?
An outlier (especially with extreme x) can pull the line toward itself, inflating error and distorting slope and intercept. It shows up as a single far-from-zero point in the residual plot.