Quiz 2
Registry Synced

Linear Regression with One Variable

2737 words
14 min read

Reading compass

Now · 🎯 Learning Objectives

Linear Regression with One Variable

🎯 Learning Objectives

  • Explain linear regression in plain English and when to use it
  • Derive the cost function (MSE) for linear regression
  • Implement gradient descent for a univariate linear regression model
  • Solve linear regression analytically using the Normal Equation
  • Evaluate model performance using R² and MSE

📋 Prerequisites

  • Introduction to ML — basic ML concepts (features, labels, training)
  • Differentiation basics — we'll need derivatives for gradient descent
  • Matrix multiplication — for the Normal Equation

📖 Core Content

2.1 Intuition: What Problem Does Linear Regression Solve?

Imagine you're a real estate agent. You notice that bigger houses tend to cost more. A 1000 sq. ft. house sells for about 200,000,whilea2000sq.ft.housesellsforabout200,000, while a 2000 sq. ft. house sells for about350,000. You want to predict the price of a 1500 sq. ft. house. Linear regression finds the "best-fit" straight line through your data points. Once you have that line, you can look up the price for any house size. The "best" line is the one that minimizes the total error — the vertical distance between each data point and the line. (Diagram)

2.2 Formal Definition

The Model:
hθ(x)=θ0+θ1xh_\theta(x) = \theta_0 + \theta_1 x
Where:
  • hθ(x)h_\theta(x) or y^\hat{y} is the predicted output
  • θ0\theta_0 (intercept/bias): the predicted value when x=0x = 0
  • θ1\theta_1 (slope/weight): the change in y^\hat{y} for a one-unit change in xx
  • xx is the input feature The Cost Function (Mean Squared Error):
J(θ0,θ1)=12mi=1m(hθ(x(i))y(i))2J(\theta_0, \theta_1) = \frac{1}{2m} \sum_{i=1}^{m} (h_\theta(x^{(i)}) - y^{(i)})^2
Where mm is the number of training examples. The 12\frac{1}{2} is for mathematical convenience — it cancels the 2 when we take the derivative. Goal: Find θ0,θ1\theta_0, \theta_1 that minimize J(θ0,θ1)J(\theta_0, \theta_1).

2.3 Worked Example 1: Hand Calculation with Tiny Dataset

x (hours studied)y (exam score)
150
255
365
470
575
Step 1: Initialize θ0=0\theta_0 = 0, θ1=0\theta_1 = 0. Step 2: Compute predictions: hθ(x)=0+0x=0h_\theta(x) = 0 + 0 \cdot x = 0 for all points. Step 3: Compute MSE cost:
J(0,0)=110[(050)2+(055)2+(065)2+(070)2+(075)2]J(0,0) = \frac{1}{10}[(0-50)^2 + (0-55)^2 + (0-65)^2 + (0-70)^2 + (0-75)^2] =110[2500+3025+4225+4900+5625]=2027510=2027.5= \frac{1}{10}[2500 + 3025 + 4225 + 4900 + 5625] = \frac{20275}{10} = 2027.5
Step 4: Let's fit a line by eye. The data roughly follows y=5x+47y = 5x + 47:
  • h(1)=52h(1) = 52, error = 2
  • h(2)=57h(2) = 57, error = 2
  • h(3)=62h(3) = 62, error = -3
  • h(4)=67h(4) = 67, error = -3
  • h(5)=72h(5) = 72, error = -3
J(47,5)=110[4+4+9+9+9]=3510=3.5J(47,5) = \frac{1}{10}[4 + 4 + 9 + 9 + 9] = \frac{35}{10} = 3.5
Much better! The optimal line via Normal Equation (next section) gives θ[46.0,6.0]\theta \approx [46.0, 6.0] with J2.0J \approx 2.0.

2.4 Gradient Descent: The Optimization Algorithm

Gradient descent is an iterative method to find the minimum of a function. Think of it like standing on a hill in the fog — you can't see the valley, but you can feel the slope beneath your feet. You take a step in the steepest downward direction, then feel again, step again, until you reach the bottom. Algorithm:
  1. Start with some θ0,θ1\theta_0, \theta_1 (often 0 or random)
  2. Simultaneously update:
θ0:=θ0αθ0J(θ0,θ1)\theta_0 := \theta_0 - \alpha \frac{\partial}{\partial \theta_0} J(\theta_0, \theta_1) θ1:=θ1αθ1J(θ0,θ1)\theta_1 := \theta_1 - \alpha \frac{\partial}{\partial \theta_1} J(\theta_0, \theta_1)
  1. Repeat until convergence Where α\alpha is the learning rate — how big a step we take each iteration. The derivatives (for MSE):
Jθ0=1mi=1m(hθ(x(i))y(i))\frac{\partial J}{\partial \theta_0} = \frac{1}{m} \sum_{i=1}^{m} (h_\theta(x^{(i)}) - y^{(i)}) Jθ1=1mi=1m(hθ(x(i))y(i))x(i)\frac{\partial J}{\partial \theta_1} = \frac{1}{m} \sum_{i=1}^{m} (h_\theta(x^{(i)}) - y^{(i)}) \cdot x^{(i)}
(Diagram)

2.5 Worked Example 2: Gradient Descent Step-by-Step

Using our study hours dataset, let's do one iteration with α=0.01\alpha = 0.01. Current θ: θ0=0,θ1=0\theta_0 = 0, \theta_1 = 0 Step 1: Compute predictions (all 0), errors:
  • (hy)=[50,55,65,70,75](h - y) = [-50, -55, -65, -70, -75] Step 2: Compute gradient:
Jθ0=15(5055657075)=3155=63\frac{\partial J}{\partial \theta_0} = \frac{1}{5}(-50 -55 -65 -70 -75) = \frac{-315}{5} = -63 Jθ1=15[(50)(1)+(55)(2)+(65)(3)+(70)(4)+(75)(5)]\frac{\partial J}{\partial \theta_1} = \frac{1}{5}[(-50)(1) + (-55)(2) + (-65)(3) + (-70)(4) + (-75)(5)] =15[50110195280375]=10105=202= \frac{1}{5}[-50 -110 -195 -280 -375] = \frac{-1010}{5} = -202
Step 3: Update:
θ0:=00.01(63)=0.63\theta_0 := 0 - 0.01(-63) = 0.63 θ1:=00.01(202)=2.02\theta_1 := 0 - 0.01(-202) = 2.02
Step 4: New predictions:
  • h(1)=0.63+2.02(1)=2.65h(1) = 0.63 + 2.02(1) = 2.65, error = 50 - 2.65 = 47.35
  • h(2)=0.63+2.02(2)=4.67h(2) = 0.63 + 2.02(2) = 4.67, error = 55 - 4.67 = 50.33
  • h(3)=0.63+2.02(3)=6.69h(3) = 0.63 + 2.02(3) = 6.69, error = 65 - 6.69 = 58.31
  • h(4)=0.63+2.02(4)=8.71h(4) = 0.63 + 2.02(4) = 8.71, error = 70 - 8.71 = 61.29
  • h(5)=0.63+2.02(5)=10.73h(5) = 0.63 + 2.02(5) = 10.73, error = 75 - 10.73 = 64.27 Step 5: New cost:
J(0.63,2.02)=110(47.352+50.332+58.312+61.292+64.272)J(0.63, 2.02) = \frac{1}{10}(47.35^2 + 50.33^2 + 58.31^2 + 61.29^2 + 64.27^2) =110(2242+2533+3400+3756+4131)=1606210=1606.2= \frac{1}{10}(2242 + 2533 + 3400 + 3756 + 4131) = \frac{16062}{10} = 1606.2
Cost decreased from 2027.5 to 1606.2 — we're moving in the right direction. After many iterations, we'll converge to the optimal values.

2.6 The Normal Equation (Closed-Form Solution)

Gradient descent is iterative. The Normal Equation gives us the answer in one step using matrix algebra:
θ=(XTX)1XTy\theta = (X^T X)^{-1} X^T y
Where XX is the design matrix (with a column of 1's for the intercept). For our study hours dataset:
X=[1112131415],y=[5055657075]X = \begin{bmatrix} 1 & 1 \\ 1 & 2 \\ 1 & 3 \\ 1 & 4 \\ 1 & 5 \end{bmatrix}, \quad y = \begin{bmatrix} 50 \\ 55 \\ 65 \\ 70 \\ 75 \end{bmatrix} XTX=[5151555]X^T X = \begin{bmatrix} 5 & 15 \\ 15 & 55 \end{bmatrix} (XTX)1=15(55)15(15)[5515155]=150[5515155](X^T X)^{-1} = \frac{1}{5(55) - 15(15)} \begin{bmatrix} 55 & -15 \\ -15 & 5 \end{bmatrix} = \frac{1}{50} \begin{bmatrix} 55 & -15 \\ -15 & 5 \end{bmatrix} XTy=[3151010]X^T y = \begin{bmatrix} 315 \\ 1010 \end{bmatrix} θ=150[5515155][3151010]=150[55(315)15(1010)15(315)+5(1010)]\theta = \frac{1}{50} \begin{bmatrix} 55 & -15 \\ -15 & 5 \end{bmatrix} \begin{bmatrix} 315 \\ 1010 \end{bmatrix} = \frac{1}{50} \begin{bmatrix} 55(315) - 15(1010) \\ -15(315) + 5(1010) \end{bmatrix} θ=150[17325151504725+5050]=150[2175325]=[43.56.5]\theta = \frac{1}{50} \begin{bmatrix} 17325 - 15150 \\ -4725 + 5050 \end{bmatrix} = \frac{1}{50} \begin{bmatrix} 2175 \\ 325 \end{bmatrix} = \begin{bmatrix} 43.5 \\ 6.5 \end{bmatrix}
So θ0=43.5\theta_0 = 43.5, θ1=6.5\theta_1 = 6.5. Line: y^=43.5+6.5x\hat{y} = 43.5 + 6.5x. Predictions:
  • x=1x = 1: 43.5+6.5=50.043.5 + 6.5 = 50.0 (perfect match!)
  • x=3x = 3: 43.5+19.5=63.043.5 + 19.5 = 63.0 (true = 65, off by 2)
  • x=5x = 5: 43.5+32.5=76.043.5 + 32.5 = 76.0 (true = 75, off by 1) Pros of Normal Equation: No learning rate, no iterations, guaranteed global minimum. Cons: O(n3)O(n^3) matrix inversion — doesn't scale beyond ~10,000 features.

2.7 Model Evaluation Metrics

Mean Squared Error (MSE):
MSE=1mi=1m(y^(i)y(i))2MSE = \frac{1}{m} \sum_{i=1}^{m} (\hat{y}^{(i)} - y^{(i)})^2
Root Mean Squared Error (RMSE):
RMSE=MSERMSE = \sqrt{MSE}
Interpretation: average prediction error in the same units as yy. RMSE = 0 means perfect predictions. R² (Coefficient of Determination):
R2=1(y^(i)y(i))2(y(i)yˉ)2R^2 = 1 - \frac{\sum(\hat{y}^{(i)} - y^{(i)})^2}{\sum(y^{(i)} - \bar{y})^2}
R² ranges from (,1](-\infty, 1]. An R² of 1 means the model explains all variance. R² of 0 means it's no better than always predicting the mean. Negative R² means it's worse than the mean. For our model: R2=135430=0.919R^2 = 1 - \frac{35}{430} = 0.919 — 91.9% of variance explained. Excellent fit!

2.8 Python Implementation

python
# runnable
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
# Our study hours data
X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)  # Feature matrix (m x 1)
y = np.array([50, 55, 65, 70, 75])             # Target vector
# Create and train the model
model = LinearRegression()
model.fit(X, y)
# Get parameters
print(f"Intercept (θ₀): {model.intercept_:.2f}")
print(f"Slope (θ₁):     {model.coef_[0]:.2f}")
print(f"Model: ŷ = {model.intercept_:.2f} + {model.coef_[0]:.2f}x")
# Predict
y_pred = model.predict(X)
# Evaluate
mse = mean_squared_error(y, y_pred)
r2 = r2_score(y, y_pred)
print(f"MSE: {mse:.2f}")
print(f"RMSE: {np.sqrt(mse):.2f}")
print(f"R²:  {r2:.4f}")
# Predict a new value
x_new = np.array(3.5)
y_new = model.predict(x_new)
print(f"\nPrediction for x=3.5 hours: {y_new[0]:.1f}")
# Plot
plt.scatter(X, y, color='blue', label='Data points')
plt.plot(X, y_pred, color='red', label='Regression line')
plt.xlabel('Hours Studied')
plt.ylabel('Exam Score')
plt.title('Linear Regression: Study Hours vs Exam Score')
plt.legend()
plt.grid(True)
plt.show()

2.9 When to Use / Not Use Linear Regression

When to UseWhen NOT to Use
Linear relationship between X and YNon-linear relationship (try polynomial regression)
Homoscedasticity (constant variance of errors)Heteroscedasticity (expanding fan shape in residuals)
Independence of observationsTime series with autocorrelation
No or little multicollinearityMany irrelevant features without regularization
Quick baseline model neededHigh-dimensional data (p >> n) — use ridge/lasso

📐 Key Formulas / Concepts

ConceptFormulaNotes
Hypothesishθ(x)=θ0+θ1xh_\theta(x) = \theta_0 + \theta_1 xLinear model with 1 feature
MSE CostJ(θ)=12m(hθ(x(i))y(i))2J(\theta) = \frac{1}{2m}\sum(h_\theta(x^{(i)}) - y^{(i)})^2Factor 1/2 for derivative convenience
Gradient (θ₀)Jθ0=1m(hθ(x(i))y(i))\frac{\partial J}{\partial \theta_0} = \frac{1}{m}\sum(h_\theta(x^{(i)}) - y^{(i)})Average error
Gradient (θ₁)Jθ1=1m(hθ(x(i))y(i))x(i)\frac{\partial J}{\partial \theta_1} = \frac{1}{m}\sum(h_\theta(x^{(i)}) - y^{(i)})x^{(i)}Average error × feature
Gradient Descent Updateθj:=θjαJθj\theta_j := \theta_j - \alpha \frac{\partial J}{\partial \theta_j}Simultaneous update
Normal Equationθ=(XTX)1XTy\theta = (X^T X)^{-1} X^T yClosed-form, O(n³)
R2=1SSresSStotR^2 = 1 - \frac{SS_{res}}{SS_{tot}}Proportion of variance explained

⚠️ Common Pitfalls

Pitfall 1: Not Adding the Intercept Column

The mistake: Forgetting the column of 1's in XX when using the Normal Equation. Why: The design matrix must include a column of 1's to learn θ0\theta_0. Without it, the line is forced through the origin. Fix: Add a column of ones to X before applying (XTX)1XTy(X^T X)^{-1} X^T y. In sklearn, LinearRegression does this automatically.

Pitfall 2: Using the Wrong Learning Rate

The mistake: Choosing α too large (diverges) or too small (too slow). Symptom: Large α → cost J increases every iteration. Small α → J barely changes. Fix: Start with α = 0.01, then adjust by factors of 3 (0.001, 0.003, 0.01, 0.03, 0.1). Plot J vs iterations to verify convergence.

Pitfall 3: Not Normalizing Features with Gradient Descent

The mistake: Using features with vastly different scales (e.g., house size 1000-3000, bedrooms 1-5). Why: The cost function becomes elongated, and gradient descent zigzags slowly. Fix: Apply feature scaling (standardization or min-max scaling) before training.

📝 Practice Questions

Q1: For the points (1,2), (2,3), (3,5), find the linear regression line by hand.
Step 1: Calculate means: xˉ=2\bar{x} = 2, yˉ=(2+3+5)/3=3.33\bar{y} = (2+3+5)/3 = 3.33
Step 2: Calculate θ1=(xixˉ)(yiyˉ)(xixˉ)2\theta_1 = \frac{\sum(x_i - \bar{x})(y_i - \bar{y})}{\sum(x_i - \bar{x})^2} =(12)(23.33)+(22)(33.33)+(32)(53.33)(12)2+(22)2+(32)2= \frac{(1-2)(2-3.33) + (2-2)(3-3.33) + (3-2)(5-3.33)}{(1-2)^2 + (2-2)^2 + (3-2)^2} =(1)(1.33)+0+(1)(1.67)1+0+1=1.33+1.672=32=1.5= \frac{(-1)(-1.33) + 0 + (1)(1.67)}{1 + 0 + 1} = \frac{1.33 + 1.67}{2} = \frac{3}{2} = 1.5
Step 3: Calculate θ0=yˉθ1xˉ=3.331.5(2)=0.33\theta_0 = \bar{y} - \theta_1\bar{x} = 3.33 - 1.5(2) = 0.33
Answer: y^=0.33+1.5x\hat{y} = 0.33 + 1.5x Q2: If R² = 0.75, what does this mean?
Answer: 75% of the variance in the target variable is explained by the model. The remaining 25% is unexplained (due to noise or missing features). The model is decent but has room for improvement. Q3: With α = 0.1 and gradient = [-50, -200], what are the new θ values?
Answer: θ0=θ00.1(50)=θ0+5\theta_0 = \theta_0 - 0.1(-50) = \theta_0 + 5 θ1=θ10.1(200)=θ1+20\theta_1 = \theta_1 - 0.1(-200) = \theta_1 + 20
We move in the opposite direction of the gradient (since gradient points uphill, we subtract to go downhill). Since both gradients are negative, we increase θ. Q4: What happens if α is too large in gradient descent?
Answer: The algorithm diverges — the cost J increases instead of decreasing. Each step overshoots the minimum, potentially moving to a worse position. You'll see the cost oscillate or grow unbounded. Solution: reduce α. Q5: Why does the Normal Equation use (XTX)1(X^T X)^{-1} and what if it's non-invertible?
Answer: The inversion finds the θ that minimizes MSE by setting derivatives to zero. If XTXX^T X is non-invertible (singular), it means:
  1. Some features are linearly dependent (remove them)
  2. More features than examples (use regularization or reduce features)
Solution: Use np.linalg.pinv (pseudo-inverse) or apply regularization. Q6: For the dataset (2,4), (4,6), (6,10), predict y when x=5 using the Normal Equation.
Step 1:
>X=[121416]>> X = \begin{bmatrix} 1 & 2 \\ 1 & 4 \\ 1 & 6 \end{bmatrix} >
,
>y=[4610]>> y = \begin{bmatrix} 4 \\ 6 \\ 10 \end{bmatrix} >
Step 2:
>XTX=[3121256]>> X^T X = \begin{bmatrix} 3 & 12 \\ 12 & 56 \end{bmatrix} >
,
>(XTX)1=124[5612123]>> (X^T X)^{-1} = \frac{1}{24}\begin{bmatrix} 56 & -12 \\ -12 & 3 \end{bmatrix} >
Step 3:
>XTy=[2088]>> X^T y = \begin{bmatrix} 20 \\ 88 \end{bmatrix} >
Step 4:
>θ=124[56(20)12(88)12(20)+3(88)]=124[11201056240+264]=124[6424]=[2.671]>> \theta = \frac{1}{24}\begin{bmatrix} 56(20) - 12(88) \\ -12(20) + 3(88) \end{bmatrix} = \frac{1}{24}\begin{bmatrix} 1120 - 1056 \\ -240 + 264 \end{bmatrix} = \frac{1}{24}\begin{bmatrix} 64 \\ 24 \end{bmatrix} = \begin{bmatrix} 2.67 \\ 1 \end{bmatrix} >
Step 5: y^=2.67+1(5)=7.67\hat{y} = 2.67 + 1(5) = 7.67 Q7: What's the difference between MSE and RMSE?
Answer: RMSE is the square root of MSE. Both measure average prediction error, but RMSE is in the same units as the target variable. MSE is in squared units. If predicting house prices in dollars, MSE is in ²(hardtointerpret),whileRMSEisin² (hard to interpret), while RMSE is in (intuitive). Q8: Your model has R² = -0.5. What went wrong?
Answer: A negative R² means the model is worse than predicting the mean. This can happen if:
  1. No regularization was used with highly overfitted model
  2. The relationship is non-linear but you used linear regression
  3. Wrong model entirely — the fit is terrible
Check your model assumptions and consider transformations or a different algorithm. Q9: Which is faster for 100 features — gradient descent or Normal Equation?
Answer: Normal Equation — it's O(n³) = O(100³) = 1,000,000 operations, which is fine for 100 features. Gradient descent would need many iterations over the full dataset. The Normal Equation's weakness is at n > 10,000 where O(n³) becomes prohibitive. Q10: Why is the 1/2 factor in the MSE cost function?
Answer: The 1/2 cancels the 2 that appears when we differentiate the squared error. Without it: θ1m(hθy)2=2m(hθy)hθθ\frac{\partial}{\partial \theta} \frac{1}{m} \sum (h_\theta - y)^2 = \frac{2}{m} \sum (h_\theta - y) \frac{\partial h_\theta}{\partial \theta}
With the 1/2, the 2 cancels out, giving cleaner gradient expressions. It doesn't change the optimal θ — scaling the cost by any positive constant doesn't shift the minimum. Q11: Implement linear regression using gradient descent for 50 iterations on the dataset (x = [1,2,3,4,5], y = [2,4,5,4,6]).
python
import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 5, 4, 6])
m = len(x)

theta0, theta1 = 0, 0
alpha = 0.01

for i in range(50):
    h = theta0 + theta1 * x
    error = h - y
    grad0 = (1/m) * np.sum(error)
    grad1 = (1/m) * np.sum(error * x)
    theta0 -= alpha * grad0
    theta1 -= alpha * grad1

print(f"After 50 iterations: θ₀ = {theta0:.4f}, θ₁ = {theta1:.4f}")
Q12: When would you choose gradient descent over the Normal Equation?
Answer: Choose gradient descent when:
  1. Number of features is large (>10,000) — Normal Equation is O(n³)
  2. Data is very large — use stochastic/mini-batch gradient descent
  3. You want to add regularization easily
  4. The model is not linear (neural networks, etc. — Normal Equation only works for linear regression)
Choose Normal Equation when n < 10,000 and you want the exact solution in one step.

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.