What’s the most pythonic way to iterate 2 arrays correspondingly when using numpy?
Question:
Assume we need to compute the value of the function with numpy
:
I know two methods:
METHOD I:
def func(b,X,Y):
res = 0
for i in range(len(X)):
res += np.log(X[i] + b * Y[i])
return res
METHOD II:
def func(b,X,Y):
return np.sum(np.array([np.log(X[i) + b*Y[i]) for i in range(len(X))]))
Are both methods (1)pythonic (2) readable (3) efficient in running time? Is there any better implementation evaluated by these three metrics?
Answers:
The second method works great
Because you have implemented the vectorized form such that the number of operations become very less compared to the method 1
You don’t need to iterate through X
and Y
, numpy
can broadcast the operations natively:
np.log(np.array(X) + b * np.array(Y)).sum()
If X
and Y
are already np.array
s:
np.log(X + b * Y).sum()
Assume we need to compute the value of the function with numpy
:
I know two methods:
METHOD I:
def func(b,X,Y):
res = 0
for i in range(len(X)):
res += np.log(X[i] + b * Y[i])
return res
METHOD II:
def func(b,X,Y):
return np.sum(np.array([np.log(X[i) + b*Y[i]) for i in range(len(X))]))
Are both methods (1)pythonic (2) readable (3) efficient in running time? Is there any better implementation evaluated by these three metrics?
The second method works great
Because you have implemented the vectorized form such that the number of operations become very less compared to the method 1
You don’t need to iterate through X
and Y
, numpy
can broadcast the operations natively:
np.log(np.array(X) + b * np.array(Y)).sum()
If X
and Y
are already np.array
s:
np.log(X + b * Y).sum()