不同大小的矩阵乘法的Pythonic方式

问题描述 投票:0回答:1

我有一个 1800 x 1800 矩阵 (Rho) 和循环来计算如下参数:

for k in range(10):
    R = (-1)**k * binom(n-k, k) * binom(n - 2*k, (n-m)//2 - k) * np.power(Rho, (n - 2*k))

但是这个循环确实很耗时。所以,我想知道我是否可以像这样用矩阵方式写它:

R_array = np.zeros(10)
k = np.arange(int((n-m)/2 + 1))
R_array = (-1)**k * binom(n-k, k) * binom(n - 2*k, (n-m)//2 - k) * np.power(Rho, (n - 2*k))

,消除

for
循环。但由于它包含矩阵
Rho
,最后一部分,即
np.power(Rho, (n - 2*k))
会出错!

那么,有人有办法解决这个问题吗?

我尝试了不同类型的矩阵书写,但没有一个起作用!

python numpy performance matrix optimization
1个回答
0
投票

我不确定是否可以消除 for 循环的需要,但也许你可以尝试矢量化?

# Vectorize parts of your calculations that don't involve powers of Rho
k = np.arange(max(int((n-m)/2 + 1), 10))  
multipliers = (-1)**k * binom(n-k, k) * binom(n - 2*k, (n-m)//2 - k)

# Initialize an array to store the results
R_results = np.zeros((10, 1800, 1800))

# Loop over the elements in 'multipliers', but apply each to the whole matrix
for i, multiplier in enumerate(multipliers):
    if i >= 10:  # Assuming you want to stop at 10 like in your original loop
        break
    R_results[i] = multiplier * np.power(Rho, (n - 2*k[i]))

# If you need a cumulative result, you can sum over the first axis:
R_final = np.sum(R_results, axis=0)

我认为一般来说,大型矩阵的计算非常耗时。

© www.soinside.com 2019 - 2024. All rights reserved.