Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

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

Read residual patterns and limits

Use residual structure to question a fitted relationship.

  1. FollowRead and try the PythonCurrent exercise
  2. ChangeCompute and inspect the evidence
  3. TransferCompute and inspect the evidence

Understand the idea

A pattern in residuals suggests the model has left systematic structure unexplained. Association, prediction, extrapolation and causation are different claims. Use held-out training predictions for candidate diagnosis; keep the final test for the fixed recipe’s final report.

Use residual structure to question a fitted relationship.Residual = actual − held-away predictionUse training-only predictions; keep the final test closed.
Use residual structure to question a fitted relationship.Scroll the diagram horizontally if needed.

What the syntax does

residual
  • Keeps row-level errors so a plot can reveal patterns hidden by a single summary.

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[['x']]
y
Target series, aligned with X.
y = df['y']
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)
folds
Supplied folds; its definition below specifies the values and role.
folds = KFold(5, shuffle=True, random_state=42)

Outputs you create

answer
  1. The requested result, with the values, labels and row order described by this task.
CURVE48 · first 8 rows
xy
-315.9571
-2.8723413.0709
-2.7446814.9362
-2.6170214.45
-2.489369.39011
-2.36179.68978
-2.2340411.2101
-2.106389.96814
Your task
  1. Use five shuffled seed-42 training folds to obtain held-out training predictions from a line on CURVE48.
  2. Store actual-minus-predicted residuals in answer, keeping training indices
  3. Plot them against training x.
  4. Keep X_test/y_test outside diagnosis.
answer
Hints

Think: The residual pattern can guide another candidate, so these must be held-out development errors.

Tools: cross_val_predict on the supplied training folds, aligned subtraction and a zero-reference scatterplot.

Approach: Plot each training observation’s out-of-fold error against its original x; leave final-test outcomes unopened.

Explained solution
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_predict
import matplotlib.pyplot as plt
import seaborn as sns
predicted = cross_val_predict(LinearRegression(),X_train,y_train,cv=folds)
answer = y_train-predicted
fig,ax = plt.subplots()
sns.scatterplot(x=X_train.x,y=answer,ax=ax)
ax.axhline(0,color='black')
ax.set(xlabel='x',ylabel='Residual',title='Training-only line residuals on curved observations')

Each plotted residual comes from a line fitted without that training observation. These development errors can motivate another recipe; final-test errors cannot be reused for a fresh selection claim.

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.