【问题标题】:How to calculate weighted average on a traingular similarity matrix如何计算三角形相似度矩阵的加权平均值
【发布时间】:2020-08-29 22:05:47
【问题描述】:

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

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

如何在丢弃零元素的同时计算每一行的加权平均值?

【问题讨论】:

  • 你的预期输出是什么?

标签: python numpy cosine-similarity


【解决方案1】:

您可以沿第二个轴相加,然后除以sum 每行非零值的数量。然后在where 中使用np.divide 中的np.divide,您可以将满足条件的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.])

【讨论】:

    【解决方案2】:

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

    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]

    【讨论】:

      【解决方案3】:

      您可以使用 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
      

      【讨论】:

        猜你喜欢
        • 2019-10-30
        • 1970-01-01
        • 1970-01-01
        • 2021-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-04
        相关资源
        最近更新 更多