python - 布尔值作为索引的 Python 效果 (a[a==0] = 1)
问题描述
我目前正在实现一些我在 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
为什么还要费心去做呢?
我在这里想念什么?
解决方案
NumPy 数组有点不同;它们的使用类似于 MATLAB 中的使用。
I == 144
生成一个与 具有相同维度的逻辑数组I
,其中所有位置都是144
,所有其他位置。I
true
false
(其他表达式也一样。)
使用这样的逻辑数组进行索引意味着索引所在的所有位置都true
将受到赋值的影响。
推荐阅读
- php - 如何在循环内实例化类(从数组)
- windows - 如何检查目录符号链接的目标是否存在?
- php - 通过将记录存储到数组中并使用 for 循环比较数字集来从表中获取缺失的 ID
- python - 如何将列表粘贴到多索引数据框中?
- ios - 防止自动布局拉伸自定义视图
- laravel - Laravel 处理仅由控制器抛出的错误
- node.js - 什么需要('..'); 在 Node.js 中
- node.js - 如何在heroku上的node.js中远程保留spotify刷新令牌
- python - Google.Ads.GoogleAds.Examples 返回 Deadline Exceeded
- javascript - 如何将 HTML 插入 getDocumentByID.innerHTML 函数