Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← All challenges
ML-X03 · Regression · 40–50 minutes

Mixed predictors, two regression families

multiple_linear · regression_tree · validation · reference · final-test discipline

Complete workflow and evidence

The question

Compare multiple linear regression and a regression tree for Candy popularity using numeric and binary characteristics.

data/ml-learning/ML-X03.csv Complete workflow and evidence

Your inputs

Challenge input · ML-X03

85 observations. One candy product in the survey. Load the CSV file yourself.

Download challenge input CSV · Original source dataset · Source and original dictionary

Ready to load: comma-delimited UTF-8, header row, no saved index. No filtering or target construction is required.

ML-X03 · first 8 prepared rows
sugarpercentpricepercentchocolatefruitycaramelpeanutyalmondynougatcrispedricewaferhardbarpluribuswinpercent
0.7320.8610100101066.9717
0.6040.51110001001067.6029
0.0110.11600000000032.2611
0.0110.51100000000046.1165
0.9060.51101000000052.3415
0.4650.76710010001050.3475
0.6040.76710111001056.9145
0.3130.51100010000123.4178

Column meanings and units

sugarpercent: sugar percentile. pricepercent: price percentile. winpercent: percentage of survey matchups won. Ingredient, bar and multipack fields are 0/1 flags.

Percentile ranks are neither physical sugar percentages nor currency prices. Ratios of percentiles do not measure economic value. Chocolate and fruit flags can overlap; non-chocolate is not synonymous with fruit. The ML class target is defined by winpercent ≥ 50.

Ready to load: comma-delimited UTF-8, header row, no saved index. No filtering or target construction is required.

Input schema
ColumnStored type
sugarpercentfloat64
pricepercentfloat64
chocolateint64
fruityint64
caramelint64
peanutyalmondyint64
nougatint64
crispedricewaferint64
hardint64
barint64
pluribusint64
winpercentfloat64

How we validate this model

Reserve 20% of the declared population for the final test using split seed 42. Use a random split.

Use the same five training folds, shuffled with seed 42, for reference comparison, candidates and selection. Use out-of-fold training predictions for diagnosis. Select with negative RMSE (larger is better) and compare with a training-mean reference. Report final RMSE in original target units. Open final-test evidence after selection and diagnosis.

The file is available in the Python working folder. Load it yourself.

Your task
  1. Compare multiple linear regression and a regression tree for Candy popularity using numeric and binary characteristics.
cv_resultsreference_resultschosen_nameresidualsfinal_rmse

Outputs you create

cv_results
  1. Dataframe indexed by the requested model IDs, with initial_score, selected_score and settings columns.
  2. Scores are observed mean training-fold scores; settings describes the chosen recipe.
reference_results
  1. cross_validate result for the dummy reference; test_score contains five scores.
chosen_name
  1. Model ID nominated from training evidence.
residuals
  1. Training-only actual, predicted and actual-minus-predicted residual evidence.
final_rmse
  1. Root mean squared error in original target units.

Deliverables

These conditions describe a complete workflow. Use the declared Python variables beside the editor; Check inspects evidence from your Run.

Python name key

Teal outlines name table columns. Violet left rules name Python objects. Dotted rules mark syntax, functions and parameters. Use each name exactly as shown.

Words in this task
DataFrame
a table with rows and columns
numeric
a number, rather than text
dummy
a simple reference model used for comparison
folds
training-data groups used to compare models on the same held-out rows
out-of-fold
predictions made for training rows by models that did not fit those rows
aligned
matched by row or category identity, rather than guessed position
residuals
observed values minus predicted values
RMSE
root mean squared error: an error measure that gives larger errors more weight
  1. Data boundary

    1. Load the supplied challenge CSV, define the declared X/y and keep aligned row identities through the split.
    2. Keep learned preparation inside each training fit.
  2. Validation & selection

    1. Compare the requested initial model families with a dummy reference on matching training folds.
    2. Evaluate the declared settings where applicable and choose from training evidence.
  3. Diagnosis

    1. Use out-of-fold training predictions to inspect residuals or class errors before opening the final test.
  4. Final evidence

    1. Fit the nominated model on training rows and evaluate the reserved rows once.
    2. Report saved predictions, the requested metrics and labelled evidence
    3. Explain limitations without using the final test for further selection.

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. Choose what to predictEstimate candy win rate from 11 selected inputs; each row is one candy.
  2. Split data and save the test setWhich rows are available for learning, and which are being saved for the final check?
  3. Explore training dataDoes sugarpercent show a training pattern related to candy win rate?
  4. Define the preparation recipeWhat preparation does this particular model need?
  5. Build the model pipelineWhich if/then splits form useful numeric prediction groups?
  6. Validate the initial modelDo validation results stay reasonably similar across folds?
  7. Compare with a simple referenceDo the selected features beat a simple guess on the same training folds?
  8. Tune the modelHow deep should the tree grow?
  9. Inspect validation errorsDo training-only residuals form a roughly random cloud around zero?
  10. Final testHow does the saved final candy win rate error compare with the initial-model CV and any selected-setting CV for Candy Power Ranking · Continuous + binary, and what pattern did the model miss?

Data policy Keep target-derived inputs out of X. Use training-only selection for prediction.

Help Hints & explained solution

Choose the amount of help you need. Opening one hint does not reveal the others.

Hint 1 — Think

Flexibility and explanation have different costs.

Hint 2 — Tools

ColumnTransformer, LinearRegression, DecisionTreeRegressor and common-fold CV.

Revisit: Regression checkpoint

Hint 3 — Approach

Compare both prepared candidates, tune tree depth, diagnose and nominate before final evaluation.

Explained solution

This complete script replaces the editor contents. It includes the input setup and the workflow.

import numpy as np
import pandas as pd
df=pd.read_csv('data/ml-learning/ML-X03.csv')
from sklearn.base import clone
from sklearn.model_selection import train_test_split, KFold, cross_validate, cross_val_predict, GridSearchCV
from sklearn.dummy import DummyRegressor
from sklearn.metrics import root_mean_squared_error

import matplotlib.pyplot as plt
import seaborn as sns
X=df[['sugarpercent', 'pricepercent', 'chocolate', 'fruity', 'caramel', 'peanutyalmondy', 'nougat', 'crispedricewafer', 'hard', 'bar', 'pluribus']]
y=df['winpercent']
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=.2,random_state=42)
folds=KFold(n_splits=5,shuffle=True,random_state=42)
candidates={}
grids={}
# Prepare inputs and construct the candidate pipeline.
preprocessor = 'passthrough'
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
model = LinearRegression()
pipeline = Pipeline([('prepare', preprocessor), ('model', model)])
model = pipeline
candidates['multiple_linear']=model
grids['multiple_linear']=None
# Prepare inputs and construct the candidate pipeline.
preprocessor = 'passthrough'
from sklearn.pipeline import Pipeline
from sklearn.tree import DecisionTreeRegressor
model = DecisionTreeRegressor(random_state=42)
pipeline = Pipeline([('prepare', preprocessor), ('model', model)])
model = pipeline
candidates['regression_tree']=model
grids['regression_tree']={'model__max_depth': [3, 5, None]}
# Validate initial candidates on matching training folds.
initial_results={name:cross_validate(candidate,X_train,y_train,cv=folds,scoring='neg_root_mean_squared_error') for name,candidate in candidates.items()}
# Compare with a simple reference before tuning.
reference_results=cross_validate(DummyRegressor(strategy='mean'),X_train,y_train,cv=folds,scoring='neg_root_mean_squared_error')
rows=[]
selected={}
for name,candidate in candidates.items():
    initial=initial_results[name]
    grid=grids[name]
    if grid:
        search=GridSearchCV(candidate,grid,cv=folds,scoring='neg_root_mean_squared_error',n_jobs=1)
        search.fit(X_train,y_train)
        selected[name]=search.best_estimator_
        validation_score=float(search.best_score_)
        settings=search.best_params_
    else:
        selected[name]=candidate
        validation_score=float(np.mean(initial['test_score']))
        settings='Keep defaults: no production search'
    rows.append({'model':name,'initial_score':float(np.mean(initial['test_score'])),'selected_score':validation_score,'settings':str(settings)})
cv_results=pd.DataFrame(rows).set_index('model')
# This solution nominates by mean training-fold score. Other evidence-based choices can be defensible.
chosen_name=cv_results.selected_score.idxmax()
chosen=selected[chosen_name]
oof_predictions=cross_val_predict(chosen,X_train,y_train,cv=folds)
diagnostic_y=y_train
residuals=pd.DataFrame({'actual':diagnostic_y,'predicted':oof_predictions,'residual':diagnostic_y-oof_predictions})
fig,ax=plt.subplots(figsize=(6,4))
sns.scatterplot(x=residuals.predicted,y=residuals.residual,s=12,ax=ax)
ax.axhline(0,color='black')
ax.set(xlabel='Training-validation prediction',ylabel='Residual',title='Training-only residuals')
fig.tight_layout()
fig.savefig('diagnostic.png',dpi=150,bbox_inches='tight')
final_model=clone(chosen).fit(X_train,y_train)
final_predictions=final_model.predict(X_test)
final_rmse=root_mean_squared_error(y_test,final_predictions)
print('Final RMSE:',final_rmse)
View input setup in this script

These opening lines are included in the complete script above. They load the challenge input.

import numpy as np
import pandas as pd
df=pd.read_csv('data/ml-learning/ML-X03.csv')

Why these steps exist

  • Numeric measurements and binary flags retain their declared meanings in both pipelines. Only the tree has a depth search here; common-fold evidence and OOF residuals support nomination before final RMSE. Coefficients and tree importance have different interpretations and neither establishes causality.

Another valid approach

Equivalent ordinary Python is welcome. A defensible candidate or grouping need not match the solution’s choice; objective evidence must remain consistent.

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.