[英]How to efficiently compute function for every cell in numpy array?
I guess that iterating over an numpy array is not the most efficient way, and I can see that my program is really slow now that I have a bit larger dataset. 我猜想对numpy数组进行迭代并不是最有效的方法,而且由于数据集更大,我可以看到我的程序真的很慢。
1) What is the go to way to iterate over a matrix and apply a function to each cell? 1)在矩阵上迭代并将函数应用于每个单元格的方法是什么?
This is part of the code: 这是代码的一部分:
# States and data are two lists with a few appended items ~100
rows = len(self.states)
cols = len(self.data)
self.trellis = np.zeros((rows, cols))
for i, state in enumerate(self.states):
for j, vector in enumerate(self.data):
self.trellis[i][j] = mvnun_wrapper(vector, state.mu, state.sigma, vector_length)
it seems to be a classic numpy problem. 这似乎是一个经典的numpy问题。 states
sound like a list of state
with 2 attributes, mu
and sigma
. states
听起来像是具有2个属性mu
和sigma
的state
列表。
I don't think vector_length
is requisite here, and suppose mvnun
a function of three scalars. 我认为这里的vector_length
不是必需的,并且假定mvnun
是三个标量的函数。
then just try: 然后尝试:
mu = [state.mu for state in states]
sigma = [state.sigma for state in states]
v=np.asarray(vector).reshape(-1,1) # a "column" vector
result = mvnun(v,mu,sigma)
As an example : 举个例子 :
class state():
def __init__(self):
self.mu=np.random.random()
self.sigma=np.random.random()
states=[state() for _ in range(10)] # 10 states
vector=list(range(5)) # a 5-vector
def mvnun(x,m,s) : return x*m+3*x*s # a scalar function
mu=[state.mu for state in states]
sigma = [state.sigma for state in states]
v=np.asarray(vector).reshape(-1,1) # a "column" vector
result = mvnun(v,mu,sigma)
result.shape
is (5,10)
. result.shape
是(5,10)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.