举例说明
索引
数据中存有5张28x28的照片的三通道分析数据
data:[5, 28, 28, 3]
#使用随机分布进行模拟图片数据
data = tf.random.normal([5, 28, 28, 3])
#索引至第5张照片的所有信息
data1 = data[4]
切片
-
省略号(…)
数据中有多个维度时,只需要在其中个别维度中进行获取数据,即可用省略号代表其他维度不填写#以上述照片的数据为例 data2 = data [3,...,2]#取第一维度中的下标为3且第四维度中下标为2的数据,其中第二、三维度不填写用...(省略号)代替
-
start : end : step
在0~9之间进行获取数据
array = tf.range(10) # array = [0 1 2 3 4 5 6 7 8 9]
# 顺序的下标:0 ----------------> 9
# 逆序的下标:<--------------- -2, -1
array1 = array[ : 5]#[0 1 2 3 4]
array2 = array[-1 : ]#[9]
array3 = array[-2 : ]#[8 9]
array4 = array[ : -1]#[0 1 2 3 4 5 6 7 8]
array5 = array[0 : 5 : 2] #间隔一个进行采样 array5 = [0 2 4]
"""
step为负数时则从在start位置上的元素开始采样,即倒序采样
"""
array6 = array[ : : -1]# array6 = [9 8 7 6 5 4 3 2 1 0]
array7 = array[ : : -2]# array7 = [9 7 5 3 1]
array8 = array[6 : : -2]# array8 = [6 4 2 0]
- tf.gather(params, indices, axis)
从params的axis维,根据indices的参数值获取切片
tf.gather(data, [2,4,5], axis=0)#在data中从0维,分别取下标为2、4、5的数据
tf.gather(data, [3,4,5], axis=1)#在data中从1维,从中分别取下标为3、4、5的数据
- tf.gather_nd(params, indices)
数据中存有N个班级,M个学生,每个学生R门课程成绩
data:[classes, students, subjects]
data = tf.random.normal([3, 5, 5])
data1 = tf.gather_nd(data, [0]) #0号班级所有学生的成绩
data2 = tf.gather_nd(data, [0, 1]) #0号班级中1号学生的所有课程成绩
data3 = tf.gather_nd(data, [0, 1, 2]) #0号班级中1号学生的2号课程成绩
'''联合索引'''
data4 = tf.gather_nd(data, [ [0, 1], [1, 1] ])#0号班级中1号学生与1号班级中1号学生的所有课程成绩的综合
data5 = tf.gather_nd(data, [ [0, 1, 2], [1, 1, 2] ])#0号班级中1号学生与1号班级中1号学生的2号课程成绩的综合