10. Twenty Questions About Pixels
Summary
How a tree picks its questions
A decision tree reduces the training images to a short series of yes-or-no questions about pixels, then discards the images. This is the opposite of k-nearest neighbors, which keeps every image and works when a new one arrives. The chapter asks how a tree chooses its first question and how it knows when to stop.
Gini impurity and entropy
Two numbers measure how mixed a group is. Gini impurity is one minus the sum of squared class shares. Entropy, in bits, is the negative sum of each share times the base-two log of that share. For six sevens and four ones, Gini is 0.48 and entropy is about 0.97 bits. A pure group scores zero on both. The two usually choose the same split.
Choosing a cut by hand
Candidate thresholds are midpoints between neighboring sorted values, and a hand calculation needs only those where the label changes. In the worked ten-image example, cut A lowers weighted impurity by about 0.31, cut B by about 0.16 and cut C by 0.32, so C wins. The tree then repeats the process on each side.
The limit of greedy splitting
Each split is chosen for its immediate gain. An XOR pattern across two pixels shows no gain from either pixel alone, so a greedy tree can miss it. Finding the truly best tree is NP-complete, so trees are built one step at a time.
Growing a tree on MNIST
The chapter uses DecisionTreeClassifier with criterion, max_depth, min_samples_leaf and random_state, fitting on the first fifty thousand training images and validating on the next ten thousand. Scaling changes nothing for a tree. An unlimited tree grows thousands of leaves and reaches about 100 percent training accuracy, while validation typically lands near 87 to 88 percent, below logistic regression's 92 and nearest neighbors' 97. A typical depth sweep runs from about 20 percent at depth 1 to the mid-80s at depth 10, then flattens. min_samples_leaf forbids tiny leaves and shrinks the tree, and ccp_alpha pruning is named as a third option.
Reading and trusting the tree
export_text and plot_tree print the top questions of a tree, and a pixel number divided by 28 gives its row and column. feature_importances_ reshaped to 28 by 28 shows bright pixels near the center and near zero at the border. predict_proba on a tree is just leaf class counts, so deep trees give mostly zero or one and are poorly calibrated. Trees are also unstable: refitting after dropping a random five percent of the data can change the top split and everything below it. That instability motivates random forests, which come next. The exercise is a twenty-fit sweep of max_depth against min_samples_leaf on validation only, with two built-in checks.
News
Google DeepMind announced Gemini 4 Carbon on October 28, 2026, aimed at cybersecurity and engineering.
A paper on fraud detection under operating limits, arXiv 2610.39556, uses chronological holdouts with XGBoost and LightGBM. On PaySim data, Platt calibration cut the Brier score from 0.1141 to 0.0245. Alerting on only the top one percent of scores cut false-positive investigations from 192 to 117, while recall fell from 0.4236 to 0.2122. These results hold for that dataset and setup only.
A model that keeps questions instead of examples
Last time, k-nearest neighbors kept every training image and did all its work when a new one arrived. A decision tree does the opposite. It studies the training images once, boils them down to a short list of yes-or-no questions, and then throws the images away. To classify a new digit, it asks the questions in order, like a game of twenty questions played about pixels. Is pixel 350 darker than 100? If yes, ask this next. If no, ask that. At the end of the path sits a label.
The question for this chapter is how a tree decides which question to ask first, and how it knows when to stop. The answer is a small piece of arithmetic you can do by hand, and then a lesson on MNIST about how far a tree should be allowed to grow.
Measuring how mixed a group is
Say you have ten images, six sevens and four ones, and you look at one pixel in each. Before any question, the group is mixed. We want a number for how mixed.
The first number is Gini impurity. For each class, take its share of the group, square it, add those squares up, and subtract the total from one. Here the shares are 0.6 and 0.4. The squares are 0.36 and 0.16, which add to 0.52. One minus 0.52 is 0.48. A group with only one class gives one minus one, which is zero. A fifty-fifty group of two classes gives one minus a half, which is 0.5. So zero means pure, and bigger means more mixed.
The second number is entropy, measured in bits. For each class, take its share, multiply by the base-two logarithm of that share, add those up, and flip the sign. For shares of 0.6 and 0.4, that comes to about 0.97 bits. A pure group gives zero, and a fifty-fifty split gives exactly one bit. It reads as the average number of yes-or-no questions you would need to name the class of a random image drawn from the group. The two measures differ in detail but usually pick the same split, so the choice rarely matters.
Choosing a cut by hand
Now sort the ten images by that one pixel's value. A cut is a threshold: images below it go left, images at or above go right. The candidate thresholds are the midpoints between neighboring values in the sorted list. If two neighbors have values 40 and 80, the midpoint is 60.
The method we are working through is the CART algorithm, short for classification and regression trees. You do not need to test every midpoint by hand. If two neighbors have the same label, cutting between them cannot beat cutting at a spot where the label changes, so you can test only the midpoints where the label switches.
Say the sorted labels run: one, one, one, seven, one, seven, seven, seven, seven, seven. Three label changes exist. Cut A comes after the third image. Left holds three ones, so its Gini is zero. Right holds one one and six sevens, seven images in all. The shares are one seventh and six sevenths, and the Gini is one minus about 0.02 minus about 0.73, so roughly 0.24. Weighted by size, the children score 0.3 times zero plus 0.7 times 0.24, about 0.17. The drop from the parent is 0.48 minus 0.17, about 0.31.
Cut B comes after the fourth image. Left holds three ones and a seven, with a Gini of 0.375. Right holds one one and five sevens, six images, with a Gini of about 0.28. Weighted, that is 0.4 times 0.375 plus 0.6 times 0.28, about 0.32. The drop is only about 0.16.
Cut C comes after the fifth image. Left holds four ones and a seven, with a Gini of 0.32. Right holds five sevens, so its Gini is zero. Weighted, that is 0.5 times 0.32 plus 0.5 times zero, which is 0.16. The drop is 0.48 minus 0.16, or 0.32, just ahead of Cut A's 0.31. Cut C wins. The tree takes the largest drop, writes that question down, and repeats the whole process inside each side.
The weakness of looking one step ahead
This procedure is greedy. At every node it picks the best single question right now and never asks whether a worse question now would open up a better one later. Picture an XOR pattern, where a label depends on two pixels together: the class is one when exactly one of them is dark. Looking at either pixel alone, the classes stay evenly mixed, so no first cut shows any gain. A greedy tree can pass right over a pair that would have solved the problem. Finding the truly best tree is NP-complete, which in practice means no known method is fast enough to search for it. So trees settle for a good tree built one step at a time.
Growing a tree on MNIST
In scikit-learn the tool is DecisionTreeClassifier, from the tree module. Four settings matter here. The criterion setting picks the impurity measure, the string "gini" by default or "entropy". The max depth setting caps how many questions can be asked in a row, and its default, None, means no cap. The min samples leaf setting is the smallest number of training images any leaf may hold, and it defaults to one. And random state fixes the order in which the tree tries pixels, which only matters when two pixels give exactly the same impurity drop and the tree has to break the tie.
Keep the split from before. Fit on the first fifty thousand training images, score on the next ten thousand, and leave the test set sealed. You also don't need a scaler. A tree only ever asks whether one pixel is at or below a threshold. Dividing every pixel by two hundred fifty-five, or passing them through StandardScaler, moves each threshold along with the data, so every image still lands on the same side of every question, and the tree makes the same predictions. Last chapter, scaling changed what nearest neighbors meant by close. Here it changes nothing.
Start with the default tree, no limits at all. Fitting usually takes well under a minute on a laptop, even though at every node the tree sorts the images by each of the seven hundred and eighty-four pixels and checks every useful midpoint. Then ask it what it built. The get depth method returns the number of questions on its longest path, and get n leaves returns how many leaves it has. Expect thousands of leaves. Left alone, the tree keeps splitting until every leaf is pure, and many of those leaves hold only one or two training images. A leaf with one image in it is a path of questions written for that single image. That is memorization you can count.
Score it both ways. Training accuracy comes out at one hundred percent, or within a hair of it, since nearly every training image sits in a leaf that holds only its own label. Validation accuracy usually lands around eighty-seven or eighty-eight percent. Put that next to the other models on the same split. The floor from always guessing one is about eleven percent. Logistic regression got about ninety-two, and nearest neighbors about ninety-seven. The tree beats the floor by a wide margin and still loses to both. Asking about one pixel at a time is a blunt way to read handwriting, and the full tree spends much of its size on images it will never see again.
Now sweep max depth and record training and validation accuracy at each value. A depth of one is a single question with two leaves, so it can name at most two digits. Its accuracy can't get far past twenty percent, because any two digits together make up only about a fifth of the images. From there, a run like this typically shows depth two near a third, depth five in the sixties, depth ten in the mid-eighties, and very little gain past fifteen. Your numbers will differ by a point or two. Training accuracy keeps climbing all the way to one hundred percent. Validation climbs with it at first, then flattens, and can slip a little as the tree goes deeper. The space between the two curves is overfitting you can measure. Each level past the flat point buys training accuracy and nothing on images the tree hasn't seen.
The min samples leaf setting attacks the same problem from the other side. Instead of stopping at a fixed depth, it forbids any leaf with fewer images than the number you give. Set it to five or twenty and the tree can't carve out a pocket for one odd image, so the leaf count drops sharply. Validation accuracy usually holds steady or moves by about a point, while the tree gets much smaller. On ten thousand validation images at about eighty-seven percent, chance alone moves the score by roughly a third of a point, so treat gaps smaller than that as ties. When two settings tie, prefer the smaller tree. It makes fewer claims about the training data that validation never got to test.
One more control is worth knowing by name. Cost-complexity pruning grows the full tree and then cuts back branches whose impurity drop isn't worth the extra leaves. In scikit-learn it is the ccp alpha setting. Zero, the default, means no pruning, and larger values prune harder. The cost complexity pruning path method lists the alpha values at which branches drop off. It is slower to explore on MNIST than the two limits above, so this chapter's sweep sticks with depth and leaf size.
Reading what the tree learned
A tree's main selling point is that you can read it, so read one. Fit a small tree with max depth set to two. Then call export text, from the same tree module, on that fitted tree and print the result. You get indented lines of text. Each question appears as a pixel name, like feature three hundred fifty, a less-than-or-equal sign and a threshold, and each leaf appears as a predicted class. The plot tree function draws the same thing with matplotlib. Both take their own max depth argument, so you can print just the top of a big tree without drawing thousands of boxes.
The pixel numbers come from flattening each image row by row, so you can turn one back into a spot on the picture. Divide the pixel number by twenty-eight. The whole-number part is the row, counting from zero at the top, and the remainder is the column, counting from zero at the left. Pixel three hundred fifty is row twelve, column fourteen, right in the middle of the image. The fitted tree also stores its questions as arrays. Its tree underscore attribute holds one array called feature and one called threshold, and the first entry of each is the root question, the one every image is asked first.
Then look at how the whole tree used the pixels. After fitting, the feature importances attribute gives one number per pixel: the share of the total impurity drop that pixel's questions produced, so all seven hundred and eighty-four add up to one. Reshape it to twenty-eight by twenty-eight and draw it with imshow. The bright pixels sit near the center, where strokes differ from one digit to another. The border stays near zero, which matches the inspection earlier in the course: border pixels are blank in almost every image, so a question about them can't split anything. Compare this with the weight images from logistic regression. Those showed, for each digit, which pixels pushed toward it and which pushed away. This map has no sign and no digit. It only says which pixels the tree found worth asking about.
How far to trust a tree
Two cautions come with every tree. The first is about its probabilities. Predict proba on a tree returns the class counts in the leaf an image lands in, divided by the size of that leaf. An unlimited tree has pure leaves, so nearly every probability it gives is exactly zero or exactly one. The tree claims certainty almost every time, while being right about eighty-seven times in a hundred. With min samples leaf at twenty, every leaf holds at least twenty images, so the probabilities come in steps no bigger than a twentieth. That is better, but it is still a count inside one leaf, not a measured confidence. Nearest neighbors had the same problem, with probabilities in steps of one over k. Ranking tools such as ROC curves will run on these scores, but the scores sit in big tied blocks, and they need calibrating before anyone reads them as real probabilities.
The second caution is instability. Drop a random five percent of the fifty thousand training images and refit. NumPy's default rng, given a fixed seed, can choose forty-seven thousand five hundred row positions to keep, with replace set to false. The validation score changes little. But the root question can move to a different pixel, and when it does, every question below it changes too, because each branch is now built from a different set of images. Small trees show this most plainly: print both depth-two trees with export text and compare them line by line. A single tree is a high-variance model. Its overall accuracy is steady, but its structure, and its answer on a borderline image, depend on exactly which images it was trained on.
That instability also points to the fix. If one tree's structure depends on the luck of its sample, many trees grown on different samples will make different mistakes, and a vote among them cancels much of that luck. That is a random forest, and it comes next.
Your exercise
Sweep max depth against min samples leaf on the validation split. Use max depth values of five, ten, fifteen, twenty and None, and min samples leaf values of one, five, twenty and fifty. That is twenty fits, and since the deeper ones each take a good fraction of a minute, plan on several minutes for the grid. For each fit, record training accuracy, validation accuracy, fit time and the leaf count from get n leaves. Before you start, write down which cell you expect to win and roughly how many leaves it will have.
Then read the grid. Find the best validation score and every cell within a third of a point of it, since those are ties at this size. Among the ties, pick the one with the fewest leaves and write down why. Two checks should hold. Within each max depth, training accuracy should generally fall as min samples leaf grows, because larger leaves can't fit single odd images. And at max depth five, min samples leaf should barely matter, since that tree has at most thirty-two leaves holding about fifteen hundred images each on average. If either check fails, look for a bug in your loop before you look for a lesson in the numbers. Keep the test set sealed, and add the grid to your project notes beside the logistic-regression and nearest-neighbor results.
Two items from the news
Google DeepMind announced Gemini 4 Carbon on October 28, 2026, aimed at cybersecurity and engineering work. Access is limited to select partner programs, so for now it is an announcement, not something you can use. Treat any claims about it as unchecked until you can run it yourself.
A paper posted on October 29, arXiv 2610.39556, studies fraud detection under operating limits. It uses chronological holdouts, meaning train on earlier transactions and test on later ones, with tree ensembles XGBoost and LightGBM, explained using SHAP. Platt calibration, a logistic correction to raw scores, cut the Brier score on the PaySim data from 0.1141 to 0.0245. The Brier score is the average squared gap between predicted probability and the outcome, so lower means better calibrated. Then a rule alerting on only the top one percent of scores cut false-positive investigations from 192 to 117, but recall fell from 0.4236 to 0.2122. That is the threshold trade-off from earlier, now forced by how many cases investigators can handle. These numbers hold for that dataset and setup only, but they tie neatly to the leaf-count probabilities above: scores from trees need calibrating before you trust them as probabilities.
Want a Program of your own?
Gnothi wrote and narrated this chapter. Name a subject and it writes you a course, or a story that teaches it, one chapter at a time, delivered to your podcast app.
Get started free