矢量值函数
我有以下功能:
def h_Y1(X, theta):
EF = X[0]
FF = X[1]
j = X[-2]
k = X[-1]
W = X[2:-2]
Sigma = theta[0]
sigma_xi2 = theta[1]
gamma_alpha = theta[2]
gamma_z = np.array(theta[3:])
gW = gamma_z @ W
eps1 = EF - gamma_alpha * gW
if j == k:
eps2 = FF - (gamma_alpha**2)*gW - gW*sigma_xi2 - Sigma
eps3 = 0
else:
eps2 = 0
eps3 = FF - (gamma_alpha**2)*gW
h1 = [eps1 * Wk for Wk in W]
h2 = [eps2 * Wk for Wk in W]
h3 = [eps3 * Wk for Wk in W]
return np.concatenate([h1, h2, h3])
我需要为一系列值执行函数,这些范围存储在gmmarray
中。具体来说,我希望为gmmarray
的每一行作为函数参数x
,用于固定theta
。
我目前使用以下代码这样做:
import numpy as np
theta = [0.01, 1, 1, 0, 0]
gmmarray = np.random.random((1120451, 6))
test = np.apply_along_axis(h_Y1, 1, gmmarray, theta = init)
但是,这很慢 - 大约需要19秒。我尝试将函数矢量化如下:
Vh_Y1 = np.vectorize(h_Y1, signature = '(n),(j)->(i)')
test1 = Vh_Y1(gmmarray, init)
但是,这仍然需要16秒。我在这里做错了什么,还是有办法进一步加快速度?
非常感谢!
I have the following function:
def h_Y1(X, theta):
EF = X[0]
FF = X[1]
j = X[-2]
k = X[-1]
W = X[2:-2]
Sigma = theta[0]
sigma_xi2 = theta[1]
gamma_alpha = theta[2]
gamma_z = np.array(theta[3:])
gW = gamma_z @ W
eps1 = EF - gamma_alpha * gW
if j == k:
eps2 = FF - (gamma_alpha**2)*gW - gW*sigma_xi2 - Sigma
eps3 = 0
else:
eps2 = 0
eps3 = FF - (gamma_alpha**2)*gW
h1 = [eps1 * Wk for Wk in W]
h2 = [eps2 * Wk for Wk in W]
h3 = [eps3 * Wk for Wk in W]
return np.concatenate([h1, h2, h3])
I need to execute the function for a range of values, which are stored in gmmarray
. Specifically, I'd like the function to be run for each row of gmmarray
as the function argument X
, for a fixed theta
.
I'm currently doing this using the following code:
import numpy as np
theta = [0.01, 1, 1, 0, 0]
gmmarray = np.random.random((1120451, 6))
test = np.apply_along_axis(h_Y1, 1, gmmarray, theta = init)
However, this is slow - it takes around 19 seconds. I tried vectorizing the function as follows:
Vh_Y1 = np.vectorize(h_Y1, signature = '(n),(j)->(i)')
test1 = Vh_Y1(gmmarray, init)
However, this still takes 16 seconds. Am I doing something wrong here or is there a way to speed things up further?
Thanks so much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将完整的
gmmarray
作为x
参数传递。然后,您可以在其列上使用矢量化操作,而不是通过gmmarray的每一行循环。
这样的事情:
调用
大约提高100倍的速度会产生相同的结果。
You can pass the full
gmmarray
as theX
parameter. Then, instead of looping through each row ofgmmarray
, you can use vectorized operations on its columns.Something like this:
Calling
produces the same result with roughly a 100x speed increase.