Python / Python Mathematical Intuition and Scikit Learn Interview Questions
How do decision trees decide which feature and threshold to split on? Explain Gini impurity and entropy.
At each node, a decision tree evaluates every feature and every possible threshold, and selects the split that produces the greatest reduction in impurity between the parent node and the weighted average impurity of the two child nodes. Two common impurity measures are Gini impurity and entropy.
Gini impurity for a node is G = 1 - Σpᵢ², where pᵢ is the proportion of class i in the node. It measures the probability that two randomly selected samples from the node would have different class labels. Entropy is H = -Σpᵢ log₂(pᵢ), borrowed from information theory, measuring the average uncertainty (bits needed to encode the class label). Both reach their maximum when classes are perfectly mixed (50/50 for binary) and zero when a node is pure (all one class).
from sklearn.tree import DecisionTreeClassifier, plot_tree
import numpy as np
def gini(y):
_, counts = np.unique(y, return_counts=True)
p = counts / counts.sum()
return 1 - np.sum(p ** 2)
def entropy(y):
_, counts = np.unique(y, return_counts=True)
p = counts / counts.sum()
return -np.sum(p * np.log2(p + 1e-15))
y_pure = np.array([1, 1, 1, 1]) # gini=0.0, entropy=0.0
y_mixed = np.array([1, 1, 0, 0]) # gini=0.5, entropy=1.0
print(gini(y_pure), gini(y_mixed)) # 0.0 0.5
print(entropy(y_pure), entropy(y_mixed))# 0.0 1.0
# scikit-learn: choose criterion explicitly
tree_gini = DecisionTreeClassifier(criterion='gini').fit(X, y)
tree_entropy = DecisionTreeClassifier(criterion='entropy').fit(X, y)Practical note: Gini and entropy almost always produce very similar trees — Gini is slightly faster to compute (no logarithm) and is scikit-learn's default. The bigger lever for tree quality is usually max_depth, min_samples_split, and min_samples_leaf, which control overfitting rather than the choice of impurity measure.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
