Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 64

Regression Models with scikit-learn

Recommended resources

Hello! Welcome to your next lesson in our journey through supervised learning.

In our last session, we delved into regularization with Ridge and Lasso regression. You learned the theory behind how these methods prevent overfitting by adding a penalty for model complexity. We also had a first look at their implementation in scikit-learn.

Today, we're going to put all the pieces together. This lesson is about establishing a standard, practical workflow for training and evaluating regression models using scikit-learn. The process you'll learn today is a fundamental blueprint that you will use repeatedly for many different machine learning models, not just regression.

Our goal is to solidify your understanding of the end-to-end process: from preparing your data to assessing how well your model performs on unseen data.

The Standard Machine Learning Workflow

A typical supervised learning project follows a sequence of well-defined steps. We'll walk through each one, using scikit-learn's tools to build a linear regression model.

The workflow looks like this:

  1. Prepare Data: Separate features (X) from the target (y).
  2. Split Data: Divide the data into training and testing sets.
  3. Train Model: Fit a model to the training data.
  4. Make Predictions: Use the trained model to predict outcomes for the test set.
  5. Evaluate Performance: Measure how well the model's predictions match the actual values.

Let's begin with a hands-on project.


A Practical Walkthrough: Predicting E-commerce Spending

To make this concrete, we'll follow a project that aims to predict how much an e-commerce customer will spend per year based on their usage patterns. The following video provides an excellent end-to-end demonstration of the scikit-learn workflow. We will watch it in segments as we cover each step.

Linear Regression in Python - Full Project for Beginners

First, let's get acquainted with the dataset and the project's goal. Watch this introductory part of the 'Linear Regression in Python - Full Project for Beginners' video by Alejandro AO.

Watch from the beginning to 05:45. Pay attention to how the data is loaded with pandas and inspected using .info() and .describe(). Notice how the presenter identifies the numerical features that will be used as predictors (X) and the target variable (y, 'Yearly Amount Spent').

As you saw, the first step is always to understand your data and clearly define your features (X), which are the inputs to your model, and your target (y), which is the value you want to predict.


Step 1: Splitting Data into Training and Test Sets

This is one of the most critical steps in machine learning. We train our model on one portion of the data (the training set) and then evaluate its performance on a completely separate, unseen portion (the test set). This simulates how the model would perform on new, real-world data.

Scikit-learn provides a convenient function for this: train_test_split.

Linear Regression in Python - Full Project for Beginners

Now, let's see how to split the data. This segment of the video clearly explains the purpose and implementation of train_test_split.

Watch from 20:05 to 25:35. Focus on: How the feature matrix X and target vector y are created. The roles of the test_size and random_state parameters. The four outputs of the function: X_train, X_test, y_train, and y_test.

The random_state parameter is important for reproducibility. By setting it to a specific number, you ensure that you get the exact same split every time you run your code, which is essential for debugging and consistent results.


Step 2: Training the Model

With our data split, we can now train our model. This involves three simple actions:

  1. Import the model class from scikit-learn (e.g., LinearRegression).
  2. Create an instance of the model.
  3. Call the .fit() method on the model instance, passing the training data (X_train, y_train).

The .fit() method is where the model "learns" the relationship between the features and the target from the training data.

Linear Regression in Python - Full Project for Beginners

Let's watch how to train the linear regression model.

Watch from 27:11 to 29:08. Observe the straightforward process of importing LinearRegression, instantiating it, and then calling the .fit() method.

That's it! The model is now trained. For linear models, the learned parameters are stored in the .coef_ (coefficients) and .intercept_ attributes.


Step 3: Making Predictions

Once the model is trained, we can use it to make predictions on new data. We use the .predict() method and pass it the features from our test set (X_test). The model will return an array of predicted target values.

Linear Regression in Python - Full Project for Beginners

This short clip shows how to use the trained model to generate predictions.

Watch from 33:05 to 35:07. Note that the .predict() method is called on the test data, X_test, which the model has not seen before.

We now have the model's predictions (y_pred) and the actual ground truth values (y_test). The final step is to compare them.


Step 4: Evaluating Model Performance

How good is our model? Evaluation is crucial for understanding a model's strengths and weaknesses. We can evaluate it both visually and with quantitative metrics.

Visual Evaluation

A simple and intuitive way to assess a regression model is to plot the actual values (y_test) against the predicted values (y_pred). If the model is perfect, all points will lie on a straight diagonal line. The more scattered the points are, the worse the model.

Machine Learning in Python: Building a Linear Regression Model

Let's see how to create and interpret a scatter plot for visual evaluation. This video from Data Professor provides a clear example.

Watch from 10:25 to 11:54. The video uses Seaborn to create a scatter plot of y_test vs y_pred. Notice how a tight, linear cluster of points indicates good performance.

Quantitative Evaluation with Metrics

While visuals are helpful, we need objective metrics to quantify performance. For regression, the most common metrics are:

  • Mean Squared Error (MSE): The average of the squared differences between the actual and predicted values. It heavily penalizes large errors.
*This diagram provides a great visual intuition for how MSE is calculated by squaring the differences (errors) between actual and predicted points and then averaging them.*
  • Root Mean Squared Error (RMSE): The square root of the MSE. A key advantage is that it is in the same units as the target variable, making it more interpretable. For our e-commerce example, an RMSE of 10 would mean our model's predictions are, on average, off by about $10.

  • R-squared (R² Score): The "coefficient of determination." It represents the proportion of the variance in the target variable that is predictable from the features.

    • R² = 1: The model explains all the variability of the data.
    • R² = 0: The model does not explain any of the variability (it's no better than just predicting the mean of the target).
    • R² < 0: The model is worse than predicting the mean.

The following guide gives clear, concise definitions for these metrics.

Sklearn Linear Regression: A Complete Guide with ...

To solidify your understanding of these metrics, please read the 'Evaluating model performance' section from the DataCamp article 'Sklearn Linear Regression'.

Read the text under the heading 'Evaluating model performance' until just before the next major heading ('Working with Multiple Linear Regression'). Focus on the definitions of R², MSE, and RMSE and how to interpret them.

Now, let's see how to calculate and interpret these metrics in our project.

Linear Regression in Python - Full Project for Beginners

This final clip from the project video demonstrates how to use sklearn.metrics to calculate evaluation scores and, importantly, how to interpret them in the context of the problem.

Watch from 35:07 to 42:27. Pay close attention to the explanation of what the Mean Absolute Error (MAE) and RMSE values mean in terms of dollars. Also, note the analysis of residuals, which is a good practice for diagnosing linear regression models.


A Complete Code Example

Here is a consolidated Python code block that summarizes the entire workflow. This example uses Ridge regression, connecting back to our previous lesson, and includes feature scaling, which is crucial for regularized models.

import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error, r2_score

# 1. Load and Prepare Data
housing = fetch_california_housing()
X = pd.DataFrame(housing.data, columns=housing.feature_names)
y = housing.target

# 2. Split Data
# Using 80% for training and 20% for testing
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 3. Preprocess Data (Feature Scaling)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test) # Use the scaler fitted on the training data

# 4. Train Model
# We'll use Ridge regression with a chosen alpha
model = Ridge(alpha=1.0)
model.fit(X_train_scaled, y_train)

# 5. Make Predictions
y_pred = model.predict(X_test_scaled)

# 6. Evaluate Performance
mse = mean_squared_error(y_test, y_pred)
rmse = mse ** 0.5  # or np.sqrt(mse)
r2 = r2_score(y_test, y_pred)

print(f"Model: Ridge Regression (alpha=1.0)")
print("--------------------------------------")
print(f"R-squared (R²): {r2:.4f}")
print(f"Mean Squared Error (MSE): {mse:.4f}")
print(f"Root Mean Squared Error (RMSE): {rmse:.4f}")

Test your understanding!

You have built two regression models to predict apartment rental prices in a city where the average rent is $2,500. After evaluation, you get the following results:

  • Model A: RMSE = $800, R² = 0.35
  • Model B: RMSE = $300, R² = 0.88

Which model is better, and why? Explain your reasoning based on both the RMSE and R² values.

Show answer

Model B is significantly better.

Here's the reasoning:

  • RMSE: Model B has an RMSE of $300, while Model A has an RMSE of $800. Since RMSE is in the same units as the target (dollars), this means Model B's predictions are, on average, off by about $300, whereas Model A's are off by $800. A lower error is better, so Model B wins on this metric. An error of $300 on an average rent of $2,500 is much more acceptable than an error of $800.
  • R-squared (R²): Model B has an R² of 0.88, meaning it explains 88% of the variance in rental prices. Model A only explains 35% (R² = 0.35). A higher R² indicates a better fit, so Model B is the clear winner here as well. It captures much more of the underlying pattern in the data.

In summary, Model B makes more accurate predictions (lower RMSE) and provides a much better explanation of the data (higher R²).


Conclusion

Excellent work! You have now walked through the fundamental workflow for building and evaluating a supervised learning model in scikit-learn. This process is your bread and butter as a machine learning practitioner.

Key Takeaways:

  • The standard workflow is: Prepare Data → Split → Train → Predict → Evaluate.
  • train_test_split is essential for creating training and test sets to get an unbiased estimate of model performance.
  • The model learns from the training data using the .fit() method.
  • Predictions are made on unseen test data using the .predict() method.
  • Performance is quantified using metrics like MSE, RMSE, and R², each providing a different perspective on model accuracy.
  • Feature scaling (StandardScaler) is a critical preprocessing step, especially for models sensitive to feature magnitudes like Ridge and Lasso.

Preview of the Next Lesson:

We can now build a model and measure how well it predicts. But what is the model actually telling us? In the next lesson, we will focus on interpreting regression coefficients. You will learn how to analyze the coef_ attribute of your trained model to understand the relationship between each feature and the target variable, answering questions like, "How much does the price increase for each additional bedroom?" This is a key step in turning a machine learning model into actionable insights.