Python 在相似性矩阵中找到最大值,而不是在对角线上

Python 在相似性矩阵中找到最大值,而不是在对角线上,python,matrix,numpy,Python,Matrix,Numpy,假设我有以下几点: 请注意,对角线上的值均等于100.0,且上三角形等于下三角形 我想找出五个不同的最高值的索引,而不是在对角线上 目前,我用暴力的方式: from collections import defaultdict d = defaultdict(list) for i in range(len(matrix)): for j in range(len(matrix[i])): d[matrix[i][j]].append((i,j)) for value in

假设我有以下几点:

请注意,对角线上的值均等于100.0,且上三角形等于下三角形

我想找出五个不同的最高值的索引,而不是在对角线上

目前,我用暴力的方式:

from collections import defaultdict
d = defaultdict(list)
for i in range(len(matrix)):
    for j in range(len(matrix[i])):
      d[matrix[i][j]].append((i,j))

for value in sorted(d.keys(), reverse=True)[1:6]:
    print value, d[value]
其中:

95.8333333333 [(3, 6), (3, 7), (6, 3), (7, 3)]
91.6666666667 [(2, 6), (2, 7), (6, 2), (6, 8), (7, 2), (7, 8), (8, 6), (8, 7)]
91.3066666667 [(1, 2), (1, 6), (1, 7), (1, 8), (2, 1), (6, 1), (7, 1), (8, 1)]
88.0 [(2, 3), (2, 4), (3, 2), (3, 8), (4, 2), (4, 6), (4, 7), (4, 8), (6, 4), (7, 4), (8, 3), (8, 4)]
87.5 [(1, 3), (1, 4), (3, 1), (4, 1), (5, 9), (9, 5)]
但这是低效的,因为我遍历了整个矩阵,而我只需要遍历矩阵的一半:对于最高值
95.8333333
,我只关心索引
(3,6)
(3,7)

有没有更有效的方法来实现这一点,也许使用numpy?

numpy会更快

import numpy as np

m = np.array(matrix) * np.diag(len(matrix)) # set the upper triangle to zero
for top_value in sorted((np.unique(m)), reverse=True)[1:6]:
    print top_value, zip(*np.where(m == top_value))
  • 使用xrange而不是range
  • 循环j仅到i-1(如果i=0,则内部循环永远不会运行…)
  • 为了有效使用,不要对列表排序,而是使用heapq中的NLAGEST 因为它为此使用堆数据结构。这对于大型矩阵应该很重要

也有100.0个元素不在对角线上@安蒂·哈帕拉被抓住了!我也想要那些。
import numpy as np

m = np.array(matrix) * np.diag(len(matrix)) # set the upper triangle to zero
for top_value in sorted((np.unique(m)), reverse=True)[1:6]:
    print top_value, zip(*np.where(m == top_value))
from heapq import nlargest
from collections import defaultdict

d = defaultdict(list)

for i in xrange(len(matrix)):
    for j in xrange(i):
      d[matrix[i][j]].append((i, j))

for value, positions in nlargest(5, d.items(), key=lambda item: item[0]):
    print value, positions