We use regression evaluation to check how well a model predicts numbers. It helps us see if the model's guesses are close to the real answers.
Regression evaluation (MSE, RMSE, R²) in ML Python
from sklearn.metrics import mean_squared_error, r2_score mse = mean_squared_error(true_values, predicted_values) rmse = mean_squared_error(true_values, predicted_values, squared=False) r2 = r2_score(true_values, predicted_values)
mean_squared_error calculates the average squared difference between real and predicted values.
Setting squared=False in mean_squared_error gives the root mean squared error (RMSE), which is easier to understand because it is in the same units as the target.
mse = mean_squared_error([3, -0.5, 2, 7], [2.5, 0.0, 2, 8])
squared=False.rmse = mean_squared_error([3, -0.5, 2, 7], [2.5, 0.0, 2, 8], squared=False)
r2 = r2_score([3, -0.5, 2, 7], [2.5, 0.0, 2, 8])
This program shows how to calculate three common regression evaluation metrics using simple lists of true and predicted values.
from sklearn.metrics import mean_squared_error, r2_score # True values (real answers) true_values = [3, -0.5, 2, 7] # Predicted values from a model predicted_values = [2.5, 0.0, 2, 8] # Calculate Mean Squared Error mse = mean_squared_error(true_values, predicted_values) # Calculate Root Mean Squared Error rmse = mean_squared_error(true_values, predicted_values, squared=False) # Calculate R-squared score r2 = r2_score(true_values, predicted_values) print(f"Mean Squared Error (MSE): {mse:.3f}") print(f"Root Mean Squared Error (RMSE): {rmse:.3f}") print(f"R-squared (R²): {r2:.3f}")
MSE and RMSE measure error size; smaller values mean better predictions.
R² score shows how well the model explains the data; values closer to 1 mean better fit.
RMSE is easier to interpret than MSE because it is in the same units as the target variable.
Regression evaluation helps check prediction accuracy.
MSE and RMSE measure average error size; RMSE is the square root of MSE.
R² score shows how well predictions match real values, with 1 being perfect.
Practice
Solution
Step 1: Understand MSE definition
MSE calculates the average of squared differences between predicted and actual values to measure error size.Step 2: Compare options to definition
Only The average of the squared differences between predicted and actual values correctly describes MSE as average squared error; others describe unrelated concepts.Final Answer:
The average of the squared differences between predicted and actual values -> Option BQuick Check:
MSE = average squared error [OK]
- Confusing MSE with accuracy
- Thinking MSE measures correlation
- Mixing MSE with count of data points
y_true and predicted values y_pred?Solution
Step 1: Recall RMSE formula
RMSE is the square root of the mean of squared differences between true and predicted values.Step 2: Match code to formula
import numpy as np rmse = np.sqrt(np.mean((y_true - y_pred)**2)) correctly computes squared differences, averages them, then takes square root. Others miss steps or use wrong operations.Final Answer:
import numpy as np rmse = np.sqrt(np.mean((y_true - y_pred)**2)) -> Option CQuick Check:
RMSE = sqrt(mean squared error) [OK]
- Using sum instead of mean
- Taking sqrt before mean
- Using absolute difference instead of squared
y_true = [3, -0.5, 2, 7] and predicted values y_pred = [2.5, 0.0, 2, 8], what is the R² score?Solution
Step 1: Calculate R² score formula
R² = 1 - (sum of squared residuals / total sum of squares). Calculate residuals and totals:Step 2: Compute sums
Residuals squared: (3-2.5)^2 + (-0.5-0)^2 + (2-2)^2 + (7-8)^2 = 0.25 + 0.25 + 0 + 1 = 1.5
Total sum squares: sum((y_true - mean(y_true))^2) with mean= (3-0.5+2+7)/4=2.875
Totals: (3-2.875)^2 + (-0.5-2.875)^2 + (2-2.875)^2 + (7-2.875)^2 = 0.015625 + 11.390625 + 0.765625 + 17.015625 = 29.1875Step 3: Calculate R²
R² = 1 - (1.5 / 29.1875) ≈ 1 - 0.0514 = 0.9486Final Answer:
0.948 -> Option DQuick Check:
R² ≈ 0.95 means good fit [OK]
- Using sum of residuals instead of squared residuals
- Forgetting to subtract mean in total sum squares
- Mixing up numerator and denominator
def mse(y_true, y_pred):
return sum(y_true - y_pred)**2 / len(y_true)What is the error?
Solution
Step 1: Analyze the code operation order
The code does sum(y_true - y_pred) first, then squares the total sum, which is incorrect for MSE.Step 2: Correct MSE calculation
MSE requires squaring each difference first, then averaging. The code should square element-wise before summing.Final Answer:
The subtraction is done element-wise but sum is outside, causing wrong squaring -> Option AQuick Check:
Square differences before sum for MSE [OK]
- Squaring sum instead of sum of squares
- Using absolute difference instead of squared
- Ignoring element-wise operations
Solution
Step 1: Understand MSE and R² meanings
MSE measures average squared error (lower is better). R² measures proportion of variance explained (higher is better).Step 2: Compare models on error and fit
Model B has lower MSE (2 < 4), so predictions are closer on average. Model A has higher R² but larger error, meaning it fits variance better but with bigger errors.Step 3: Prioritize error for prediction quality
Lower error (MSE) usually means better prediction accuracy, so Model B is better despite lower R².Final Answer:
Model B is better because it has lower MSE, indicating smaller average error -> Option AQuick Check:
Lower MSE means better prediction accuracy [OK]
- Choosing model with higher R² ignoring error size
- Thinking MSE and R² always agree
- Ignoring what metric matters for task
Ready to prove it?
Pass the test and this pattern moves unknown
