import json def gini(labels): positive_rate = sum(labels) / len(labels) return 2 * positive_rate * (1 - positive_rate) x = [1, 2, 3, 4] y = [0, 0, 1, 1] thresholds = [1.5, 2.5, 3.5] weighted = [] for threshold in thresholds: # 按切点分成两个非空子节点,各自的不纯度按样本占比加权。 left = [label for value, label in zip(x, y) if value <= threshold] right = [label for value, label in zip(x, y) if value > threshold] weighted.append((len(left) * gini(left) + len(right) * gini(right)) / len(y)) best = thresholds[weighted.index(min(weighted))] # 为解释投票,另外给三棵阈值已知的树;这里只演示预测。 votes = [int(3 > threshold) for threshold in thresholds] assert best == 2.5 and sum(votes) == 2 result = {"gini_after_split": weighted, "best_threshold": best, "votes": votes, "prediction": int(sum(votes) >= 2)} print("LAB_RESULT " + json.dumps(result, ensure_ascii=False))