【发布时间】:2021-11-22 09:18:52
【问题描述】:
我一直在尝试优化 numpy 中的循环。现在循环在 26 秒内运行。我想知道是否可以减少这个时间。
import numpy as np
from scipy import interpolate
import numpy.matlib as matlib
I=10000
T=10000
ct = np.zeros((I,T))
x = matlib.repmat(np.linspace(0,25,I).reshape(I,1),1,T)
y = np.random.uniform(0, 10, (I,T))
x1 = matlib.repmat(np.linspace(2,20,I).reshape(I,1),1,T)
tck0 = interpolate.splrep(x[:,0], y[:,0], s=0)
tck1 = interpolate.splrep(x[:,1], y[:,1], s=0)
for t in range(T):
ct[:,t] = (y[:,t]<=5)*interpolate.splev(x1[:,t], tck0, der=0, ext=0) + \
(y[:,t]>5)*interpolate.splev(x1[:,t], tck1, der=0, ext=0)
【问题讨论】:
-
您的代码不清楚。如果您只使用第一个列,那么 X 有 T 列有什么意义? y[:,t]5 的意义何在?对于这两种情况,您分配的值相同吗?否则你可以简单地说 ct=interpolate.splev(x1, tck0, der=0, ext=0) 在我的电脑上花了大约 10 秒。
-
你是对的。我修复了代码。
-
interpolate.splev可以与 2dx1一起使用,可以是全部还是子集?提高速度的最佳方法是将 10000 次调用interpolate.splev替换为一个或几个。我不知道这是否可能。
标签: python numpy optimization time scipy