python - How to efficiently compute function for every cell in numpy array? -
i guess iterating on numpy array not efficient way, , can see program slow have bit larger dataset.
1) go way iterate on matrix , apply function each cell?
this part of code:
# states , data 2 lists few appended items ~100 rows = len(self.states) cols = len(self.data) self.trellis = np.zeros((rows, cols)) i, state in enumerate(self.states): j, vector in enumerate(self.data): self.trellis[i][j] = mvnun_wrapper(vector, state.mu, state.sigma, vector_length)
it seems classic numpy problem. states
sound list of state
2 attributes, mu
, sigma
.
i don't think vector_length
requisite here, , suppose mvnun
function of 3 scalars.
then try:
mu = [state.mu state in states] sigma = [state.sigma state in states] v=np.asarray(vector).reshape(-1,1) # "column" vector result = mvnun(v,mu,sigma)
as example :
class state(): def __init__(self): self.mu=np.random.random() self.sigma=np.random.random() states=[state() _ in range(10)] # 10 states vector=list(range(5)) # 5-vector def mvnun(x,m,s) : return x*m+3*x*s # scalar function mu=[state.mu state in states] sigma = [state.sigma state in states] v=np.asarray(vector).reshape(-1,1) # "column" vector result = mvnun(v,mu,sigma)
result.shape
is (5,10)
.
Comments
Post a Comment