文章目录
索引
在 TensorFlow 中,支持基本的[𝑖][𝑗] …标准索引方式,也支持通过逗号分隔索引号的索引方式。考虑输入X 为4 张32x32 大小的彩色图片,shape 为[4,32,32,3],首先创建张量:
x = tf.random.normal([4,32,32,3])
接下来我们使用索引方式读取张量的部分数据。
❑ 取第 1 张图片的数据:
In [51]: x[0]
Out[51]:<tf.Tensor: id=379, shape=(32, 32, 3), dtype=float32, numpy=
array([[[ 1.3005302 , 1.5301839 , -0.32005513],
[-1.3020388 , 1.7837263 , -1.0747638 ], ...
[-1.1092019 , -1.045254 , -0.4980363 ],
[-0.9099222 , 0.3947732 , -0.10433522]]], dtype=float32)>
❑ 取第 1 张图片的第2 行:
In [52]: x[0][1]
Out[52]:
<tf.Tensor: id=388, shape=(32, 3), dtype=float32, numpy=
array([[ 4.2904025e-01, 1.0574218e+00, 3.1540772e-01],
[ 1.5800388e+00, -8.1637271e-02, 6.3147342e-01], ...,
[ 2.8893018e-01, 5.8003378e-01, -1.1444757e+00],
[ 9.6100050e-01, -1.0985689e+00, 1.0827581e+00]], dtype=float32)>
❑ 取第 1 张图片,第2 行,第3 列的像素:
In [53]: x[0][1][2]
Out[53]:
<tf.Tensor: id=401, shape=(3,), dtype=float32, numpy=array([-0.55954427,
0.14497331, 0.46424514], dtype=float32)>
❑ 取第 3 张图片,第2 行,第1 列的像素,B 通道(第2 个通道)颜色强度值:
In [54]: x[2][1][0][1]
Out[54]:
<tf.Tensor: id=418, shape=(), dtype=float32, numpy=-0.84922135>
当张量的维度数较高时,使用[𝑖][𝑗]. . . [𝑘]的方式书写不方便,可以采用[𝑖, 𝑗, … , 𝑘]的方式索引,它们是等价的。

最低0.47元/天 解锁文章
1684

被折叠的 条评论
为什么被折叠?



