I have a generator that returns numpy arrays. For example sake, let it be:
import numpy as np
a = np.arange(9).reshape(3,3)
gen = (x for x in a)
Calling:
np.sum(gen)
On numpy 1.17.4:
DeprecationWarning: Calling np.sum(generator) is deprecated, and in the future will give a different result. Use np.sum(np.fromiter(generator)) or the python sum builtin instead.
Trying to refactor the above:
np.sum(np.fromiter(gen, dtype=np.ndarray))
I get:
ValueError: cannot create object arrays from iterator
What is wrong in the above statement?
The problem is the second argument, np.ndarray in the fromiter(). Numpy fromiter expected a 1D and returns a 1D array:
Create a new 1-dimensional array from an iterable object.
Therefore, you cannot create object arrays from iterator. Furthermore the .reshape() will also raise an error, because of what I stated in the first line. All in all, this works:
import numpy as np
a = np.arange(9)
gen = (x for x in a)
print(np.sum(np.fromiter(gen,float)))
Output:
36
Since you're summing instances of arrays you can just use the built-in sum:
result = sum(gen)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With