Neural Sync Active
Linear Regression with One Variable
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.housesellsforabout350,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:
Where:
- hθ(x) or y^ is the predicted output
- θ0 (intercept/bias): the predicted value when x=0
- θ1 (slope/weight): the change in y^ for a one-unit change in x
- x is the input feature The Cost Function (Mean Squared Error):
Where m is the number of training examples. The 21 is for mathematical convenience — it cancels the 2 when we take the derivative.
Goal: Find θ0,θ1 that minimize J(θ0,θ1).
2.3 Worked Example 1: Hand Calculation with Tiny Dataset
| x (hours studied) | y (exam score) |
|---|---|
| 1 | 50 |
| 2 | 55 |
| 3 | 65 |
| 4 | 70 |
| 5 | 75 |
Step 1: Initialize θ0=0, θ1=0.
Step 2: Compute predictions: hθ(x)=0+0⋅x=0 for all points.
Step 3: Compute MSE cost:
Step 4: Let's fit a line by eye. The data roughly follows y=5x+47:
- h(1)=52, error = 2
- h(2)=57, error = 2
- h(3)=62, error = -3
- h(4)=67, error = -3
- h(5)=72, error = -3
Much better! The optimal line via Normal Equation (next section) gives θ≈[46.0,6.0] with J≈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:
- Start with some θ0,θ1 (often 0 or random)
- Simultaneously update:
- Repeat until convergence Where α is the learning rate — how big a step we take each iteration. The derivatives (for MSE):
(Diagram)
2.5 Worked Example 2: Gradient Descent Step-by-Step
Using our study hours dataset, let's do one iteration with α=0.01.
Current θ: θ0=0,θ1=0
Step 1: Compute predictions (all 0), errors:
- (h−y)=[−50,−55,−65,−70,−75] Step 2: Compute gradient:
Step 3: Update:
Step 4: New predictions:
- h(1)=0.63+2.02(1)=2.65, error = 50 - 2.65 = 47.35
- h(2)=0.63+2.02(2)=4.67, error = 55 - 4.67 = 50.33
- h(3)=0.63+2.02(3)=6.69, error = 65 - 6.69 = 58.31
- h(4)=0.63+2.02(4)=8.71, error = 70 - 8.71 = 61.29
- h(5)=0.63+2.02(5)=10.73, error = 75 - 10.73 = 64.27 Step 5: New cost:
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:
Where X is the design matrix (with a column of 1's for the intercept).
For our study hours dataset:
So θ0=43.5, θ1=6.5. Line: y^=43.5+6.5x.
Predictions:
- x=1: 43.5+6.5=50.0 (perfect match!)
- x=3: 43.5+19.5=63.0 (true = 65, off by 2)
- x=5: 43.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) matrix inversion — doesn't scale beyond ~10,000 features.
2.7 Model Evaluation Metrics
Mean Squared Error (MSE):
Root Mean Squared Error (RMSE):
Interpretation: average prediction error in the same units as y. RMSE = 0 means perfect predictions.
R² (Coefficient of Determination):
R² ranges from (−∞,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=1−43035=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 Use | ❌ When NOT to Use |
|---|---|
| Linear relationship between X and Y | Non-linear relationship (try polynomial regression) |
| Homoscedasticity (constant variance of errors) | Heteroscedasticity (expanding fan shape in residuals) |
| Independence of observations | Time series with autocorrelation |
| No or little multicollinearity | Many irrelevant features without regularization |
| Quick baseline model needed | High-dimensional data (p >> n) — use ridge/lasso |
📐 Key Formulas / Concepts
| Concept | Formula | Notes |
|---|---|---|
| Hypothesis | hθ(x)=θ0+θ1x | Linear model with 1 feature |
| MSE Cost | J(θ)=2m1∑(hθ(x(i))−y(i))2 | Factor 1/2 for derivative convenience |
| Gradient (θ₀) | ∂θ0∂J=m1∑(hθ(x(i))−y(i)) | Average error |
| Gradient (θ₁) | ∂θ1∂J=m1∑(hθ(x(i))−y(i))x(i) | Average error × feature |
| Gradient Descent Update | θj:=θj−α∂θj∂J | Simultaneous update |
| Normal Equation | θ=(XTX)−1XTy | Closed-form, O(n³) |
| R² | R2=1−SStotSSres | Proportion of variance explained |
⚠️ Common Pitfalls
Pitfall 1: Not Adding the Intercept Column
The mistake: Forgetting the column of 1's in X when using the Normal Equation.
Why: The design matrix must include a column of 1's to learn θ0. Without it, the line is forced through the origin.
Fix: Add a column of ones to X before applying (XTX)−1XTy. 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
>X=111246>Q1: For the points (1,2), (2,3), (3,5), find the linear regression line by hand.Step 1: Calculate means: xˉ=2, yˉ=(2+3+5)/3=3.33Step 2: Calculate θ1=∑(xi−xˉ)2∑(xi−xˉ)(yi−yˉ) =(1−2)2+(2−2)2+(3−2)2(1−2)(2−3.33)+(2−2)(3−3.33)+(3−2)(5−3.33) =1+0+1(−1)(−1.33)+0+(1)(1.67)=21.33+1.67=23=1.5Step 3: Calculate θ0=yˉ−θ1xˉ=3.33−1.5(2)=0.33Answer: 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=θ0−0.1(−50)=θ0+5 θ1=θ1−0.1(−200)=θ1+20We 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 and what if it's non-invertible?Answer: The inversion finds the θ that minimizes MSE by setting derivatives to zero. If XTX is non-invertible (singular), it means:
- Some features are linearly dependent (remove them)
- More features than examples (use regularization or reduce features)
Solution: Usenp.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:
>y=4610>,
>XTX=[3121256]>Step 2:
>(XTX)−1=241[56−12−123]>,
>XTy=[2088]>Step 3:
>θ=241[56(20)−12(88)−12(20)+3(88)]=241[1120−1056−240+264]=241[6424]=[2.671]>Step 4:
Step 5: 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 (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:
- No regularization was used with highly overfitted model
- The relationship is non-linear but you used linear regression
- 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: ∂θ∂m1∑(hθ−y)2=m2∑(hθ−y)∂θ∂hθ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]).pythonimport 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:
- Number of features is large (>10,000) — Normal Equation is O(n³)
- Data is very large — use stochastic/mini-batch gradient descent
- You want to add regularization easily
- 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
- Next Topic: Multiple & Polynomial Regression — extending to multiple features
- Related: Gradient Descent Deep Dive — optimization variants
- Related: Regularization — preventing overfitting in linear models
- External: IITM BSCS2004 Week 2, Pattern Recognition and Machine Learning (Bishop) Ch. 3 Join Discord PreviousIntro to MLNextGradient Descent Variants