python计算矩阵的散度_Python:多分布计算中Kullback-Leibler散度的快速高效实现

这应该管用。def kullback_leibler_divergence(X):

"""

Finds the pairwise Kullback-Leibler divergence

matrix between all rows in X.

Parameters

----------

X : array_like, shape (n_samples, n_features)

Array of probability data. Each row must sum to 1.

Returns

-------

D : ndarray, shape (n_samples, n_samples)

The Kullback-Leibler divergence matrix. A pairwise matrix D such that D_{i, j}

is the divergence between the ith and jth vectors of the given matrix X.

Notes

-----

Based on code from Gordon J. Berman et al.

(https://github.com/gordonberman/MotionMapper)

References:

-----------

Berman, G. J., Choi, D. M., Bialek, W., & Shaevitz, J. W. (2014).

Mapping the stereotyped behaviour of freely moving fruit flies.

Journal of The Royal Society Interface, 11(99), 20140672.

"""

X_log = np.log(X)

X_log[np.isinf(X_log) | np.isnan(X_log)] = 0

entropies = -np.sum(X * X_log, axis=1)

D = np.matmul(-X, X_log.T)

D = D - entropies

D = D / np.log(2)

D *= (1 - np.eye(D.shape[0]))

return D

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值