我从我的主管那里得到了一个代码来实现MDCT多相分析和综合。不幸的是,这段代码包含一个非常慢的函数,有两个循环。如果有人能帮助我简化这个功能,使它更快,我将感谢你的帮助。这是代码的一部分:
def polmatmult(A, B):
"""polmatmult(A,B)
multiplies two polynomial matrices (arrays) A and B, where each matrix entry is a polynomial.
Those polynomial entries are in the 3rd dimension
The third dimension can also be interpreted as containing the (2D) coefficient matrices of exponent of z^-1.
Result is C=A*B;"""
print("np.shape(A)", np.shape(A))
print("np.shape(B)", np.shape(B))
[NAx, NAy, NAz] = np.shape(A);
[NBx, NBy, NBz] = np.shape(B);
"Degree +1 of resulting polynomial, with NAz-1 and NBz-1 being the degree of the input polynomials:"
Deg = NAz + NBz - 1;
print("Deg", Deg)
C = np.zeros((NAx, NBy, Deg));
"Convolution of matrices:"
for n in range(0, (Deg)):
for m in range(0, n + 1):
if ((n - m) < NAz and m < NBz):
C[:, :, n] = C[:, :, n] + np.dot(A[:, :, (n - m)], B[:, :, m]);
return C
首先我很惊讶美国运输部那里没有np.乘法. 卷积已经在for循环中发生了,它应该被广播到前两个维度,对吗?不管怎样,我会和np.乘法而不是美国运输部如果我错了,你可以把它改回来。在
如果这个函数是一个真正的瓶颈,我将使用Cython来提高速度。以下是代码示例:
在myconvolve.pyx公司在
这必须被编译,我用它
^{pr2}$然后用下面的比较脚本
我得到:
编辑:我现在意识到
poly1d
比原来的解决方案效率要低得多,主要是因为poly1d
是用Python而不是C实现的不过,我会坚持,至少要更容易些。在
如果您使用
^{pr2}$poly1d
类型,这将非常容易:一个小的操作,使点积变得更简单,
ufuc_at
操作可以删除for
循环:一般来说,您希望您的索引轴(},并进行广播。因此所有的
z
)是第一个维度,而不是最后一个维度。这允许您使用ufunc
技巧(如add.at
)、@
而不是{np.moveaxis
。在相关问题 更多 >
编程相关推荐