ML Exercises
Time to practise! Each exercise has a starter playground that runs as-is and prints placeholder values in the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the expected result. All randomness is seeded, so your numbers should match exactly. If you get stuck, open the solution — but give it a real try first.
| # | Exercise | Topics |
|---|---|---|
| 1 | Describe a data set | mean, median, standard deviation, percentiles |
| 2 | Fit a line | linear regression, predict |
| 3 | Train/test a decision tree | train_test_split, accuracy |
| 4 | Read a confusion matrix | precision, recall |
| 5 | Does scaling matter? | StandardScaler, KNN, pipelines, cross validation |
| 6 | One-hot encoding | categorical data, pandas |
| 7 | K-means clusters | clustering, inertia |
| 8 | Tune a random forest | grid search, ensembles |
1. Describe a data set
Seven days of step counts are stored in an array. Print the mean, median and population standard deviation with one decimal, then the interquartile range (Q3 − Q1).
Expected:
mean=9978.6 median=9800.0 std=2841.0
IQR=3375.0import numpy as np
steps = np.array([8200, 10450, 6300, 12100, 9800, 15400, 7600])
mean = median = std = 0.0 # TODO: compute with NumPy
print(f"mean={mean:.1f} median={median:.1f} std={std:.1f}")
iqr = 0.0 # TODO: use np.percentile
print(f"IQR={iqr:.1f}")mean=0.0 median=0.0 std=0.0
IQR=0.0
Show solution
import numpy as np
steps = np.array([8200, 10450, 6300, 12100, 9800, 15400, 7600])
print(f"mean={steps.mean():.1f} median={np.median(steps):.1f} std={steps.std():.1f}")
q1, q3 = np.percentile(steps, [25, 75])
print(f"IQR={q3 - q1:.1f}")2. Fit a line
A shop tracked how many ads it ran per week and its sales. Fit a LinearRegression, print the slope and intercept (2 decimals) and predict sales for 8 ads (1 decimal).
Expected:
slope=8.17 intercept=3.73
prediction for 8: 69.1import numpy as np
from sklearn.linear_model import LinearRegression
ads = np.array([1, 2, 3, 4, 5, 6]) # TODO: reshape into a 2-D column
sales = np.array([12, 19, 29, 37, 45, 52])
slope, intercept, prediction = 0.0, 0.0, 0.0 # TODO: fit the model and predict
print(f"slope={slope:.2f} intercept={intercept:.2f}")
print(f"prediction for 8: {prediction:.1f}")slope=0.00 intercept=0.00
prediction for 8: 0.0
Show solution
import numpy as np
from sklearn.linear_model import LinearRegression
ads = np.array([1, 2, 3, 4, 5, 6]).reshape(-1, 1)
sales = np.array([12, 19, 29, 37, 45, 52])
model = LinearRegression().fit(ads, sales)
print(f"slope={model.coef_[0]:.2f} intercept={model.intercept_:.2f}")
print(f"prediction for 8: {model.predict([[8]])[0]:.1f}")3. Train/test a decision tree
Split the iris data 70/30 with random_state=7 and stratify=y, train a DecisionTreeClassifier(max_depth=2, random_state=0) on the training part and print training and test accuracy.
Expected: train=0.971 test=0.889
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_iris(return_X_y=True)
# TODO: split, train, score
train_acc, test_acc = 0.0, 0.0
print(f"train={train_acc:.3f} test={test_acc:.3f}")train=0.000 test=0.000
Show solution
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_iris(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=7, stratify=y)
tree = DecisionTreeClassifier(max_depth=2, random_state=0).fit(X_tr, y_tr)
print(f"train={tree.score(X_tr, y_tr):.3f} test={tree.score(X_te, y_te):.3f}")4. Read a confusion matrix
Compute the confusion matrix for the predictions below, unpack it into TP/FP/FN/TN and compute precision and recall by hand from those counts.
Expected:
TP=4 FP=1 FN=2 TN=5
precision=0.800 recall=0.667from sklearn.metrics import confusion_matrix
actual = [1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0]
predicted = [1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0]
tn = fp = fn = tp = 0 # TODO: use confusion_matrix(...).ravel()
print(f"TP={tp} FP={fp} FN={fn} TN={tn}")
precision = recall = 0.0 # TODO: formulas from the lesson
print(f"precision={precision:.3f} recall={recall:.3f}")TP=0 FP=0 FN=0 TN=0
precision=0.000 recall=0.000
Show solution
from sklearn.metrics import confusion_matrix
actual = [1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0]
predicted = [1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0]
tn, fp, fn, tp = confusion_matrix(actual, predicted).ravel()
print(f"TP={tp} FP={fp} FN={fn} TN={tn}")
print(f"precision={tp / (tp + fp):.3f} recall={tp / (tp + fn):.3f}")5. Does scaling matter?
Compare 5-fold cross-validated accuracy of KNeighborsClassifier(n_neighbors=5) on the wine data without scaling and with a StandardScaler in a pipeline.
Expected: raw=0.691 scaled=0.949 — a huge difference for a distance-based model.
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
X, y = load_wine(return_X_y=True)
raw = scaled = 0.0 # TODO: two cross_val_score(...).mean() calls
print(f"raw={raw:.3f} scaled={scaled:.3f}")raw=0.000 scaled=0.000
Show solution
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
X, y = load_wine(return_X_y=True)
raw = cross_val_score(KNeighborsClassifier(n_neighbors=5), X, y, cv=5).mean()
scaled = cross_val_score(make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5)), X, y, cv=5).mean()
print(f"raw={raw:.3f} scaled={scaled:.3f}")6. One-hot encoding
One-hot encode the fuel column with pd.get_dummies(..., dtype=int). Print the new column names and the encoded row of the electric car (index 2) as a list.
Expected:
['km', 'fuel_diesel', 'fuel_electric', 'fuel_petrol']
[15000, 0, 1, 0]import pandas as pd
cars = pd.DataFrame({"fuel": ["petrol", "diesel", "electric", "petrol"], "km": [52000, 81000, 15000, 30000]})
encoded = cars # TODO: one-hot encode the fuel column
print(list(encoded.columns))
print(encoded.iloc[2].tolist())['fuel', 'km']
['electric', np.int64(15000)]
Show solution
import pandas as pd
cars = pd.DataFrame({"fuel": ["petrol", "diesel", "electric", "petrol"], "km": [52000, 81000, 15000, 30000]})
encoded = pd.get_dummies(cars, columns=["fuel"], dtype=int)
print(list(encoded.columns))
print(encoded.iloc[2].tolist())7. K-means clusters
Cluster the generated points into 3 groups with KMeans(n_clusters=3, n_init=10, random_state=0). Print the sorted cluster sizes and the inertia (1 decimal).
Expected:
sizes: [79, 80, 81]
inertia=656.3import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=240, centers=3, cluster_std=1.2, random_state=11)
sizes, inertia = [], 0.0 # TODO: fit KMeans; np.bincount(labels) counts cluster sizes
print("sizes:", sizes)
print(f"inertia={inertia:.1f}")sizes: []
inertia=0.0
Show solution
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=240, centers=3, cluster_std=1.2, random_state=11)
km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(X)
print("sizes:", sorted(np.bincount(km.labels_).tolist()))
print(f"inertia={km.inertia_:.1f}")8. Tune a random forest
Use GridSearchCV with cv=3 to tune max_depth in [2, 4, 8] and n_estimators in [25, 50] for RandomForestClassifier(random_state=0) on the breast-cancer data. Print the best parameters and the best CV accuracy.
Expected:
best: {'max_depth': 8, 'n_estimators': 25}
cv accuracy=0.960from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
X, y = load_breast_cancer(return_X_y=True)
grid = {} # TODO: the parameter grid
best_params, best_score = {}, 0.0 # TODO: run the search
print("best:", best_params)
print(f"cv accuracy={best_score:.3f}")best: {}
cv accuracy=0.000
Show solution
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
X, y = load_breast_cancer(return_X_y=True)
grid = {"max_depth": [2, 4, 8], "n_estimators": [25, 50]}
search = GridSearchCV(RandomForestClassifier(random_state=0), grid, cv=3).fit(X, y)
print("best:", search.best_params_)
print(f"cv accuracy={search.best_score_:.3f}")Test yourself
In exercise 5, why does scaling improve KNN so much on the wine data?
- Scaling adds more training data
- Unscaled, features with large ranges (like proline) dominate the distances
- KNN cannot read decimals
- Scaling changes the labels
Which call returns the four confusion-matrix counts of a binary problem in the order TN, FP, FN, TP?
confusion_matrix(a, p).ravel()confusion_matrix(a, p).sum()classification_report(a, p)accuracy_score(a, p)