Suppose you want a second opinion on a medical report. You would not trust one doctor if you could ask a hundred, each trained a little differently and each looking at different details. If most of them reach the same conclusion, you can be fairly confident. A random forest works on this principle. It is a crowd of decision trees that vote.
Random forest is one of the most widely used algorithms in machine learning, and for good reason. It handles both classification and regression, works well with little tuning, copes with many features and gives you a measure of which features matter. It is often the first strong model people try on a table of data, and the one other models are compared against.
In this tutorial, we begin with the decision tree, the building block of the forest, and see why a single tree is not enough. We then explain how a random forest is built, how its trees split data using the Gini index, entropy or mean squared error, and what its strengths and weaknesses are. A complete Python program follows, with output from a real run that includes accuracy, precision and recall, the effect of the number of trees and the most important features. We finish with common mistakes and a short FAQ.
Classification is a supervised learning task. The model learns from examples that already have labels, then predicts the label of new data, such as spam or not spam, or benign or malignant. Many algorithms do this, including logistic regression, KNN, SVM and Naive Bayes. Random forest is one of the strongest general purpose choices among them, and it is also used for regression, where the answer is a number and not a class.
A decision tree classifies data by asking a series of yes or no questions. Each question splits the data into smaller groups, and the final group gives the answer. For example, a tree for loan approval might ask whether income is above a limit, then whether there is a past default, and then end at approve or reject.

A single tree is easy to read, but it has a weakness. If left to grow deep, it memorises its training data, including the noise. Change a few rows and you can get a very different tree. That sensitivity is called high variance, and it is what the forest fixes.
A random forest builds many decision trees and combines their answers. Two kinds of randomness make the trees different from each other:
To predict, every tree gives its answer. For classification, the class with the most votes wins. In scikit learn, the forest averages the trees’ predicted probabilities, which usually gives the same answer. For regression, it averages the trees’ numbers.
Say a forest has 6 trees, and 4 of them predict class A while 2 predict class B. The forest answers class A. Even if two of the trees are wrong, the group is still right.

Each tree makes its own mistakes, but because the trees are different, the mistakes point in different directions and largely cancel when averaged. The pattern that every tree shares is kept. The result is a model with lower variance than one tree, and usually higher accuracy on new data, without much extra effort.
| Point | Single decision tree | Random forest |
|---|---|---|
| Accuracy on new data | Lower and unstable | Higher and steadier |
| Overfitting | High if grown deep | Reduced, not removed |
| Easy to explain | Yes, you can draw it | No, it is a black box |
| Speed | Fast to train and predict | Slower, many trees |
| Tuning needed | Depth and splits matter a lot | Works well with defaults |
At every node, a tree looks for the question that separates the data best. How it measures best depends on the task.
For regression, a common choice is mean squared error, or MSE. It is the average of the squared gaps between the predicted values and the actual values. In the formula, N is the number of data points, fi is the value the model returns, and yi is the actual value for that data point. A split is chosen if it makes this error smaller. MSE is a common choice, not the only one.

For classification, the tree uses a measure of how mixed the classes are in a node. A node with only one class is pure, and a node with an even mix is as impure as it gets. A good split makes the groups after the split purer than before.
The Gini index is one minus the sum of the squared class proportions. In the formula, pi is the relative frequency of each class and c is the number of classes. It measures impurity. It does not measure which branch is more likely.

Entropy is another measure of impurity. It is the negative sum of each class proportion times the base 2 logarithm of that proportion.

Here is a worked example. A node holds 10 records, 6 of one class and 4 of the other, so the proportions are 0.6 and 0.4.
| Measure | Calculation | Result |
|---|---|---|
| Gini index | 1 minus (0.6 squared plus 0.4 squared) | 0.48 |
| Entropy | Minus (0.6 times log2 of 0.6, plus 0.4 times log2 of 0.4) | 0.971 |
| A pure node | Only one class | Gini 0, entropy 0 |
A perfectly even node would score 0.5 on Gini and 1 on entropy, so this node is quite mixed. In practice, Gini and entropy usually pick very similar splits. Gini is the default in scikit learn and is a little faster.
This program uses the breast cancer dataset that comes with scikit learn, with 569 patients and 30 measurements each, labelled malignant or benign. It compares one tree with a forest, shows precision and recall, tests how the number of trees matters, lists the most important features and checks the Gini and entropy example above.
When I ran the program, it printed:
The test set has 171 patients, so the forest got about 4 more patients right than the single tree. The out of bag score is a free validation estimate, computed from the rows each tree did not see. It came to 0.967 without touching the test set.
Overall accuracy looks fine at 0.94, but look at the malignant row. Its recall is 0.91, which means the forest caught 58 of 64 malignant cases and missed 6. In a medical setting, a missed malignant case is the costly error, so recall for that class matters more than the headline number. This is the check the original page left out.
One tree scores 0.912, and more trees help overall. But 50 trees scored a little below 10 trees, which is normal noise on a small test set, since one patient is worth about 0.6 points. The honest lesson is that more trees give steadier results, with diminishing returns. A forest does not get worse from adding trees. It only gets slower.
A forest can rank which features it relied on. Here the largest tumour measurements matter most. Treat this ranking with care. Perimeter, area and radius are strongly related to each other, so the forest splits the credit between them. The importance scores show what the model used, not what causes the result.
| Setting | Default | What it does |
|---|---|---|
| n_estimators | 100 | Number of trees. More is steadier but slower |
| max_depth | None | How deep trees can grow. Limit it to reduce overfitting |
| max_features | sqrt | How many features are considered at each split |
| min_samples_leaf | 1 | Minimum rows in a leaf. Raise it to smooth the model |
| oob_score | False | Switch on for a free validation score |
| class_weight | None | Use balanced when one class is rare |
| n_jobs | None | Parallel jobs. Use minus one for all cores |
| random_state | None | Set a number so results can be repeated |
A random forest turns many unstable trees into one dependable model. Run the program above on your own data, look at recall as well as accuracy, and use the out of bag score as a quick check. When you want to push accuracy higher, look at boosting next.