1.Forest versus single tree
IntermediateCompare a DecisionTreeClassifier(random_state=0) with a RandomForestClassifier(n_estimators=200, random_state=0) on the breast cancer data using 5-fold cross-validation. Print each model's mean accuracy (3 decimals).
Show hint
cross_val_score(model, X, y, cv=5).mean() for each model.
Show solution
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
for model in [DecisionTreeClassifier(random_state=0), RandomForestClassifier(n_estimators=200, random_state=0)]:
print(type(model).__name__, round(cross_val_score(model, X, y, cv=5).mean(), 3))DecisionTreeClassifier 0.917
RandomForestClassifier 0.96Averaging 200 trees, each trained on different samples and features, reduces variance, so the forest beats the single tree.