Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Open In Colab Open In Kaggle

Now we move to creating and training decision trees. Here we will learn how to train and fine-tune a decision tree on a synthetic dataset.

Since decision trees contain multiple trainable hyperparameters, parts of this notebook focus on adjusting and optimizing multiple hyperparameters in the decision tree algorithm.

Goal:

  1. Know how to train a decision tree.

  2. To be proficient in tuning ML model hyperparameters with cross-validation.

Moon.jpg

Can we grow a tree to predict the moon? 🌳 πŸŒ›

The goal of this exercise is to train and adjust the hyperparameters of a decision tree on a synthetic β€œmoons” dataset. The dataset contains two interleaving half circles that we seek to separate via classification.

First, let’s generate a moons dataset using make_moons.

Q1) Split the moons dataset into a training and a test set

Hint 1: You may use the train_test_split function of scikit-learn.

Hint 2: Here we will keep 20% of the dataset for testing.

Hint 3: To ensure you get the same result every time you run the code, we will specify the random_state option in train_test_split function to be 42.

Q2) Visualize the data, indicating which points belong to each half circle of the moon, and which points belong to the training and test sets

Hint 1: In the moons dataset, X contains the 2D spatial coordinates of each sample, while y indicates which half circle of the moon the sample belongs to.

Hint 2: You may randomly subsample your data for visualization purposes. Alternatively, you can adjust the size and transparency of a Matplotlib scatter plot by varying the parameters s and alpha. We adopt the latter visualization method in the code snippet. Do not hesitate to experiment with the first visualization method as long as the figure looks good.

Do your data & training/test splits look reasonable?

Q3) Conduct a hyperparameter search to find the two hyperparameters that lead to the best-performing decision tree

Hint 1: You can conduct an exhaustive hyperparameter search over specified parameter values using the GridSearchCV class documented at this link. We recommend using cross-validation by setting the parameter cv.

Hint 2: If you choose to train a DecisionTreeClassifier object, we recommmend conducting the search over the max_leaf_nodes and min_samples_split hyperparameters. Consult the DecisionTreeClassifier documentation to decide which range to search over.

Q4) Using the best hyperparameter values you found, train a decision tree over the entire training set and calculate its accuracy over both the training and test sets

Hint 1: GridSearchCV has a method predict that automatically selects the best model found during the search.

Hint 2: Using the accuracy classification score, you should find an accuracy of β‰ˆ\approx85% on the test set.

Q5) Visualize the errors made by your best model

Hint: You may recycle the visualization scripts you developed in Question 2

Can you think of ways to improve your best model?

Bonus Exercise 2: Upgrading the Decision Tree to a Random ForestΒΆ

Moon_Forest.jpg

Is a full forest enough to predict the moon? 🌲

Building on the previous exercise, we would like to upgrade the decision tree to a random forest to make more accurate predictions on the moons dataset.

Q1) Generate 1,000 subsets of the training set, each containing 100 instances selected randomly

Hint: You may use scikit-learn’s random permutation cross-validator ShuffleSplit with the appropriate value of the n_splits parameter.

Q2) Train one DecisionTreeClassifier on each subset, using the best hyperparameter values found above

Q3) Evaluate each decision tree on the test set and visualize their accuracy

Hint 1: You can quickly make histograms by using Matplotlib.pyplot’s hist function

Hint 2: The mean accuracy of your decision trees should be approximately 80% because the decision trees are fitted on smaller sets.

Now comes the magic ❇ 🌲 ❇

Q4) Generate the predictions of the 1,000 decision trees over the test set, and only keep the most frequent prediction. This gives you majority-vote predictions over the test set

Hint: You may use Scipy’s mode function to calculate the most frequent prediction.

Congratulations!! πŸ˜ƒ You have created a random forest classifier 🌲 🌳 🌲

Q5) Calculate the accuracy of your random forest classifier and visualize its performance

Hint: Your accuracy should be approximately 1% higher than your best decision tree.