使用reduce计算节点的gini索引

时间:2019-05-15 04:14:23

标签: python functools

我正在尝试应用公式:

Formula

我不清楚为什么这不起作用:

{}

评估def gini_node(node): count = sum(node) gini = functools.reduce(lambda p,c: p + (1 - (c/count)**2), node) print(count, gini) print(1 - (node[0]/count)**2, 1 - (node[1]/count)**2) return gini 打印:

gini([[175, 330], [220, 120]])

请注意,在给出示例输入的情况下,第二个打印语句将打印我要求和的数字。返回值(第一个打印语句的第二个值)应为0到1之间的数字。

我的reduce怎么了?

我要编写的完整函数是:

505 175.57298304087834
0.8799137339476522 0.5729830408783452
340 220.87543252595157
0.5813148788927336 0.8754325259515571

1 个答案:

答案 0 :(得分:1)

reduce工作的方式是从容器中获取2个参数(仅2个)
https://docs.python.org/3/library/functools.html#functools.reduce
并执行赋予它的操作,然后继续对列表进行相同的操作使用2个参数。

gini = functools.reduce(lambda p,c: p + (1 - (c/count)**2), node)

对于第一个节点(175, 330),此lambda将在175中使用p,在330中使用c,然后返回175.57298304087834,而我们想要< / p>

gini = functools.reduce(lambda p,c: (1 - (p/count)**2) + (1 - (c/count)**2), node)


我添加了一些打印语句,让我们看看它们的输出。

import functools

def gini_node(node):
    count = sum(node)
    gini = functools.reduce(lambda p,c: (1 - (p/count)**2) + (1 - (c/count)**2), node)
    print(count, gini)
    print(1 - (node[0]/count)**2, 1 - (node[1]/count)**2)
    return gini

def gini (groups):
    counts = [ sum(node) for node in groups ]
    count = sum(counts)
    proportions = [ n/count for n in counts ]
    print(count, counts, proportions) #This
    gini_indexes = [ gini_node(node) * proportion for node, proportion in zip(groups, proportions)]
    print(gini_indexes) #And this
    return sum(gini_indexes)

# test
print(gini([[175, 330], [220, 120]]))

rahul@RNA-HP:~$ python3 so.py
845 [505, 340] [0.5976331360946746, 0.40236686390532544]
505 1.4528967748259973 #Second number here is addition of 2 numbers below
0.8799137339476522 0.5729830408783452
340 1.4567474048442905 #Same for this
0.5813148788927336 0.8754325259515571
#The first number of this list is first 1.45289677.... * 0.597633...
#Basically the addition and then multiplication by it's proportion.
[0.868299255961099, 0.5861468847894187]
#What you are returning to final print statement is the addition of gini co-effs of each node i.e the sum of the list above
1.4544461407505178

如果有两个以上参数(*)

 gini = sum([(1 - (p/count)**2) for p in node])

与上面定义的reduce()函数相同。