Kann ich numpy verwenden, um diese Schleife zu beschleunigen?
Guten Abend,
Ich versuche, die Schleife in diesem Code zu beschleunigen. Ich habe die numpy docs durchgelesen, aber ohne Erfolg. np.accumulate sieht so aus, als ob es fast das ist, was ich brauche, aber nicht ganz.
Was könnte ich tun, um die Schleife zu beschleunigen?
import numpy as np
N = 1000
AR_part = np.random.randn(N+1)
s2 = np.ndarray(N+1)
s2[0] = 1.0
beta = 1.3
old_s2 = s2[0]
for t in range( 1, N+1 ):
s2_t = AR_part[ t-1 ] + beta * old_s2
s2[t] = s2_t
old_s2 = s2_t
Als Antwort auf Warren habe ich meinen Code aktualisiert:
importiere numpy als np aus scipy.signal importiere lfilter, lfiltic
N = 1000
AR_part = np.random.randn(N+1)
beta = 1.3
def method1( AR_part):
s2 = np.empty_like(AR_part)
s2[0] = 1.0
old_s2 = s2[0]
for t in range( 1, N+1 ):
s2_t = AR_part[ t-1 ] + beta * old_s2
s2[t] = s2_t
old_s2 = s2_t
return s2
def method2( AR_part):
y = np.empty_like(AR_part)
b = np.array([0, 1])
a = np.array([1, -beta])
# Initial condition for the linear filter.
zi = lfiltic(b, a, [1.0], AR_part[:1])
y[:1] = 1.0
y[1:], zo = lfilter(b, a, AR_part[1:], zi=zi)
return y
s2 = method1( AR_part )
y = method2( AR_part )
np.alltrue( s2==y )
Timing des Codes:
%timeit method1( AR_part )
100 loops, best of 3: 1.63 ms per loop
%timeit method2( AR_part )
10000 loops, best of 3: 129 us per loop
Das zeigt, dass Warrens Methode über 10-mal schneller ist! Sehr beeindruckend!