python - 避免创建新数组作为 numpy/scipy 操作的结果?

标签 python numpy memory-management optimization scipy

对于在 numpy/scipy 中重复操作,有很多开销,因为大多数操作返回一个新对象。

例如

for i in range(100):
   x = A*x

我想通过传递对操作的引用来避免这种情况,就像在 C 中一样

for i in range(100):
   np.dot(A,x,x_new) #x_new would now store the result of the multiplication
   x,x_new = x_new,x

有什么办法吗?我希望这不仅仅是乘法运算,而是所有返回矩阵或向量的操作。

最佳答案

参见 Learning to avoid unnecessary array copies在 IPython 书籍中。从那里,注意例如这些准则:

a *= b

不会生成副本,而:

a = a * b

制作一份副本。此外,flatten() 将复制,而 ravel() 仅在必要时进行复制,否则返回 View (因此通常应该是首选)。 reshape() 也不生成副本,而是返回一个 View 。

此外,正如@hpaulj 和@ali_m 在他们的评论中指出的那样,许多 numpy 函数都支持 out 参数,因此请查看文档。来自 numpy.dot() docs :

out : ndarray, optional Output argument.

This must have the exact kind that would be returned if it was not used. In particular, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for dot(a,b). This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible.

关于python - 避免创建新数组作为 numpy/scipy 操作的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29872914/

相关文章:

c - 为什么在添加初始化静态变量时 .bss 大小会减小?

c++ - 是否需要 "nested"释放 std::vector<pair<vector<int>,int>> 中的保留内存以手动释放它?

python - "cv2.imshow ()"函数有问题

python - tf.transpose 如何在 tensorflow 中工作?

c - malloc 一次,然后在结构数组上分配内存

python - 如何在使用 python SimpleHTTPServer 时更改默认 404 页面

python - 应该如何使用 Alembic 删除 SQLAlchemy-Searchable 触发器

javascript - AJAX 发布后 django 模板未重新加载

python - 内存分析器在所有步骤中提供恒定的内存

python - 值错误: unknown type object pandas eval for n rows => 100