如何在梯形相似度矩阵上计算加权平均值

时间:2020-08-29 13:11:31

标签: python numpy cosine-similarity

我有一个像这样的三角形相似矩阵。

[[3, 1, 2, 0],
 [1, 3, 0, 0],
 [1, 0, 0, 0],
 [0, 0, 0, 0]]

在丢弃零要素的情况下,如何计算每行的加权平均值?

3 个答案:

答案 0 :(得分:2)

您可以沿第二个轴相加,然后除以sum除以每行的非零值。然后使用np.divide中的where可以划分 where 的条件,该条件可以通过将其设置为指定非零值所在的掩码来防止除法零错误:

a = np.array([[3, 1, 2, 0],
              [1, 3, 0, 0],
              [1, 0, 0, 0],
              [0, 0, 0, 0]])

m = (a!=0).sum(1)
np.divide(a.sum(1), m, where=m!=0)
# array([2., 2., 1., 0.])

答案 1 :(得分:0)

在每一行上循环,然后在每个元素上循环。遍历元素时,请勿包含零。如果仅找到零元素,则只需将零(或任何您想要的默认值)添加到列表中即可。

weighted_averages = []
for row in matrix:
  total_weight = 0
  number_of_weights = 0
  for element in row:
    if element != 0:
      total_weight += element
      number_of_weights += 1
  if number_of_weights == 0:
    weighted_averages.append(0)
  else:
    weighted_averages.append(total_weight/number_of_weights)
您的情况下的

weighted_averages返回为: [2.0, 2.0, 1.0, 0]

答案 2 :(得分:0)

您可以使用numpy来计算加权平均值。

import numpy as np
a = np.array([
 [3, 1, 2, 0],
 [1, 3, 0, 0],
 [1, 0, 0, 0],
 [0, 0, 0, 0]
])
weights = np.array([1,2,3,4])
#create an mask where element is 0
ma = np.ma.masked_equal(a,0)
#take masked weighted average
ans = np.ma.average(ma, weights=weights,axis = 1)
#fill masked points as 0
ans.filled(0)

输出:

array([1.83333333, 2.33333333, 1.        , 0.        ])

仅Python:

ar = [[3, 1, 2, 0],
 [1, 3, 0, 0],
 [1, 0, 0, 0],
 [0, 0, 0, 0]]
weight = [1,2,3,4]
ans=[]
for li in ar:
    wa = 0 #weighted average
    we = 0 #weights
    for index,ele in enumerate(li): 
        if ele !=0:
            wa+=weight[index]*ele
            we+=weight[index]
    if we!=0:
        ans.append(wa/we)
    else:
        ans.append(0)
ans