python数组运算技巧_python – 计算每个numpy数组行的熵的最快方法?

scipy.special.entr为数组中的每个元素计算-x * log(x).调用之后,您可以对行进行求和.

这是一个例子.首先,创建一个正数值的数组p,其行总和为1:

In [23]: np.random.seed(123)

In [24]: x = np.random.rand(3, 10)

In [25]: p = x/x.sum(axis=1, keepdims=True)

In [26]: p

Out[26]:

array([[ 0.12798052, 0.05257987, 0.04168536, 0.1013075 , 0.13220688,

0.07774843, 0.18022149, 0.1258417 , 0.08837421, 0.07205402],

[ 0.08313743, 0.17661773, 0.1062474 , 0.01445742, 0.09642919,

0.17878489, 0.04420998, 0.0425045 , 0.12877228, 0.1288392 ],

[ 0.11793032, 0.15790292, 0.13467074, 0.11358463, 0.13429674,

0.06003561, 0.06725376, 0.0424324 , 0.05459921, 0.11729367]])

In [27]: p.shape

Out[27]: (3, 10)

In [28]: p.sum(axis=1)

Out[28]: array([ 1., 1., 1.])

现在计算每行的熵. entr使用自然对数,因此要得到base-2 log,将结果除以log(2).

In [29]: from scipy.special import entr

In [30]: entr(p).sum(axis=1)

Out[30]: array([ 2.22208731, 2.14586635, 2.22486581])

In [31]: entr(p).sum(axis=1)/np.log(2)

Out[31]: array([ 3.20579434, 3.09583074, 3.20980287])

如果您不希望依赖于scipy,则可以使用显式公式:

In [32]: (-p*np.log2(p)).sum(axis=1)

Out[32]: array([ 3.20579434, 3.09583074, 3.20980287])

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值