gpt4 book ai didi

python - 增长 numpy 数值数组的最快方法

转载 作者:IT老高 更新时间:2023-10-28 21:43:39 28 4
gpt4 key购买 nike

要求:

  • 我需要从数据中增加一个任意大的数组。
  • 我可以猜测大小(大约 100-200),但不能保证每次都适合数组
  • 一旦它增长到最终大小,我需要对其执行数值计算,因此我希望最终得到一个二维 numpy 数组。
  • 速度至关重要。例如,对于 300 个文件中的一个,update() 方法被调用 4500 万次(大约需要 150s 左右),而 finalize() 方法被调用 500k 次(总共需要 106s)......总共需要 250s左右。

这是我的代码:

def __init__(self):
self.data = []

def update(self, row):
self.data.append(row)

def finalize(self):
dx = np.array(self.data)

我尝试过的其他内容包括以下代码……但这要慢得多。

def class A:
def __init__(self):
self.data = np.array([])

def update(self, row):
np.append(self.data, row)

def finalize(self):
dx = np.reshape(self.data, size=(self.data.shape[0]/5, 5))

这是如何调用的示意图:

for i in range(500000):
ax = A()
for j in range(200):
ax.update([1,2,3,4,5])
ax.finalize()
# some processing on ax

最佳答案

我尝试了一些不同的事情,有时间安排。

import numpy as np
  1. 你提到的慢的方法:(32.094秒)

    class A:

    def __init__(self):
    self.data = np.array([])

    def update(self, row):
    self.data = np.append(self.data, row)

    def finalize(self):
    return np.reshape(self.data, newshape=(self.data.shape[0]/5, 5))
  2. 常规ol Python列表:(0.308秒)

    class B:

    def __init__(self):
    self.data = []

    def update(self, row):
    for r in row:
    self.data.append(r)

    def finalize(self):
    return np.reshape(self.data, newshape=(len(self.data)/5, 5))
  3. 尝试在 numpy 中实现一个数组列表:(0.362 秒)

    class C:

    def __init__(self):
    self.data = np.zeros((100,))
    self.capacity = 100
    self.size = 0

    def update(self, row):
    for r in row:
    self.add(r)

    def add(self, x):
    if self.size == self.capacity:
    self.capacity *= 4
    newdata = np.zeros((self.capacity,))
    newdata[:self.size] = self.data
    self.data = newdata

    self.data[self.size] = x
    self.size += 1

    def finalize(self):
    data = self.data[:self.size]
    return np.reshape(data, newshape=(len(data)/5, 5))

这就是我的计时方式:

x = C()
for i in xrange(100000):
x.update([i])

所以看起来普通的旧 Python 列表相当不错;)

关于python - 增长 numpy 数值数组的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7133885/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com