如何为给定方程写完美循环?

时间:2019-08-04 14:46:09

标签: python

我想在python中为以下方程式编写一个for循环: enter image description here

Z3是大小为M * d的矩阵。

JSD函数是:

def JSD(p, q, alpha):
  return np.sum(np.sqrt(p+alpha) * np.log(np.sqrt(p+alpha) / np.sqrt(q+alpha)))


similarity = 0
for i in range(Z3.shape[0]):
  for j in range(Z3.shape[0]): 
    if (Z3[j] != Z3[i]).all():
      m = 0.5*(Z3[i]+Z3[j])
      similarity += 0.5*JSD(Z3[i],m,2)+0.5*JSD(Z3[j],m,2)

print(similarity)

如何为上述方程式编写完美的代码?

1 个答案:

答案 0 :(得分:1)

def JSD(p, q, alpha):
  return np.sum(np.sqrt(p+alpha) * np.log(np.sqrt(p+alpha) / np.sqrt(q+alpha)))


similarity = 0
for i in range(Z3.shape[0]):
  for j in range(Z3.shape[0]): 
    if (j != i):
      m = 0.5*(Z3[i]+Z3[j])
      similarity += 0.5*JSD(Z3[i],m,2)+0.5*JSD(Z3[j],m,2)

print(similarity)