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

2024-04-25 17:06:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在实现一些在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()

为了训练神经网络,作者对图像进行了预处理。我困惑的是:

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

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

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

我错过了什么?你知道吗


Tags: 代码github列表type作者floatelsejust
1条回答
网友
1楼 · 发布于 2024-04-25 17:06:26

NumPy数组有点不同;它们的用法类似于MATLAB中的用法。你知道吗

I == 144生成与I具有相同维度的逻辑数组,其中I中的144所有位置都是true,其他所有位置都是false。你知道吗

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

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

相关问题 更多 >