我使用大量数据,这段代码的执行时间非常重要。每次迭代的结果都是相互依赖的,因此很难并行实现。如果有更快的方法来实现此代码的某些部分,例如:
,那将是非常棒的填充weights
矩阵非常快。
代码执行以下操作:
word_list
列表,其中包含count
个元素。在开始时,每个单词都是一个单独的列表。 count
的二维列表(count
x weights
)(下三角矩阵,i>=j
为零的值)word_list
中的相应单词列表。它将两个列表保存在索引较小的列表(max_j
)中,并删除索引较大的列表(max_i
)。THRESHOLD
我可能会想到一个不同的算法来完成这项任务,但我现在没有任何想法,如果至少有一个小的性能改进就会很棒。
我尝试使用NumPy,但效果更差。
weights = fill_matrix(count, N, word_list)
while 1:
# find the max element in the matrix and its indices
max_element = 0
for i in range(count):
max_e = max(weights[i])
if max_e > max_element:
max_element = max_e
max_i = i
max_j = weights[i].index(max_e)
if max_element < THRESHOLD:
break
# reset the value of the max element
weights[max_i][max_j] = 0
# here it is important that always max_j is less than max i (since it's a lower triangular matrix)
for j in range(count):
weights[max_j][j] = max(weights[max_i][j], weights[max_j][j])
for i in range(count):
weights[i][max_j] = max(weights[i][max_j], weights[i][max_i])
# compare the symmetrical elements, set the ones above to 0
for i in range(count):
for j in range(count):
if i <= j:
if weights[i][j] > weights[j][i]:
weights[j][i] = weights[i][j]
weights[i][j] = 0
# remove the max_i-th column
for i in range(len(weights)):
weights[i].pop(max_i)
# remove the max_j-th row
weights.pop(max_i)
new_list = word_list[max_j]
new_list += word_list[max_i]
word_list[max_j] = new_list
# remove the element that was recently merged into a cluster
word_list.pop(max_i)
count -= 1
答案 0 :(得分:2)
这可能会有所帮助:
def max_ij(A):
t1 = [max(list(enumerate(row)), key=lambda r: r[1]) for row in A]
t2 = max(list(enumerate(t1)), key=lambda r:r[1][1])
i, (j, max_) = t2
return max_, i, j
答案 1 :(得分:1)
这取决于你想要投入多少工作,但如果你真的关心速度,你应该研究Cython。 quick start tutorial给出了一些例子,从35%的加速到惊人的150倍加速(你需要付出一些额外的努力)。