numpy的就地操作(例如,"+ =")如何工作? [英] How do numpy's in-place operations (e.g. `+=`) work?

查看:92
本文介绍了numpy的就地操作(例如,"+ =")如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本问题是:a[i] += b在执行引擎盖时会发生什么?

给出以下内容:

import numpy as np
a = np.arange(4)
i = a > 0
i
= array([False,  True,  True,  True], dtype=bool)

我了解:

  • a[i] = xa.__setitem__(i, x)相同,后者直接分配给i
  • 指示的项目
  • a += xa.__iadd__(x)相同,就地进行加法

但是当我这样做时会发生什么:

a[i] += x

特别是:

  1. a[i] = a[i] + x相同吗? (这不是就地操作)
  2. 如果i是,在这种情况下是否有所不同:
    • int索引,或
    • ndarray,或
    • 一个slice对象


背景

我开始研究此问题的原因是在处理重复索引时遇到了非直觉的行为:

a = np.zeros(4)
x = np.arange(4)
indices = np.zeros(4,dtype=np.int)  # duplicate indices
a[indices] += x
a
= array([ 3.,  0.,  0.,  0.])

关于此问题

的更有趣的东西a>.

您需要意识到的第一件事是a += x并不完全映射到a.__iadd__(x),而是映射到a = a.__iadd__(x).请注意,文档专门说就地运算符返回其结果,但这并没有不必是self(尽管实际上通常是).这意味着a[i] += x琐碎地映射到:

a.__setitem__(i, a.__getitem__(i).__iadd__(x))

因此,技术上的添加是就地发生的,但仅在临时对象上发生.但是,创建的临时对象仍然可能比调用__add__的对象少.

The basic question is: What happens under the hood when doing: a[i] += b?

Given the following:

import numpy as np
a = np.arange(4)
i = a > 0
i
= array([False,  True,  True,  True], dtype=bool)

I understand that:

  • a[i] = x is the same as a.__setitem__(i, x), which assigns directly to the items indicated by i
  • a += x is the same as a.__iadd__(x), which does the addition in place

But what happens when I do:

a[i] += x

Specifically:

  1. Is this the same as a[i] = a[i] + x? (which is not an in-place operation)
  2. Does it make a difference in this case if i is:
    • an int index, or
    • an ndarray, or
    • a slice object


Background

The reason I started delving into this is that I encountered a non-intuitive behavior when working with duplicate indices:

a = np.zeros(4)
x = np.arange(4)
indices = np.zeros(4,dtype=np.int)  # duplicate indices
a[indices] += x
a
= array([ 3.,  0.,  0.,  0.])

More interesting stuff about duplicate indices in this question.

解决方案

The first thing you need to realise is that a += x doesn't map exactly to a.__iadd__(x), instead it maps to a = a.__iadd__(x). Notice that the documentation specifically says that in-place operators return their result, and this doesn't have to be self (although in practice, it usually is). This means a[i] += x trivially maps to:

a.__setitem__(i, a.__getitem__(i).__iadd__(x))

So, the addition technically happens in-place, but only on a temporary object. There is still potentially one less temporary object created than if it called __add__, though.

这篇关于numpy的就地操作(例如,"+ =")如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆