TensorFlow索引与切片语句

    技术2025-10-29  10

    学习课程 1.Basic indexing

    a=tf.ones([1,5,5,3]) #创建tensor a[0][0] #结果是5*3的tensor a[0][0][0] #结果是1*3的tensor a[0][0][0][1] #结果是一个数1

    2.Numpy-style indexing

    a = tf.random.normal([4,28,28,3]) #4张照片 a[1].shape #第2张照片的信息维度,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([])

    3.start:end #左闭右开

    a=tf.range(10) a[-1:] #结果为[9] a[-2:] #结果为[8,9] a[1:] #结果为[1,2,3,4,5,6,7,8,9] a[:-1] #结果为[0,1,2,3,4,5,6,7,8]

    4.Indexing by :

    a = tf.random.normal([4,28,28,3]) #4张照片 a[0].shape #第1张照片的信息维度,TensorShape([28,28,3]) a[0,:,:,:].shape #第1张照片的信息维度,TensorShape([28,28,3]) a[0,1,:,:].shape #第1张照片第1行的信息维度,TensorShape([28,3]) a[:,:,:,2].shape #第三层信息维度,TensorShape([4,28,28]) a[:,0,:,:].shape #第1行信息维度,TensorShape([4,28,3])

    5.Indexing by :: start: end:step ::step

    a[0:2,:,:,:].shape #TensorShape([2,28,28,3]) a[:,0:28:2,:,:].shape #TensorShape([4,14,28,3]) a[:,:14,:,:].shape #TensorShape([4,14,28,3]) a[:,:14,14:,:].shape #TensorShape([4,14,14,3]) a[:,::2,::2,:].shape #TensorShape([4,14,14,3])

    6.::-1 #逆序

    a=tf.range(4) #[0,1,2,3] a[::-1] #[3,2,1,0] a[::-2] #[3,1] a[2::-2] #[2,0]

    7.…

    a = tf.random.normal([2,4,28,28,3]) #,2个tasts,4张照片 a[0].shape #TensorShape([4,28,28,3]) a[0,:,:,:,:].shape #TensorShape([4,28,28,3]) a[0,...].shape #TensorShape([4,28,28,3]) a[:,:,:,:,0].shape #TensorShape([2,4,28,28]) a[...,0].shape #TensorShape([2,4,28,28]) a[0,:,:,:,0].shape #TensorShape([4,28,28]) a[0,...,0].shape #TensorShape([4,28,28])

    8.tf.gather

    a=tf.random.normal([4,35,8]) #4个班级,每个班级35个学生,每个学生8科课程 tf.gather(a,axis=0,indices[2,3]).shape #TensorShape([2,35,8]),选第3和第4个班级的所有数据 a[2:4].shape #TensorShape([2,35,8]),选第3和第4个班级的所有数据 tf.gather(a,axis=0,indices[3,2,4,1]).shape #TensorShape([4,35,8]),所有班级所有数据,但班级查看顺序不一样 tf.gather(a,axis=1,indices[2,4,7]).shape #TensorShape([4,3,8]),所有班级的第3,5,8号学生的所有科目成绩

    9.tf.gather_nd 略 10.tf.boolean_mask

    Processed: 0.009, SQL: 9