Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← Regression lessons
Lines and evidence · ML-R02 · 12–18 MIN

RMSE and R² answer different questions

Distinguish target-unit errors from relative fit.

  1. FollowRead and run the PythonCurrent exercise
  2. ChangeCompute and inspect the evidence
  3. TransferAdapt the Python

Understand the idea

RMSE measures errors in target units. R² compares squared error with variation around the evaluation-set mean. It can be negative. A trained mean dummy uses the training mean, so it is a distinct reference.

Distinguish target-unit errors from relative fit.RMSE: error in target unitsR²: relative to a referenceEvaluation-mean prediction gives R² = 0.Negative R² performs worse than that evaluation reference.
Distinguish target-unit errors from relative fit.Scroll the diagram horizontally if needed.

What the syntax does

r2_score
  • Compares squared prediction error with variation around the evaluation-target mean; the result can be negative.

Supplied for this practice

These objects are prepared afresh before your editor runs.

X
Feature dataframe for the declared population, preserving row indices.
X = df[['distance']]
y
Target series, aligned with X.
y = df['duration']
X_train / X_test / y_train / y_test
Training feature rows from the declared split. Final-test feature rows from the declared split. Training targets, aligned with X_train. Final-test targets, aligned with X_test.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model
Already fitted on X_train, y_train. Fitted estimator or pipeline for the requested model family. Fitted on X_train, y_train; reuse without refitting.
predictions
Supplied predictions; its definition below specifies the values and role.
predictions = model.predict(X_test)

Outputs you create

rmse
  1. Requested result described in the task and deliverables.
r2
  1. Requested result described in the task and deliverables.
LINE24 · first 8 rows
distanceduration
15.30501
1.4782611.2361
1.9565211.8488
2.4347814.809
2.9130410.7589
3.391319.4972
3.8695717.89
4.3478315.531
Your task
  1. Compute RMSE and R² for the supplied predictions; store them in rmse and r2.
rmser2
Hints

Think: One measure reports error in outcome units; the other compares squared error with a reference.

Tools: root_mean_squared_error and r2_score.

Approach: Apply both metrics to the same aligned outcomes and predictions, then store each named result.

Explained solution
from sklearn.metrics import root_mean_squared_error,r2_score
rmse=root_mean_squared_error(y_test,predictions)
r2=r2_score(y_test,predictions)

Using identical rows makes the two summaries complementary descriptions of the same prediction evidence.

Ctrl/⌘+Enter: Run · Tab: indent · Esc then Tab: leave editor

Python loads when you run. Code and results stay in this activity only.

Run your code to inspect its output. Check uses that same run.