【问题标题】:Vectorized KL divergence calculation between all pairs of rows of a matrix矩阵的所有行对之间的向量化 KL 散度计算
【发布时间】:2021-04-27 13:46:26
【问题描述】:

我想找出矩阵的所有行对之间的 KL 散度。为了解释,我们假设有一个形状为N x K 的矩阵V。现在我想创建一个维度为N x N 的矩阵L,其中每个元素L[i,j] = KL(V[i,:],V[j,:])。到目前为止,我已经使用了以下scipy.stats.entropy 来计算

upper_triangle = [entropy(V[i,:],V[j,:]) for (i,j) in itertools.combinations(range(N,2)]
lower_triangle = [entropy(V[j,:],V[i,:]) for (i,j) in itertools.combinations(range(N,2)]

L = np.zeroes((N,N))

L[np.triu_indices(N,k = 1)] = upper_triangle
L[np.tril_indices(N,k = -1)] = lower_triangle

有没有更聪明的方法?

【问题讨论】:

    标签: python numpy scipy vectorization scipy.stats


    【解决方案1】:

    好的,在稍微调整一下 KL 散度方程之后,下面的方程也应该可以工作,当然,它的数量级更快,

    kl = np.dot(V, np.log(Vc).T)
    right = kl + kl.T
    left = np.tile(np.diag(kl),(kl.shape[0],1))
    left = left + left.T
    L = left - right
    

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 2020-03-13
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 2021-11-08
      • 2018-04-29
      相关资源
      最近更新 更多