我试图用一个列表构建一个矩阵,然后用dict的值填充它。它可以处理小数据,但是当使用大数据(没有足够的Ram)时,计算机会崩溃。 我的脚本显然太重了,但我不知道如何改进它(第一次在编程中)。谢谢
import numpy as np
liste = ["a","b","c","d","e","f","g","h","i","j"]
dico = {"a/b": 4, "c/d" : 2, "f/g" : 5, "g/h" : 2}
#now i'd like to build a square array (liste x liste) and fill it up with the values of
# my dict.
def make_array(liste,dico):
array1 = []
liste_i = [] #each line of the array
for i in liste:
if liste_i :
array1.append(liste_i)
liste_i = []
for j in liste:
if dico.has_key(i+"/"+j):
liste_i.append(dico[i+"/"+j])
elif dico.has_key(j+"/"+i):
liste_i.append(dico[j+"/"+i])
else :
liste_i.append(0)
array1.append(liste_i)
print array1
matrix = np.array(array1)
print matrix.shape()
print matrix
return matrix
make_array(liste,dico)
非常感谢您的回答,使用in dico
或列表理解确实提高了脚本的速度,这非常有用。
但我的问题似乎是由以下功能引起的:
def clustering(matrix, liste_globale_occurences, output2):
most_common_groups = []
Y = scipy.spatial.distance.pdist(matrix)
Z = scipy.cluster.hierarchy.linkage(Y,'average', 'euclidean')
scipy.cluster.hierarchy.dendrogram(Z)
clust_h = scipy.cluster.hierarchy.fcluster(Z, t = 15, criterion='distance')
print clust_h
print len(clust_h)
most_common = collections.Counter(clust_h).most_common(3)
group1 = most_common[0][0]
group2 = most_common[1][0]
group3 = most_common[2][0]
most_common_groups.append(group1)
most_common_groups.append(group2)
most_common_groups.append(group3)
with open(output2, 'w') as results: # here the begining of the problem
for group in most_common_groups:
for i, val in enumerate(clust_h):
if group == val:
mise_en_page = "{0:36s} groupe co-occurences = {1:5s} \n"
results.write(mise_en_page.format(str(liste_globale_occurences[i]),str(val)))
当使用一个小文件时,我会得到正确的结果,例如:
contact a = groupe 2
contact b = groupe 2
contact c = groupe 2
contact d = groupe 2
contact e = groupe 3
contact f = groupe 3
但当使用重文件时,每个组只得到一个示例:
contact a = groupe 2
contact a = groupe 2
contact a = groupe 2
contact a = groupe 2
contact e = groupe 3
contact e = groupe 3
你可以创建一个矩阵mat=len(liste)*len(liste)的0,并通过你的dico和split键:“/”之前的val将是行数,“/”之后的val将是列数。这样您就不需要使用“has\u key”搜索功能。你知道吗
您的问题看起来像一个O(n2),因为您需要从
liste
中获得所有的组合。所以你必须有一个内环。你知道吗您可以尝试将每一行写入一个文件,然后在以后的新进程中,从该文件创建矩阵。新进程将使用更少的内存,因为它不必存储
liste
和dico
的大量输入。比如说:一旦执行完毕,您就可以调用
我使用了短路求值来减少
if
语句的代码行。实际上,如果您使用list comprehensions,您可以将make_array
函数简化为:相关问题 更多 >
编程相关推荐