如何从生成器对象中构建numpy数组?
让我来说明一下这个问题:
>>> import numpy
>>> def gimme():
... for x in xrange(10):
... yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numpy.array(xrange(10))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> numpy.array(gimme())
array(<generator object at 0x28a1758>, dtype=object)
>>> numpy.array(list(gimme()))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Run Code Online (Sandbox Code Playgroud)
在这个例子中,gimme()是我想要变成数组的输出的生成器.但是,数组构造函数不会迭代生成器,它只是存储生成器本身.我想要的行为来自numpy.array(list(gimme())),但我不想支付同时在内存中使用中间列表和最终数组的内存开销.有更节省空间的方式吗?
在Python和Matlab中,我编写了生成矩阵的代码,并使用索引函数填充它.Python代码的执行时间大约是Matlab代码执行时间的20倍.具有相同结果的两个函数是用python编写的,bWay()基于这个答案
这是完整的Python代码:
import numpy as np
from timeit import timeit
height = 1080
width = 1920
heightCm = 30
distanceCm = 70
centerY = height / 2 - 0.5;
centerX = width / 2 - 0.5;
constPart = height * heightCm / distanceCm
def aWay():
M = np.empty([height, width], dtype=np.float64);
for y in xrange(height):
for x in xrange(width):
M[y, x] = np.arctan(pow((pow((centerX - x), 2) + pow((centerY - y), 2)), 0.5) / constPart)
def bWay():
M = …Run Code Online (Sandbox Code Playgroud)