吴裕雄--天生自然TensorFlow2教程:numpy [ ] 索引

import tensorflow as tf

a = tf.ones([1, 5, 5, 3])
a.shape

a[0][0]
numpy : 索引

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

a[1].shape

a[1, 2].shape
a[1][2][3].shape
a[1, 2, 3, 2].shape
一维切片
a = tf.range(10)
a

a[-1:]
a[-2:]
a[:2]
a[:-1]
多维切片
a = tf.random.normal([4, 28, 28, 3])
a.shape

a[0].shape

a[0, :, :, :].shape

a[0, 1, :, :].shape

a[:, :, :, 0].shape

a[:, :, :, 2].shape

a[:, 0, :, :].shape
步长::step
a = tf.random.normal([4, 28, 28, 3])
a.shape

a[0:2, :, :, :].shape

a[:, 0:28:2, 0:28:2, :].shape

a[:, :14, :14, :].shape

a[:, 14:, 14:, :].shape

a[:, ::2, ::2, :].shape
倒序::-1
a = tf.range(4)
a

a[::-1]

a[::-2]

a[2::-2]
省略号...
a = tf.random.normal([2, 4, 28, 28, 3])
a.shape

a[0].shape

a[0, :, :, :, :].shape

a[0, ...].shape

a[:, :, :, :, 0].shape

a[..., 0].shape

a[0, ..., 2].shape

a[1, 0, ..., 0].shape
gather

a = tf.random.normal([4, 35, 8])
a.shape

tf.gather(a, axis=0, indices=[2, 3]).shape

a[2:4].shape

tf.gather(a, axis=0, indices=[2, 1, 3, 0]).shape

tf.gather(a, axis=1, indices=[2, 3, 7, 9, 16]).shape

tf.gather(a, axis=2, indices=[2, 3, 7]).shape

aa = tf.gather(a,axis,[several students])
aaa = tf.gather(aa,axis,[several subjects])
gather_nd

a = tf.random.normal([4, 35, 8])
a.shape

tf.gather_nd(a, [0]).shape  # [[0],[],[]]

tf.gather_nd(a, [0, 1]).shape

tf.gather_nd(a, [0, 1, 2]).shape

tf.gather_nd(a, [[0, 1, 2]]).shape

tf.gather_nd(a, [[0, 0], [1, 1]]).shape

tf.gather_nd(a, [[0, 0], [1, 1], [2, 2]]).shape

# 第一个班级第一个学生的第一门课
# 第二个班级第二个学生的第二门课
# 第三个班级第三个学生的第三门课
tf.gather_nd(a, [[0, 0, 0], [1, 1, 1], [2, 2, 2]]).shape

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

tf.boolean_mask(a, mask=[True, True, False, False]).shape

tf.boolean_mask(a, mask=[True, True, False], axis=3).shape

a = tf.ones([2, 3, 4])
a.shape

# [2,3],还剩下4,三个True,因此是3*4True
tf.boolean_mask(a, mask=[[True, False, False], [False, True, True]]).shape

猜你喜欢

转载自www.cnblogs.com/tszr/p/12105009.html