多维度 Numpy 数组
除了Owen和Prashant Kumar的回答,这里提供一个使用多维 Numpy 数组(又称为 shape)的版本,可以加速 Numpy 解决方案的代码。如果您需要经常访问 (finalize()
) 数据,这将非常有帮助。
版本 |
Prashant Kumar |
行长度=1 |
行长度=5 |
A类 - np.append |
2.873 秒 |
2.776 秒 |
0.682 秒 |
B类 - python列表 |
6.693 秒 |
80.868 秒 |
22.012 秒 |
C类 - 数组列表 |
0.095 秒 |
0.180 秒 |
0.043 秒 |
列Prashant Kumar
是他在我的机器上执行的示例,以进行比较。使用row_length=5
是最初问题的示例。由于{built-in method numpy.array}
,Python列表的显着增加意味着numpy需要更多时间将多维列表转换为数组,以便与具有相同数量条目的1D列表重塑。例如:np.array([[1,2,3]*5])
与np.array([1]*15).reshape((-1,3))
。
以下是代码:
import cProfile
import numpy as np
class A:
def __init__(self,shape=(0,), dtype=float):
"""First item of shape is ingnored, the rest defines the shape"""
self.data = np.array([], dtype=dtype).reshape((0,*shape[1:]))
def update(self, row):
self.data = np.append(self.data, row)
def finalize(self):
return self.data
class B:
def __init__(self, shape=(0,), dtype=float):
"""First item of shape is ingnored, the rest defines the shape"""
self.shape = shape
self.dtype = dtype
self.data = []
def update(self, row):
self.data.append(row)
def finalize(self):
return np.array(self.data, dtype=self.dtype).reshape((-1, *self.shape[1:]))
class C:
def __init__(self, shape=(0,), dtype=float):
"""First item of shape is ingnored, the rest defines the shape"""
self.shape = shape
self.data = np.zeros((100,*shape[1:]),dtype=dtype)
self.capacity = 100
self.size = 0
def update(self, x):
if self.size == self.capacity:
self.capacity *= 4
newdata = np.zeros((self.capacity,*self.data.shape[1:]))
newdata[:self.size] = self.data
self.data = newdata
self.data[self.size] = x
self.size += 1
def finalize(self):
return self.data[:self.size]
def test_class(f):
row_length = 5
x = f(shape=(0,row_length))
for i in range(int(100000/row_length)):
x.update([i]*row_length)
for i in range(1000):
x.finalize()
for x in 'ABC':
cProfile.run('test_class(%s)' % x)
还有一种选项可以添加到上面Luca Fiaschi的帖子中。
b=[]
for i in range(nruns):
s=time.time()
c1=np.array(a, dtype=int).reshape((N,1000))
b.append((time.time()-s))
print("Timing version array.reshape ",np.mean(b))
对于我来说,计时结果为:
Timing version vstack 0.6863266944885253
Timing version reshape 0.505419111251831
Timing version array.reshape 0.5052066326141358
Timing version concatenate 0.5339600563049316