Lab 4 of 8about 40 minutes
Neighbors, a tree and a forest
It uses what you learned in k-nearest neighbors, Decision trees and Random forests.
Start here
Run itThe penguins of ml-knn, by bill length and weight, dealt as in the videos: 256 to learn from, and 86 kept aside as the test set. Every model below is scored on the same five folds of the 256, and the test set is opened once, at the end. The tree and the forest videos used the flipper in place of the weight, so their numbers here are not the videos'.
1The new penguin, as measured
Run itFrom k-nearest neighbors
Run the cell. It asks the video's new penguin, a bill of 50.3 mm and 3,300 g, for its five nearest neighbors as measured, and prints them.
All five weigh within 25 g of it, and four have bills over 10 mm shorter. As measured, a gram counts as much as a millimetre, so the weight in grams decides every vote: Adelie.
2One ruler, and k
Your turnFrom k-nearest neighbors
Put a standard scaler in front of the neighbors, in a pipeline, as ml-knn did. The loop tries k, the number of neighbors who vote, on five folds, and keeps each k's average score in knn_scores.
Hint
The scaler goes first in the pipeline, then the neighbors. n_neighbors=k sets how many vote.
One way to do it
knn_scores = {}
for k in [1, 3, 5, 9, 15, 25]:
one_ruler = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))
knn_scores[k] = cross_val_score(one_ruler, X_train, y_train).mean()
print({k: round(score, 3) for k, score in knn_scores.items()})
print("as measured:", round(cross_val_score(as_measured, X_train, y_train).mean(), 3))3A tree, and its depth
Your turnFrom Decision trees
cross_validate(..., return_train_score=True) scores a tree with no limit twice: on the penguins each fold learned from, and on the fold kept out. Then try each depth on the folds yourself, and keep each one's average score in tree_scores.
Two questions, four, or no limit: all 0.910 on the folds. So keep two, the tree you can read.
Hint
Inside the loop, make a tree with max_depth=depth, and store its five folds' average under tree_scores[depth].
One way to do it
no_limit = DecisionTreeClassifier(random_state=0)
result = cross_validate(no_limit, X_train, y_train, return_train_score=True)
print("its own penguins:", result["train_score"].mean(), "the folds:", round(result["test_score"].mean(), 3))
tree_scores = {}
for depth in [1, 2, 3, 4, None]:
tree_scores[depth] = cross_val_score(DecisionTreeClassifier(max_depth=depth, random_state=0), X_train, y_train).mean()
print({depth: round(score, 3) for depth, score in tree_scores.items()})4A forest beside one tree
Your turnFrom Random forests and Decision trees
The cell prints the tree of two questions as a rule. Then score a random forest on the same five folds, and keep its average in forest_score. The last line sets it beside one tree and the neighbors.
On two columns, though, the neighbors on one ruler still score best.
Hint
The same call as for the tree and the neighbors: cross_val_score, then its average.
One way to do it
two = DecisionTreeClassifier(max_depth=2, random_state=0).fit(X_train, y_train)
print(export_text(two, feature_names=list(X.columns)))
forest = RandomForestClassifier(random_state=0)
forest_score = cross_val_score(forest, X_train, y_train).mean()
print("forest", round(forest_score, 3), "one tree", round(tree_scores[2], 3), "neighbors", round(knn_scores[9], 3))5The test set, once
On your ownFrom k-nearest neighbors and Random forests
On your own now. Make the model that scored best on the folds, fit it on all 256 training penguins, and open the test set once: keep its score in test_score.
Hint
Look back at the best of knn_scores, tree_scores and forest_score. Fit it on X_train, then score it on X_test.
One way to do it
winner = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=9))
winner.fit(X_train, y_train)
test_score = winner.score(X_test, y_test)
print(test_score)6The bank's calls
On your ownFrom Random forests and Decision trees
On your own now: lab 3's calls, in bank-calls.csv, its twelve columns and 500 kept aside as there. One-hot the words and pass the numbers through, as ml-decision-trees did. Score one tree of ten questions and a forest of 100 such trees on five folds, by the area under the ROC curve, in tree_auc and forest_auc.
On 40,000 calls the video's tree scored 0.699, its forest 0.738. On 1,500, one tree overfits more.
Hint
Lab 3's step 1 reads and deals the calls. make_column_transformer takes the one-hot encoder for words and remainder="passthrough" for the rest. max_depth=10 goes in both models.
One way to do it
calls = pd.read_csv("bank-calls.csv")
words = ["job", "marital", "education", "default", "housing", "loan", "contact", "poutcome"]
cols = ["age", "campaign", "pdays", "previous"] + words
bank_y = calls["y"] == "yes"
bank_train, bank_test, bank_y_train, bank_y_test = train_test_split(
calls[cols], bank_y, test_size=500, stratify=bank_y, random_state=0)
onehot = make_column_transformer(
(OneHotEncoder(handle_unknown="ignore"), words), remainder="passthrough")
one = make_pipeline(onehot, DecisionTreeClassifier(max_depth=10, random_state=0))
bank_forest = make_pipeline(onehot, RandomForestClassifier(max_depth=10, random_state=0))
tree_auc = cross_val_score(one, bank_train, bank_y_train, scoring="roc_auc").mean()
forest_auc = cross_val_score(bank_forest, bank_train, bank_y_train, scoring="roc_auc").mean()
print(round(tree_auc, 3), round(forest_auc, 3))Run on Pyodide 314, Python 3.14, pandas 3.0 and scikit-learn 1.8. Checked on .
