v9.1.1
Menu

Best Split Finder

mediumFREEDecision TreesMachine Learning 1

Find the best threshold for splitting a feature to maximize information gain.

Given a list of feature values and corresponding labels, try every midpoint between consecutive sorted unique feature values as a potential split threshold. For each threshold, split the data into left (≤\leq threshold) and right (>> threshold) subsets.

Information gain is the parent entropy minus the size-weighted entropies of the two subsets, with entropy measured in bits (log base 2).

Return the threshold that gives the highest information gain, along with the gain value, as a tuple (threshold, gain). Both rounded to 4 decimal places. If several thresholds tie for the highest gain, return the smallest one.

If there's no possible split (all values identical), or no threshold gives a gain greater than 0, return (None, 0.0).

Example

Input
feature_values = [1, 2, 3, 4]
labels = [0, 0, 1, 1]
Output
(2.5, 1.0)
Reasoning
  • feature_values holds one number per sample (1,2,3,41, 2, 3, 4) and labels holds its class (0,0,1,10, 0, 1, 1). The candidate thresholds are the points halfway between neighbouring distinct values: 1.51.5, 2.52.5 and 3.53.5.
  • The parent set has two of each class, so its entropy is H=−12log⁡212−12log⁡212=1H = -\tfrac{1}{2}\log_2\tfrac{1}{2} - \tfrac{1}{2}\log_2\tfrac{1}{2} = 1 bit.
  • At 1.51.5: the left side is {0}\{0\} (H=0H = 0) and the right side is {0,1,1}\{0, 1, 1\} with H=−13log⁡213−23log⁡223≈0.9183H = -\tfrac{1}{3}\log_2\tfrac{1}{3} - \tfrac{2}{3}\log_2\tfrac{2}{3} \approx 0.9183. The gain is 1−34(0.9183)≈0.31131 - \tfrac{3}{4}(0.9183) \approx 0.3113. By symmetry 3.53.5 also gives 0.31130.3113.
  • At 2.52.5: the left side is {0,0}\{0, 0\} and the right side is {1,1}\{1, 1\}. Both are pure, so the gain is 1−24⋅0−24⋅0=1.01 - \tfrac{2}{4}\cdot 0 - \tfrac{2}{4}\cdot 0 = 1.0, the largest possible here.
  • Notice that a gain of 1.01.0 equals the parent entropy: the split removes all uncertainty, giving (2.5, 1.0).

Constraints

  • feature_values: list of numeric values
  • labels: list of class labels (same length)
  • Split: left = values <= threshold, right = values > threshold
  • Return (best_threshold, best_gain) rounded to 4 decimal places

Learn this in

More from Machine Learning 1

solution.py

Test results

Sign in to run your code against the test cases.