$ cat linear-regression-from-scratch.md
Linear Regression from Scratch
Overview
Linear regression is one of the most fundamental algorithms in machine learning and statistics. It models the relationship between a dependent variable (target) and one or more independent variables (features) by fitting a linear equation to observed data.
What is Linear Regression?
Linear regression assumes that there is a linear relationship between the input variables (X) and the output variable (y). The goal is to find the best-fitting straight line (or hyperplane in higher dimensions) through the data points.
Mathematical Foundation
The linear regression model can be expressed as:
y = w₁x₁ + w₂x₂ + ... + wₙxₙ + b
Or in vector notation:
y = X·w + b
Where:
- y is the predicted output
- X is the input feature matrix
- w (weights) are the coefficients that define the relationship between features and target
- b (bias) is the intercept term
Key Concepts
Cost Function (Mean Squared Error)
The cost function measures how well our model fits the data:
MSE = (1/n) Σ(yᵢ - ŷᵢ)²
Where yᵢ is the actual value and ŷᵢ is the predicted value.
Gradient Descent
We use gradient descent to minimize the cost function by iteratively adjusting the weights and bias:
w = w - α · ∂MSE/∂w
b = b - α · ∂MSE/∂b
Where α (alpha) is the learning rate that controls the step size.
Implementation Details
Our implementation includes:
Core Components
-
Initialization (
__init__)- Initializes weights (w) and bias (b) to None
- Parameters are learned during training
-
Training (
fit)- Accepts training data (X, y) and hyperparameters
- Initializes weights to zeros and bias to 0
- Iteratively updates parameters using gradient descent
- Supports early stopping to prevent overfitting
-
Prediction (
predict)- Computes predictions using learned weights:
X @ w + b - Validates that model has been trained
- Computes predictions using learned weights:
-
Evaluation (
evaluate)- MSE (Mean Squared Error): Average squared difference between predictions and actual values
- MAE (Mean Absolute Error): Average absolute difference
- R² Score: Proportion of variance in the dependent variable explained by the model (1.0 is perfect)
Training Parameters
- alpha (learning rate): Controls how much to adjust weights in each iteration (default: 0.01)
- n_iter: Maximum number of training iterations (default: 1000)
- early_stopping: Stops training when improvement plateaus (default: False)
- patience: Number of iterations to wait before stopping (default: 20)
- min_delta: Minimum improvement required to reset patience counter (default: 1e-4)
Data Preprocessing
The preprocessing module includes:
Feature Normalization
normalize_prices(data)
- Applies log transformation to price and area (handles skewed distributions)
- Standardizes numerical features (bedrooms, bathrooms, stories, parking) using StandardScaler
Categorical Encoding
encode_cat_features(data)
- One-hot encodes furnishing status
- Converts boolean yes/no features to binary (0/1)
Use Cases
Linear regression is widely used across various domains:
1. Real Estate Price Prediction
Predict housing prices based on features like:
- Square footage
- Number of bedrooms/bathrooms
- Location
- Age of property
Example: Our implementation uses housing data to predict prices based on area, rooms, and amenities.
2. Sales Forecasting
Businesses use linear regression to predict:
- Revenue based on advertising spend
- Sales volume based on seasonal factors
- Customer lifetime value
3. Risk Assessment
Financial institutions apply it for:
- Credit scoring
- Insurance premium calculation
- Investment portfolio analysis
4. Medical Research
Healthcare applications include:
- Predicting patient outcomes based on clinical measurements
- Dosage optimization
- Disease progression modeling
5. Economics
Economists use it to:
- Model GDP growth
- Analyze inflation trends
- Forecast unemployment rates
6. Engineering
Applications in engineering:
- Predicting system performance
- Quality control
- Resource optimization
Advantages
- Interpretability: Coefficients directly show the relationship between features and target
- Simplicity: Easy to understand and implement
- Fast Training: Computationally efficient, even on large datasets
- No Hyperparameter Tuning: Minimal configuration needed (mainly learning rate)
- Probabilistic Interpretation: Provides confidence intervals for predictions
Limitations
- Linearity Assumption: Only models linear relationships
- Sensitive to Outliers: Extreme values can significantly impact the model
- Multicollinearity: Highly correlated features can cause instability
- Feature Engineering: May require transformations for non-linear patterns
- Homoscedasticity: Assumes constant variance in errors
Mathematical Derivation
Gradient Computation
For weights:
∂MSE/∂w = -(2/n) · Xᵀ(y - ŷ)
For bias:
∂MSE/∂b = -(2/n) · Σ(y - ŷ)
Our implementation:
dw = (-2 / n_samples) * (X.T @ (y - pred_y))
db = (-2 / n_samples) * np.sum(y - pred_y)
Parameter Update
self.w = self.w - alpha * dw
self.b = self.b - alpha * db
This iterative process continues until convergence or the maximum number of iterations is reached.
Performance Metrics
Mean Squared Error (MSE)
- Penalizes larger errors more heavily
- Useful when large errors are particularly undesirable
- Same units as squared target variable
Mean Absolute Error (MAE)
- More robust to outliers than MSE
- Easier to interpret (average prediction error)
- Same units as target variable
R² Score (Coefficient of Determination)
- Ranges from 0 to 1 (can be negative for poor models)
- 1.0 indicates perfect predictions
- 0.0 means model performs no better than predicting the mean
- Useful for comparing models
Best Practices
- Feature Scaling: Normalize or standardize features for faster convergence
- Handle Missing Data: Impute or remove missing values before training
- Check Assumptions: Verify linearity, independence, and homoscedasticity
- Cross-Validation: Use k-fold cross-validation to assess generalization
- Regularization: Consider Ridge or Lasso regression for high-dimensional data
- Monitor Training: Track loss over iterations to detect convergence issues
Conclusion
Our from-scratch implementation demonstrates the core principles of linear regression using only NumPy for numerical computations. By implementing gradient descent manually, we gain a deeper understanding of how the algorithm learns from data and optimizes its parameters.
This foundational knowledge serves as a stepping stone to more complex machine learning algorithms, including polynomial regression, regularized models, and neural networks.