布尔值作为索引的 Python 效果 (a[a==0] = 1)

Dub*_*box 1 python arrays indexing numpy boolean-indexing

我目前正在实现我在 github 上看到的一些代码。

( https://gist.github.com/karpathy/a4166c7fe253700972fcbc77e4ea32c5 )

这里的兴趣点如下:

def prepro(I):
   """ prepro 210x160x3 uint8 frame into 6400 (80x80) 1D 
   float vector """
   I = I[35:195] # crop
   I = I[::2,::2,0] # downsample by factor of 2
   I[I == 144] = 0 # erase background (background type 1)
   I[I == 109] = 0 # erase background (background type 2)
   I[I != 0] = 1 # everything else (paddles, ball) just set to 1
   return I.astype(np.float).ravel()
Run Code Online (Sandbox Code Playgroud)

作者在这里预处理图像以训练神经网络。我感到困惑的部分是:

I[I == 144] = 0 # erase background (background type 1)
I[I == 109] = 0 # erase background (background type 2)
I[I != 0] = 1 # everything else (paddles, ball) just set
Run Code Online (Sandbox Code Playgroud)

我认为作者想将列表中所有值为 144(109,而不是 0)的元素设置为特定值。但如果我是对的,一个布尔值在 python 中只代表 0 或 1。因此,将列表与整数进行比较将始终导致 False,因此为 0。

这使得I[I==x] <=> I[0] : x is integer为什么还要费心去做呢?

我在这里缺少什么?

glg*_*lgl 5

NumPy 数组有点不同;它们的使用类似于 MATLAB 中的使用。

I == 144产生具有相同的尺寸的逻辑阵列I,其中它们的所有位置144Itrue,所有其他false

(其他表达式也是如此。)

使用这样的逻辑数组进行索引意味着索引所在的所有位置都true将受到赋值的影响。