首页 > 解决方案 > 如何使用两个 numpy 数组计算基尼指数

问题描述

因此,对于机器学习课程,我需要计算具有 2 个类别(在本例中为 0 和 1)的决策树的基尼指数。我已经阅读了多个关于如何计算的资料,但我似乎无法让它在我自己的脚本中工作。尝试了大约 10 种不同的计算后,我有点绝望。

数组是:

Y_left = np.array([[1.],[0.],[0.],[1.],[1.],[1.],[1.]])
Y_right = np.array([[1.],[0.],[0.],[0.],[1.],[0.],[0.],[1.],[0.]])

输出应该是 0.42857。

公式

C 是类标签的集合(所以 2),S_L 和 S_R 是由拆分标准确定的两个拆分。

我现在拥有的:

def tree_gini_index(Y_left, Y_right, classes):
    """Compute the Gini Index.
    # Arguments
        Y_left: class labels of the data left set
            np.array of size `(n_objects, 1)`
        Y_right: class labels of the data right set
            np.array of size `(n_objects, 1)`
        classes: list of all class values
    # Output
        gini: scalar `float`
    """
    gini = 0.0
    total = len(Y_left) + len(Y_right)
    gini = sum((sum(Y_left) / total)**2, (sum(Y_right) / total)**2)
    return gini

如果有人能给我关于如何定义这个函数的任何指示,我将不胜感激。

标签: pythonnumpymachine-learning

解决方案


此函数计算每个leftright标签数组的基尼指数。只需根据您的公式probs存储每个类的概率。p_c

import numpy as np

def gini(y, classes):

    y = y.reshape(-1, )                             # Just flattens the 2D array into 1D array for simpler calculations
    if not y.shape[0]:
        return 0
    
    probs = []
    for cls in classes:
        probs.append((y == cls).sum() / y.shape[0]) # For each class c in classes compute class probabilities
    
    p = np.array(probs)
    return 1 - ((p*p).sum())

之后,此函数计算它们的加权(按样本数)平均值,以生成相应拆分的最终基尼指数值。请注意,p_L并在您的公式中p_R扮演角色where is 。|S_n|/|S|n{left, right}

def tree_gini_index(Y_left, Y_right, classes):
    
    N = Y_left.shape[0] + Y_right.shape[0]
    p_L = Y_left.shape[0] / N
    p_R = Y_right.shape[0] / N
    
    return p_L * gini(Y_left, classes) + p_R * gini(Y_right, classes)

称它为:

Y_left = np.array([[1.],[0.],[0.],[1.],[1.],[1.],[1.]])
Y_right = np.array([[1.],[0.],[0.],[0.],[1.],[0.],[0.],[1.],[0.]])
tree_gini_index(Y_left, Y_right, [0, 1])

输出:

0.4285714285714286

推荐阅读