循环矩阵运算的循环优化

时间:2018-10-11 12:27:30

标签: python performance loops matrix optimization

我有一个向量X_k和一个矩阵Y_ {k,j},其中k =(k,...,K)和j =(1,.. J)。它们是圆形的,这表示

X_{k+K} = X_k, Y_{k+K,j} = Y_{k,j} and Y_{k,j+J} = Y_{k,j} 

我想根据以下表达式计算Zx向量和Zy矩阵:

Zx = -X_{k-1}*(X_{K-2}-X_{K+1})-X_k

Zy = -Y_{k,j+1}*(Y_{k,j+2}-Y_{k,j-1})-Y_{k,j}+X_k

目前,我是通过循环执行此操作的,首先我计算边缘情况(对于X:k = 1、2,K。对于Y:j = 1,J,J-1)。对于其他人,我使用公式。

我想知道这种微积分是否可以向量化。这是示例代码。

import numpy as np

np.random.seed(10)
K = 20
J = 10

# initial state (equilibrium)
x = np.random.uniform(size=K) 
y = np.random.uniform(size=(K*J)) 
y = y.reshape(K,J)

# zy
zy = np.zeros((K*J))
zy = zy.reshape(K,J)

# Edge case of Y
for k in range(K):
    zy[k,0] = -y[k,1]*(y[k,2]-y[k,J-1])-y[k,0]+ x[k]
    zy[k,J-1] = -y[k,0]*(y[k,1]-y[k,J-2])-y[k,J-1]+ x[k]
    zy[k,J-2] = -y[k,J-1]*(y[k,0]-y[k,J-3])-y[k,J-2]+ x[k]

    # General Case of Y
    for j in range(1,J-2):
        zy[k,j] = -y[k,j+1]*(y[k,j+2]-y[k,j-1])-y[k,j]+ x[k]

# zx
zx = np.zeros(K)

# first the 3 edge cases: k = 1, 2, K
zx[0] = -x[K-1]*(-x[1] + x[K-2])  - x[0]
zx[1] = - x[0]*(-x[2] + x[K-1])- x[1] 
zx[K-1] = -x[K-2]*(-x[0] + x[K-3]) - x[K-1]

# then the general case for X
for k in range(2, K-1)
    zx[k] = -x[k-1]*(-x[k+1] + x[k-2]) - x[k]

print(zx)
print(zy)

我怀疑可以通过矩阵运算进行优化,但是不确定是否可以不使用循环(至少对于边缘情况)。

1 个答案:

答案 0 :(得分:0)

Code Review,我得到了正确的答案。向量化这种操作的方式是通过np.roll()

例如,Y变量为:

zy = np.roll(y,-1,axis=1)*(np.roll(y,-2,axis=1)-np.roll(y,1,axis=1))- y +x[:,None]