Lesson Introduction

Hello! Today, we will learn about the R-squared metric, a vital measure in machine learning. Have you ever wondered how to measure how well your model fits the real data? That’s exactly what the R-squared metric helps with! By the end of this lesson, you'll understand what R-squared is, why it’s essential, and how to calculate it using Python.

Understanding R-squared
Interpreting R-squared

Why is R-squared Important?

Think about predicting someone’s height based on their age. If your predictions are very close to the actual heights, your model does a good job. If predictions are off, your model needs improvement. R-squared gives you a single number to show how well your model performs.

Higher R-squared values mean the model better explains the variability of the target variable. For instance, a high R-squared value in a model predicting house prices means the model accurately predicts based on inputs like square footage and number of bedrooms.

If your model has an R-squared of 0.85, it tells you 85% of the variance in house prices is explained by your model.

Calculating R-squared in Python

Here’s how to calculate R-squared using Python. Let’s take a look at the code snippet first and explain it step-by-step.

Python
from sklearn.metrics import r2_score
import numpy as np

# Sample regression dataset: True values
y_true = np.array([3.0, -0.5, 2.0, 7.0])
y_pred = np.array([2.5, 0.0, 2.0, 8.0])

r2 = r2_score(y_true, y_pred)
print(f"R-squared: {r2}")  # R-squared: 0.948
  1. Importing Libraries: First, we import the function r2_score from the sklearn.metrics module. This tool makes calculating R-squared straightforward.

  2. Calculating R-squared: Using the r2_score function with y_true and y_pred, we calculate the R-squared value

  3. Displaying the Result: We print out the R-squared value

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal