python - 如何使用两个 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
如果有人能给我关于如何定义这个函数的任何指示,我将不胜感激。
解决方案
此函数计算每个left
或right
标签数组的基尼指数。只需根据您的公式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
推荐阅读
- c# - 如何使用以编程方式返回 FileContentResult 的 API 调用
- json - 如何通过快速更新特定值将数据重写到相同的 json 文件
- c# - 是否可以从 docker 容器内部访问任务定义
- chromium - 从网络选项卡捕获 Websocket 消息
- sql - 如何正确排序 SSRS 2016 中的字母数字参数/字段?
- arrays - 检查数组中的随机元素,如果为真则返回
- json - 如何在 tcl 中将多级字典写入 json?
- python - PyTorch:时间序列任务的数据加载器
- asp.net-mvc - Stuctured architecture mvc core如何在BLL层使用Automapper?
- r - 从目录中读取最新的 SPSS 文件