Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← ML Foundations lessonsQUESTIONS · MODELS · EVIDENCE
First complete workflows · ML-F11 · 25–40 MIN

Your first complete regression workflow

Connect the steps from a delivery question to an honest error estimate.

Exercises within this concept

  1. FollowRun, predict and explainCurrent exercise
  2. ChangeRebuild key steps and justify
  3. TransferBuild from the eight-step outline

Understand the idea

Use the numbered comments as an eight-step route through one worked Python script. A dummy is a reference that ignores the features. A fold holds out part of the training rows while a fresh copy fits the rest. Compare the sole candidate with the dummy and say if it has not earned an improvement claim. The final test remains untouched until the recipe is fixed.

At dispatch, estimate a new delivery duration in minutes.Question / X, ySplit: reserve testTraining-only foldsDummy + candidateChoose + diagnoseFinal predict / explainFit preparation inside folds. Open final evidence once.
Schematic · At dispatch, estimate a new delivery duration in minutes.Scroll the diagram horizontally if needed.

Python skill: Read a Pipeline, compare matching training folds and report final error in minutes.

Meet the syntax

Pipeline([('prepare', preparation), ('model', estimator)])
cross_validate(candidate, X_train, y_train, cv=folds, scoring=metric)
cross_val_predict(candidate, X_train, y_train, cv=folds)
clone(candidate).fit(X_train, y_train)
validation['test_score']
neg_root_mean_squared_error
neg_mean_absolute_error
Pipeline
Keeps preparation with the model, so each fold learns fitted settings only from its training rows.
cross_validate
Fits fresh copies on training folds and returns their validation scores.
cross_val_predict
Makes one held-out training prediction per row for diagnosis; use cross_validate for the validation score.
clone(candidate).fit(X_train, y_train)
Starts an unfitted copy of the selected recipe and fits all development rows after selection.
test_score
Validation-fold scores inside cross_validate, despite the word test; the reserved final test is separate.
neg_root_mean_squared_error
scikit-learn makes larger scores better: a value nearer zero means a smaller RMSE. Report final error as a positive number of minutes.
neg_mean_absolute_error
A value nearer zero means fewer minutes of absolute error on average. Report final MAE as a positive number of minutes.

Follow the code

Use the numbered comments to connect each Python block to the workflow above.

from sklearn.model_selection import train_test_split, KFold, cross_validate, cross_val_predict
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
from sklearn.dummy import DummyRegressor
from sklearn.base import clone
from sklearn.metrics import mean_squared_error
# 1. Question, features available now, and later outcome
feature_names = ['distance']
target = 'duration'
X, y = df[feature_names], df[target]
# 2. Protect the final test; split X and y together
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=42)
# 3. Inspect training rows only
print(X_train.describe())
# 4. Define preparation and the candidate; no fitting yet
candidates = {'simple': Pipeline([('prepare', 'passthrough'), ('model', LinearRegression())])}
folds = KFold(n_splits=3, shuffle=True, random_state=42)
metric = 'neg_root_mean_squared_error'
# 5. Compare a reference and candidates on matching training folds
reference = DummyRegressor(strategy="mean")
reference_results = cross_validate(reference, X_train, y_train, cv=folds, scoring=metric)
cv_results = {'simple': cross_validate(candidates['simple'], X_train, y_train, cv=folds, scoring=metric, return_train_score=True)}
print('Reference validation:', reference_results['test_score'])
print('Candidate validation:', cv_results['simple']['test_score'])
print('Candidate minus dummy mean:', cv_results['simple']['test_score'].mean() - reference_results['test_score'].mean())
# 6. Assess the candidate with training evidence; inspect training-only errors
chosen_name = 'simple'  # Sole candidate; report if it does not beat the dummy
diagnostic_predictions = cross_val_predict(candidates[chosen_name], X_train, y_train, cv=folds)
print(pd.DataFrame({'actual': y_train, 'predicted': diagnostic_predictions, 'residual': y_train-diagnostic_predictions}))
# 7. Fit the fixed recipe; predict the final rows once
final_model = clone(candidates[chosen_name]).fit(X_train, y_train)
final_predictions = final_model.predict(X_test)
final_score = np.sqrt(mean_squared_error(y_test, final_predictions))
print('Final metric:', final_score)
# 8. Explain the evidence and its limits in the self-review field

This practice: Run, predict and explain. Next: Change · Your first complete regression workflow.

The question and data dictionary

At dispatch, estimate a new delivery duration in minutes.

Independent deliveries from one stable service; no repeated driver or route identifiers are supplied.

Decide what can be known at prediction time
ColumnMeaning and availability
distanceRoute length in km, known at dispatch.
durationCompleted journey duration in minutes. This is the outcome.

The playground workflow

Use the same data boundary as ML → Workflow: frame, split, explore, prepare, validate against a reference, diagnose, then make the final evaluation. Each step answers one question.

  1. Question → X / yName the outcome and the inputs available when the prediction is needed. Later outcomes, identifiers and outcome-derived fields are not predictors.
  2. Split and protectReserve final rows before inspecting distributions or fitting. Independent rows permit a shuffled holdout; repeated entities or future forecasting need different designs.
  3. Explore training rowsInspect only development rows to identify types, missingness and class balance.
  4. Prepare → modelPut learned preparation inside a Pipeline so each fold learns it afresh. A numeric linear model can pass the original units through.
  5. Baseline → validateA dummy establishes what ignoring X achieves. Fit the candidate on matching training folds; these validation rows are not the final test.
  6. Choose → diagnoseChoose using training evidence, then inspect held-out training predictions. Simplify a model that fails to generalise; do not open the final test to choose.
  7. Final fit → predict → metricFix the recipe, fit all training rows, predict reserved rows once and calculate the declared metric from those saved predictions.
  8. Interpret and limitCompare validation with the baseline and final evidence. State units or class error costs, uncertainty from the small sample, and the population to which the claim applies.

Explain your decisions · self-review

Before Run, write your prediction. After Run, explain what the evidence supports and what it cannot establish. Code checks cannot award these reasoning scores.

  1. Frame and boundaryName prediction time, observation, target and unavailable inputs. Choose a split that matches intended use.
  2. Preparation and baselineFit learned preparation inside each training fold. Compare the dummy on those same folds.
  3. Validation and selectionChoose from training-fold scores and error patterns. Explain any gap between training and validation.
  4. Metric and final testJustify the metric and interpret the reserved-test result. Do not revise the recipe using that result.
  5. Interpretation and limitsQuote baseline, validation and final results. Explain error units or costs, one failure case and one limit; avoid causal claims.

Use the interpretation field beside your output. After an attempt, Check identifies code evidence and shows reasoning guidance. The optional explained solution is one defensible approach, not the only acceptable answer.

Simple linear regression · from idea to workflow

Question: How does one available measurement help predict a quantity?

Mechanism: A slope and intercept minimise squared training residuals.

Watch for: Curvature, unusual points and extrapolation can make a straight line misleading.

Interpret or debug · self-review: Read the residuals: does a curve remain? Explain why a small training error does not establish performance beyond the observed input range.

Independent full workflow: ML-X01 · ML-X02. First practise complete regression and classification in F11–F12; check readiness in W-K2–W-K3.

Your inputs · LINE24

24 synthetic independent observations. The dataframe df is supplied afresh on each Run. Column availability is described in the question’s dictionary above.

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 · Follow

Before Run, predict whether a line should beat a constant duration. Run and inspect every step. Locate the training-only scores and final error. Explain the difference in minutes and why distance is available at dispatch.

Required Python variables and evidence

Use these names so Check can inspect your workflow. Each meaning is shown beside its name.

Workflow evidence contract
VariableMeaning
target / feature_namesYour outcome column name and list of legitimate inputs. Choose from the data dictionary.
X / y / X_train / X_test / y_train / y_testOriginal indexed feature/target data and aligned partitions. A 15–30% holdout is supported; choose and justify its seed/design.
folds / metricA 3–5-fold shuffled KFold or StratifiedKFold object; metric is an sklearn scoring name. Regression: neg_root_mean_squared_error or neg_mean_absolute_error. Classification: f1_macro or balanced_accuracy.
reference / reference_resultsDummy estimator and its actual cross_validate result.
candidates / cv_resultsNamed Pipelines and matching cross_validate result dictionaries. Regression supports LinearRegression, Ridge and DecisionTreeRegressor; classification supports LogisticRegression, DecisionTreeClassifier, KNeighborsClassifier, GaussianNB, LinearDiscriminantAnalysis, SVC and MLPClassifier.
diagnostic_predictionsActual cross_val_predict outputs for the chosen candidate on training folds; inspect residuals or a confusion table.
chosen_name / final_modelName of your chosen validated candidate and a clone fitted on all training rows. Defend the choice, including any simplicity trade-off.
final_predictions / final_scoreOne saved final prediction array and its final metric. Positive error units for regression. No further selection after this call.
Hint 1 — Think

Before Run, predict whether a line should beat a constant duration. Run and inspect every step. Locate the training-only scores and final error. Explain the difference in minutes and why distance is available at dispatch. At dispatch, estimate a new delivery duration in minutes. Which fields exist at that moment?

Hint 2 — Tools

Use a dataframe/series pair, train_test_split, Pipeline, cross_validate and a dummy suited to a numeric outcome.

Hint 3 — Approach

Keep final rows outside every fit. Compare matching training-fold evidence before predicting reserved rows in LINE24.

Explained solution
from sklearn.model_selection import train_test_split, KFold, cross_validate, cross_val_predict
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
from sklearn.dummy import DummyRegressor
from sklearn.base import clone
from sklearn.metrics import mean_squared_error
# 1. Question, features available now, and later outcome
feature_names = ['distance']
target = 'duration'
X, y = df[feature_names], df[target]
# 2. Protect the final test; split X and y together
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=42)
# 3. Inspect training rows only
print(X_train.describe())
# 4. Define preparation and the candidate; no fitting yet
candidates = {'simple': Pipeline([('prepare', 'passthrough'), ('model', LinearRegression())])}
folds = KFold(n_splits=3, shuffle=True, random_state=42)
metric = 'neg_root_mean_squared_error'
# 5. Compare a reference and candidates on matching training folds
reference = DummyRegressor(strategy="mean")
reference_results = cross_validate(reference, X_train, y_train, cv=folds, scoring=metric)
cv_results = {'simple': cross_validate(candidates['simple'], X_train, y_train, cv=folds, scoring=metric, return_train_score=True)}
print('Reference validation:', reference_results['test_score'])
print('Candidate validation:', cv_results['simple']['test_score'])
print('Candidate minus dummy mean:', cv_results['simple']['test_score'].mean() - reference_results['test_score'].mean())
# 6. Assess the candidate with training evidence; inspect training-only errors
chosen_name = 'simple'  # Sole candidate; report if it does not beat the dummy
diagnostic_predictions = cross_val_predict(candidates[chosen_name], X_train, y_train, cv=folds)
print(pd.DataFrame({'actual': y_train, 'predicted': diagnostic_predictions, 'residual': y_train-diagnostic_predictions}))
# 7. Fit the fixed recipe; predict the final rows once
final_model = clone(candidates[chosen_name]).fit(X_train, y_train)
final_predictions = final_model.predict(X_test)
final_score = np.sqrt(mean_squared_error(y_test, final_predictions))
print('Final metric:', final_score)
# 8. Explain the evidence and its limits in the self-review field

At dispatch, estimate a new delivery duration in minutes. The reference ignores features. Training-fold evidence informs the choice, and the final metric describes only the reserved sample. Excluding later outcomes prevents answering the question with information unavailable at prediction time. The reasoning rubric needs human review.

Helpful prior knowledge: Could we know this at prediction time? These links are guidance, not locks.

Sources and API context

Examples run with this Playground’s scikit-learn 1.4.2 / Pyodide 0.26.4 runtime.

Your task · Follow

Before Run, predict whether a line should beat a constant duration. Run and inspect every step. Locate the training-only scores and final error. Explain the difference in minutes and why distance is available at dispatch.

reference_resultscv_resultschosen_namefinal_score
Keep beside your code

At dispatch, estimate a new delivery duration in minutes.

distanceRoute length in km, known at dispatch.
durationCompleted journey duration in minutes. This is the outcome.

Pipeline Keeps preparation with the model, so each fold learns fitted settings only from its training rows.cross_validate Fits fresh copies on training folds and returns their validation scores.cross_val_predict Makes one held-out training prediction per row for diagnosis; use cross_validate for the validation score.

Frame → reserve final rows → compare dummy and candidate on training folds → diagnose → fit the fixed recipe → evaluate once.

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.

Does the line earn an improvement claim over the dummy on matching delivery folds?

Use your Run output as evidence. This response is optional, not machine-graded or saved.