Compute information gain for a candidate split in a decision tree, which tells you how much uncertainty about the labels is reduced after splitting. You’ll implement entropy and use it to score a split given arrays of labels and feature values.
The Information Gain for a binary split is defined as:
where is the entropy of the labels.
Implement the function
def information_gain(y, x, threshold):
"""
Computes information gain for a binary split x <= threshold vs x > threshold.
Args:
y (np.ndarray): Class labels (e.g., 0/1 or 0..K-1), length n.
x (np.ndarray): Feature values aligned with y, length n.
threshold (float): Split threshold.
Returns:
float: Information gain IG = H(y) - [ (n_L/n) * H(y_L) + (n_R/n) * H(y_R) ].
"""
# Your solution belowRules:
y = np.array([0, 0, 1, 1])
x = np.array([2.0, 3.0, 8.0, 9.0])
threshold = 5.0
information_gain(y, x, threshold)Output:
1.0{
"x": [
2,
3,
8,
9
],
"y": [
0,
0,
1,
1
],
"threshold": 5
}1| Argument | Type |
|---|---|
| x | np.ndarray |
| y | np.ndarray |
| threshold | float |
| Return Name | Type |
|---|---|
| value | float |
Use NumPy.
Return a float.
Use np.unique(y, return_counts=True) to get class counts for entropy calculation.
Entropy is -sum(p * log2(p)). Handle p=0 implicitly by only iterating over non-zero counts.
Use boolean masking mask = x <= threshold to split y into y[mask] and y[~mask].