Supervised Learning Fundamentals: Regression

10 min read

Supervised Learning Fundamentals: Regression

Welcome! 👋 This guide will walk you through the fundamentals of regression, a core concept in supervised machine learning. We'll start with the basics of linear regression and then move on to more advanced techniques. Our focus will be on practical, industry-standard knowledge to get you up and running with scikit-learn.

First things first, let's get your environment set up.

Installation ⚙️

It's highly recommended to work within a virtual environment to avoid conflicts with other packages.

  1. Install Python: Make sure you have Python 3 (64-bit) installed. You can get it from the official website.
  2. Create a virtual environment:
    bash
    python -m venv my_sklearn_env
  3. Activate the environment:
    • On Windows:
      bash
      my_sklearn_env\Scripts\activate
    • On macOS and Linux:
      bash
      source my_sklearn_env/bin/activate
  4. Install scikit-learn: The easiest way is using pip.
    bash
    pip install -U scikit-learn

Now that you're all set up, let's dive in!


1. Linear Regression: Predicting Continuous Values

The Problem: What are we trying to solve?

Imagine you're trying to predict the price of a house based on its size in square feet. You have a bunch of data for houses that have already been sold, including their size and price. This is a classic regression problem: we want to predict a continuous numerical value (price) based on some input features (size).

The Solution: Linear Regression

Linear regression is a fundamental algorithm that models the relationship between a dependent variable (what you're trying to predict, e.g., house price) and one or more independent variables (the features, e.g., house size). It does this by fitting a straight line to the data.

Think of it like drawing the "best-fit" line through a scatter plot of your data points. This line can then be used to make predictions for new, unseen data.

Under the Hood (in simple terms):
Linear Regression finds the straight line that minimizes the sum of the squared differences between the actual data points and the points on the line. This is called the "Ordinary Least Squares" method.

Here's the equation for a simple linear regression with one feature:

y = w_1 * x + b

  • y is the predicted value (e.g., house price).
  • x is the input feature (e.g., house size).
  • w_1 is the coefficient or weight of the feature. It represents the change in y for a one-unit change in x.
  • b is the intercept, which is the value of y when x is 0.

The algorithm's job is to find the optimal values for w_1 and b.

Let's see it in action with scikit-learn: 🚀

python
import numpy as np
from sklearn.linear_model import LinearRegression

# Imagine this is our house size data (in square feet)
X = np.array([[1400], [1600], [1700], [1875], [1100], [1550], [2350], [2450], [1425], [1700]])

# And these are the corresponding house prices (in thousands of dollars)
y = np.array([245, 312, 279, 308, 199, 219, 405, 324, 319, 255])

# Create a Linear Regression model
model = LinearRegression()

# Train the model with our data
model.fit(X, y)

# Let's predict the price of a 2000 sq ft house
predicted_price = model.predict([[2000]])

print(f"Predicted price for a 2000 sq ft house: ${predicted_price[0]:.2f}k")
print(f"Model coefficient (w_1): {model.coef_[0]:.2f}")
print(f"Model intercept (b): {model.intercept_:.2f}")

Fun Fact: The concept of least squares, which is the foundation of linear regression, was first published in 1805 by Adrien-Marie Legendre, a French mathematician. However, Carl Friedrich Gauss, a German mathematician, claimed he had been using it since 1795 but hadn't published it. This led to a bit of a mathematical feud!


2. Evaluating Regression Models: MSE, RMSE, and R-squared

The Problem: How good is our prediction?

So, we've built a model and it's making predictions. But how do we know if it's any good? Are the predictions close to the actual values, or are they way off? We need some metrics to measure the performance of our regression model.

The Solutions: Key Evaluation Metrics

Here are three of the most common metrics used to evaluate regression models.

Mean Squared Error (MSE) 📉

MSE measures the average of the squares of the errors. An "error" is the difference between the actual value and the predicted value. Squaring the errors gives more weight to larger errors.

Formula:
MSE = (1/n) * Σ(y_i - ŷ_i)^2

  • n is the number of data points.
  • y_i is the actual value.
  • ŷ_i is the predicted value.

A lower MSE is better. An MSE of 0 means the model is perfect.

Root Mean Squared Error (RMSE) 📏

RMSE is simply the square root of the MSE. The advantage of RMSE is that its units are the same as the target variable. So, if you're predicting house prices in dollars, the RMSE will also be in dollars, making it easier to understand.

Formula:
RMSE = sqrt(MSE)

Like MSE, a lower RMSE indicates a better fit.

R-squared (R²) - Coefficient of Determination 🎯

R-squared tells you what proportion of the variance in the dependent variable is predictable from the independent variable(s). In simpler terms, it gives you an idea of how much of the "story" of the target variable your model can explain.

  • An R² of 1 indicates that the model perfectly predicts the target variable.
  • An R² of 0 means the model does no better than simply predicting the mean of the target variable.
  • It can even be negative if the model is arbitrarily worse than just predicting the mean.

Let's calculate these metrics with scikit-learn:

python
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

# Sample data
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 5, 4, 5])

# Create and train the model
model = LinearRegression()
model.fit(X, y)

# Make predictions
y_pred = model.predict(X)

# Calculate the metrics
mse = mean_squared_error(y, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y, y_pred)

print(f"Mean Squared Error (MSE): {mse:.2f}")
print(f"Root Mean Squared Error (RMSE): {rmse:.2f}")
print(f"R-squared (R²): {r2:.2f}")

3. Polynomial Regression: Handling Non-Linear Trends

The Problem: What if a straight line isn't enough?

Linear regression is great, but it assumes a linear relationship between the features and the target. What if the relationship is curved? For example, the relationship between a car's speed and its fuel efficiency might not be a straight line. Using a straight line to model this would lead to poor predictions.

The Solution: Polynomial Regression

Polynomial regression allows us to model non-linear relationships by fitting a polynomial equation to the data. It's still considered a type of linear regression because we are still solving for the coefficients of a linear equation, but we introduce polynomial terms of the features.

Under the Hood:
We create new features by raising the original features to a certain power. For example, if we have a feature x, we can create a new feature x^2. Then, we fit a linear regression model to these new features.

The equation for a simple polynomial regression of degree 2 would be:

y = w_1*x + w_2*x^2 + b

Let's see this in action:

python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

# Let's create some non-linear data
X = np.arange(1, 11).reshape(-1, 1)
y = X**2 + np.random.randn(10, 1) * 2

# Create polynomial features (degree 2)
poly_features = PolynomialFeatures(degree=2, include_bias=False)
X_poly = poly_features.fit_transform(X)

# Fit a linear regression model to the polynomial features
model = LinearRegression()
model.fit(X_poly, y)
y_poly_pred = model.predict(X_poly)

# For comparison, let's also fit a simple linear regression model
linear_model = LinearRegression()
linear_model.fit(X, y)
y_linear_pred = linear_model.predict(X)

# Plot the results
plt.scatter(X, y, color='blue', label='Actual data')
plt.plot(X, y_poly_pred, color='red', label='Polynomial Regression (degree 2)')
plt.plot(X, y_linear_pred, color='green', label='Linear Regression')
plt.title('Polynomial vs. Linear Regression')
plt.xlabel('X')
plt.ylabel('y')
plt.legend()
plt.show()

You'll notice the red curved line (polynomial regression) fits the data much better than the straight green line (linear regression).


4. Regularization Techniques: Ridge, Lasso, and ElasticNet

The Problem: My model is too complex and overfits!

Sometimes, a model can become too complex and learn the training data too well, including the noise. This is called overfitting. An overfitted model performs great on the training data but poorly on new, unseen data. This can happen in polynomial regression if you use a very high degree.

Imagine you're a student studying for an exam. If you just memorize the answers to the practice questions (training data), you might do well on those specific questions, but you'll likely fail the actual exam (new data) because you didn't learn the underlying concepts.

The Solution: Regularization

Regularization is a technique used to prevent overfitting by adding a penalty term to the loss function. This penalty discourages the model from having overly large coefficients, which can be a sign of overfitting.

Ridge Regression (L2 Regularization)

Ridge regression adds a penalty equal to the square of the magnitude of the coefficients. This "shrinks" the coefficients towards zero, but they rarely become exactly zero.

Use Ridge when: you believe all your features are relevant to the outcome.

Lasso Regression (L1 Regularization)

Lasso (Least Absolute Shrinkage and Selection Operator) regression adds a penalty equal to the absolute value of the magnitude of the coefficients. A key feature of Lasso is that it can shrink some coefficients all the way to zero, effectively performing feature selection.

Use Lasso when: you believe some features are irrelevant and you want to select a smaller subset of important features.

ElasticNet

ElasticNet is a combination of Ridge and Lasso. It has a mixing parameter that lets you control the blend of L1 and L2 regularization. It can be useful when you have multiple correlated features, as Lasso might arbitrarily pick one of them.

Let's implement these in scikit-learn:

python
from sklearn.linear_model import Ridge, Lasso, ElasticNet
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split

# Create some sample data
X, y = make_regression(n_samples=100, n_features=10, noise=15, random_state=42)

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)

# Ridge Regression
ridge = Ridge(alpha=1.0) # alpha is the regularization strength
ridge.fit(X_train, y_train)
print(f"Ridge R-squared on test data: {ridge.score(X_test, y_test):.2f}")

# Lasso Regression
lasso = Lasso(alpha=1.0)
lasso.fit(X_train, y_train)
print(f"Lasso R-squared on test data: {lasso.score(X_test, y_test):.2f}")
print(f"Number of features used by Lasso: {np.sum(lasso.coef_ != 0)}")


# ElasticNet
elastic_net = ElasticNet(alpha=1.0, l1_ratio=0.5) # l1_ratio controls the mix
elastic_net.fit(X_train, y_train)
print(f"ElasticNet R-squared on test data: {elastic_net.score(X_test, y_test):.2f}")

Analogy Time! 📦

Imagine you're moving to a new apartment. Your goal is to pack everything efficiently (minimize the error/loss).

  • No Regularization (Overfitting): You try to stuff everything you own into boxes, even the junk you don't need. Your apartment is perfectly empty (great training performance), but your new place is cluttered and unusable (poor test performance).
  • Ridge Regression: You have a rule that for every item you pack, you have to pay a small "weight tax" squared. This encourages you to pack lighter items and be more mindful, but you still end up taking most of your stuff.
  • Lasso Regression: For every item you pack, you pay a flat "item tax". This makes you question if you really need that broken lamp or those old magazines. You end up leaving a lot of unnecessary stuff behind (some coefficients become zero).
  • ElasticNet: You use a combination of the weight tax and the item tax to decide what to pack.

References for Extra Reading

Challenge

You are tasked with building a regression model for a dataset with a known non-linear relationship. To accomplish this, you will need to implement a machine learning pipeline that involves feature transformation and regularized regression.

Your tasks are:

  1. Create Polynomial Features: Instantiate a PolynomialFeatures transformer for a polynomial of degree 10. Do not include a bias term in this transformation step, as the regression model will handle its own intercept.
  2. Transform Data: Use the transformer you created to fit and transform the original feature matrix X into the new polynomial feature matrix.
  3. Initialize the Model: Create an instance of the Ridge regression model. Set the regularization strength alpha to 0.5.
  4. Train the Model: Train the Ridge model using the transformed polynomial features and the target variable y.
  5. Predict and Evaluate: Use the trained model to make predictions on the same transformed polynomial features. Then, calculate the Mean Squared Error (MSE) between the original target y and your predictions.
  6. Display Results: Print the model's learned coefficients (coef_) and the calculated MSE according to the format specified in the expected output description.

Expected result

Your solution should print exactly two lines to standard output.

  1. The first line must be the string "Coefficients:", followed by a space, and then the NumPy array of the model's coefficients. The array will contain coefficients for the polynomial features from degree 1 to 10.
  2. The second line must be the string "Mean Squared Error:", followed by a space, and then the floating-point value of the calculated Mean Squared Error.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.