我的输入有一个形状:(9, 480, 1)
以下是我当前的职能:
def f(X):
ordered_max_scorers = np.sort(np.max(X, axis=2), axis=1)
cd_mat2 = np.array([[0] * len(X)] * len(X), dtype="float64")
for ind1, score1 in enumerate(ordered_max_scorers):
for ind2, score2 in enumerate(ordered_max_scorers[:ind1]):
cognitive_diversity = np.sum((score1 - score2)**2)**(1/2)
cd_mat2[ind1][ind2] = cognitive_diversity
cd_mat2[ind2][ind1] = cognitive_diversity
return cd_mat2
我正试图优化这个函数,使它运行得更快:它被对象A中的对象B调用一次。如果有区别的话,每次A运行一次B调用几百次(大约20次)。在
我试着用一点新意来代替:
^{pr2}$有:
cognitive_diversity = np.sqrt(np.sum(np.square(score1 - score2)))
但这似乎减慢了代码的速度。 我还尝试使用numba进行优化:
@autojit
def temp(x, y):
return np.sum((score1 - score2) ** 2) ** (1/2)
它又被用于认知多样性。在
cognitive_diversity = temp(score1, score2)
但这也大大减慢了代码的速度 如果任何人有任何关于加速的建议,或者任何关于如何正确地重写循环以加速它的建议,那将是惊人的!在
编辑 谢谢你的帮助。我用它想出了一个稍微不同的解决方案。在
#Std jit optimization
@jit()
def cd_matrix_jit(oms,l_oms,l_oms2,cd_mat2):
for ind1 in range(l_oms):
for ind2 in range(l_oms):
d=0.0
for i in range(l_oms2):
d = d + (oms[ind1,i]-oms[ind2,i])**2
cd_mat2[ind1,ind2] = d**(1/2)
return cd_mat2
首先是风格上的一些改进:
^{pr2}$len(X)
是9,X.shape[0]
。所以这个表达式最好写成例如,一个9x9的0数组(float默认的数据类型)。在
可以写成
^{4}$在
您试图通过使用上(下)三角形来避免重复计算。对于
numpy
,这可能不值得。如果可以用一个表达式而不是循环来执行整个计算,那么即使某些值是重复的,也会更快。在比如:
一个样本,
X
,最好小于(9480,1),这样我们就可以在备选方案中重复您的计算。在相关问题 更多 >
编程相关推荐