对于在 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/