我一直试图将以下代码的循环向量化。 (编辑征求意见)
M, N, F = 10, 50, 30
ts = np.linspace(0.001,3,M)
v = np.random.rand(N,1)
A = np.random.rand(N,N)
D = np.zeros(shape=(N,N,M))
for i, t in enumerate(ts):
for x in range(0,N):
for y in range(x,N):
D[x,y,i] = np.sum( np.exp(-t * v[0:F]) * A[x,0:F] * A[y,0:F] )
D[y,x,i] = D[x,y,i]
我一直在阅读其他问题,但无法在此处弄清楚如何应用它。
建议?
答案 0 :(得分:1)
以下是使用broadcasting
和matrix-multiplication
与np.dot
的组合的矢量化方法 -
# Get r,c indices corresponding to indices along dim-0,1 for o/p
r,c = np.triu_indices(N)
vals = (A[r,:F] * A[c,:F]).dot(np.exp(v[:nf,None]*(-ts)))
# Initialize o/p array and assign values
out = np.empty(shape=(N,N,M))
out[r,c,:] = vals
out[c,r,:] = vals