30 Mins

2. Supervised Learning: Regression

Linear Regression Mathematical Intuition and Scaling Requirements

Linear regression is the foundational method for modeling a continuous relationship between a dependent target variable and one or more independent feature variables. Mathematically, the model predicts the target using a linear combination of features, represented by the equation: y = w1*x1 + w2*x2 + ... + wn*xn + b. Here, w represents the weights or coefficients, x represents the feature values, and b represents the bias or intercept. The objective of ordinary least squares (OLS) regression is to minimize the Residual Sum of Squares (RSS), which measures the variance between the actual and predicted values.

While standard OLS is scale-invariant when calculating predictions, feature scaling becomes vital when dealing with optimization stability or regularized models. If one feature has values in the thousands and another has values between zero and one, the feature with the larger scale will dominate the gradient descent updates and skew the coefficients. Standardizing features using a method like Z-score scaling (StandardScaler) translates features to have a mean of zero and a standard deviation of one. This step guarantees that all variables contribute equitably to the cost function during training.

Operator Note: Always scale your features before performing regression if you plan to introduce regularization later. It ensures that the penalty is applied uniformly across all dimensions.
Python 3
import numpy as np
from sklearn.preprocessing import StandardScaler

# Generate simulated raw features with vastly different scales
np.random.seed(42)
raw_features = np.random.rand(5, 2) * np.array([[1000.0, 0.1]])

# Initialize and apply StandardScaler
scaler = StandardScaler()
scaled_features = scaler.fit_transform(raw_features)

print("Raw Features:\n", raw_features)
print("\nScaled Features:\n", scaled_features)

Regularized Regression Models: Ridge and Lasso Regression (L1/L2 Penalties)

When a regression model contains too many features or highly correlated features, it is prone to overfitting. Regularization introduces an extra penalty term to the loss function to constrain the size of the learned weights. This keeps the model simpler and more generalizable to unseen datasets.

The two most common regularization types are Ridge Regression (L2 penalty) and Lasso Regression (L1 penalty). While Ridge shrinks weights towards zero, Lasso can force coefficients exactly to zero, which provides a form of automatic feature selection. Below is a comparison table outlining their core differences:

FeatureRidge Regression (L2)Lasso Regression (L1)
Penalty TermSum of squared weights (alpha * sum(w^2))Sum of absolute weights (alpha * sum(|w|))
Weight SparsityShrinks weights close to zero but never exactly zeroCan shrink weights to exactly zero
Primary Use CasePrevents overfitting when multicollinearity existsFeature selection and sparse feature sets
Operator Note: Lasso regression acts as an automatic feature selector by driving less informative weights directly to absolute zero.
Python 3
import numpy as np
from sklearn.linear_model import Ridge, Lasso

# Prepare mock regression data
X = np.array([[1.0, 50.0], [2.0, 45.0], [3.0, 12.0], [4.0, 8.0]])
y = np.array([12.5, 14.8, 22.1, 28.3])

# Instantiate Ridge (L2) and Lasso (L1)
ridge_model = Ridge(alpha=1.5)
lasso_model = Lasso(alpha=0.8)

# Fit models to learn parameters
ridge_model.fit(X, y)
lasso_model.fit(X, y)

print("Ridge Coefficients:", ridge_model.coef_)
print("Lasso Coefficients:", lasso_model.coef_)

Evaluating Regression Outcomes in Scikit-learn (Score and Predict)

Once a model is trained, we evaluate its predictive capability using real test data. In Scikit-learn, the .predict(X) method takes a feature matrix as input and returns a continuous prediction vector. These predictions are then compared against the true target labels to assess the accuracy of our model.

To score how well the regression line fits our data, we can call the default .score(X, y) method of a regression model. By default, this method calculates the Coefficient of Determination, also known as the R-squared (R2) score. This score indicates the proportion of total variance in the target variable that is successfully explained by the features. R2 ranges from negative infinity to 1, where 1 represents a perfect prediction and 0 represents a model that simply predicts the mean of the dataset.

Operator Note: An R² score of 1.0 represents a perfect fit, while a score of 0.0 means the model performs no better than a horizontal line predicting the mean of the target variable.
Python 3
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

# Create simple synthetic test and train sets
X_train = np.array([[1], [2], [3], [4], [5]])
y_train = np.array([2.1, 3.8, 6.2, 7.9, 10.1])

# Fit standard regression
model = LinearRegression()
model.fit(X_train, y_train)

# Predict and evaluate outcomes
predictions = model.predict(X_train)
r2_val = model.score(X_train, y_train)
mse_val = mean_squared_error(y_train, predictions)

print("Model Predictions:", predictions)
print("R^2 Score via .score():", r2_val)
print("Mean Squared Error (MSE):", mse_val)

Training a Model and Extracting coef_ and intercept_ Parameters

In Scikit-learn, fitting an estimator triggers an optimization process that learns parameter weights and stores them within internal properties. These properties are identified by a trailing underscore in their variable names, which designates them as learned properties rather than configuration hyperparameters.

For linear models, the coefficients representing weight values are stored inside the .coef_ attribute as a NumPy array. The intercept (or bias term) is stored inside the .intercept_ attribute as a single floating-point number. Utilizing these attributes directly allows us to trace back mathematically how predictions are formulated and debug the specific impact of individual feature variables on the target.

Operator Note: Attributes in Scikit-learn that end with an underscore, like coef_ and intercept_, are estimated or calculated during the fit process and are not available beforehand.
Python 3
import numpy as np
from sklearn.linear_model import LinearRegression

# Multi-feature mock dataset representing size and bedrooms
X = np.array([[1200, 3], [1500, 3], [1800, 4], [2200, 4]])
y = np.array([300000, 340000, 410000, 480000])

# Initialize and fit model
reg = LinearRegression()
reg.fit(X, y)

# Extract internal parameters
weights = reg.coef_
bias = reg.intercept_

print("Learned Weights (coef_):", weights)
print("Learned Bias (intercept_):", bias)

# Manual prediction math: y = X_new * weights + bias
sample_test = np.array([1600, 3])
manual_pred = np.dot(sample_test, weights) + bias
model_pred = reg.predict([sample_test])[0]

print("Manual Predict Output:", manual_pred)
print("Scikit-learn Predict Output:", model_pred)

Knowledge Check

Ready to test your understanding of 2. Supervised Learning: Regression?

Back