TensorFlow2-Tensor 索引和切片

索引

numpy [ ] 索引

import tensorflow as tf
a = tf.ones([1, 5, 5, 3])
a.shape
TensorShape([1, 5, 5, 3])
a[0][0]
<tf.Tensor: id=767, shape=(5, 3), dtype=float32, numpy=
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]], dtype=float32)>
a[0][0][0]
<tf.Tensor: id=780, shape=(3,), dtype=float32, numpy=array([1., 1., 1.], dtype=float32)>
a[0][0][0][2]
<tf.Tensor: id=797, shape=(), dtype=float32, numpy=1.0>

numpy : 索引

a = tf.random.normal([4, 28, 28, 3])
a.shape
TensorShape([4, 28, 28, 3])
a[1].shape
TensorShape([28, 28, 3])
a[1, 2].shape
TensorShape([28, 3])
a[1][2][3].shape
TensorShape([3])
a[1, 2, 3, 2].shape
TensorShape([])

切片

一维切片

a = tf.range(10)
a
<tf.Tensor: id=832, shape=(10,), dtype=int32, numpy=array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int32)>
a[-1:]
<tf.Tensor: id=837, shape=(1,), dtype=int32, numpy=array([9], dtype=int32)>
a[-2:]
<tf.Tensor: id=842, shape=(2,), dtype=int32, numpy=array([8, 9], dtype=int32)>
a[:2]
<tf.Tensor: id=847, shape=(2,), dtype=int32, numpy=array([0, 1], dtype=int32)>
a[:-1]
<tf.Tensor: id=852, shape=(9,), dtype=int32, numpy=array([0, 1, 2, 3, 4, 5, 6, 7, 8], dtype=int32)>

多维切片

a = tf.random.normal([4, 28, 28, 3])
a.shape
TensorShape([4, 28, 28, 3])
a[0].shape
TensorShape([28, 28, 3])
a[0, :, :, :].shape
TensorShape([28, 28, 3])
a[0, 1, :, :].shape
TensorShape([28, 3])
a[:, :, :, 0].shape
TensorShape([4, 28, 28])
a[:, :, :, 2].shape
TensorShape([4, 28, 28])
a[:, 0, :, :]    .shape
TensorShape([4, 28, 3])

步长::step

start

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!