tensorflow2.0基本操作三,tensor的索引与切片

import  os
import  tensorflow as tf
#basic indexing
a = tf.ones([1,5,5,3])
print(a)
print('------------------------------------')
print(a[0][0])#选择第一个

print(a[0][0][0])#选择第一个的第0行
print(a[0][0][0][1])#选择第一个的第0行的第二个元素



#numpy-style indexin
#推荐使用这种类似于numpy风格的形式进行
a = tf.random.normal([4,28,28,3])
a[1].shape#调出a中第二张照片的shape
a[1,2].shape#调出a中第二张照片的第三行的数值
a[1,2,3].shape#调出a中第二张照片的第三行第四列的数值
a[1,2,3,2].shape#调出a中第二张照片的第三行第四列B通道的数值


#start:end
#切片,末端不包含
a = tf.range(10)
#最后一个
a[-1:]
#最后两个
a[-2:]
#开头两个
a[:2]
#最开始到最后一个之前
a[:-1]





#使用":"做索引
a.shape#这里的a指的是一个数据集,比如说,一个有着很多个照片的数据集
a[0].shape
a[0,:,:,:].shape#取第一个数据,后面所有维度的数据都取
a[0,1,:,:].shape
a[:,:,:,0].shape
a[:,:,:,2].shape
a[:,0,:,2].shape




#使用"::"做索引
#start:end:step#隔着两个做索引
a[:,::2,::2,:].shape



#倒序功能
#::-1
a = tf.range(4)
a[::-1]
a[::-2]
a[2::-2]




#...的应用,用于代替那些冒号。
a = tf.random.normal([2,4,28,28,3])
a[0].shape

#比如这两种情况下,输出效果是一样的
a[0,:,:,:,:].shape
a[0,...].shape


#这两种情况下,输出效果是一样的
a[:,:,:,:,0].shape
a[...,0].shape



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










#selective indexing
#tf.gather
#tf.gather_nd
#tf.boolean_mask
a = [4,35,8]#班级个数,学生人数,课程数

#查询2,3号班级的成绩
#取班级维度,第0维,选择里面的2,3个成绩
tf.gather(a,axis=0,indices=[2,3]).shape#数据源,取哪个维度,indices班级具体的索引号

a[2:4].shape

tf.gather(a,axis=0,indices = [2,1,3,0]).shape#搜2号再搜1号,再搜3号,再搜0号班级的成绩


#取学生维度,第1维,选择里面的2,3,7,9,16个学生
tf.gather(a,axis=1,indices = [2,3,7,9,16]).shape

#取课程维度,第2维,选择里面的第2,3,7个课程
tf.gather(a,axis=2,indices = [2,3,7]).shape








#a.shape→[4,35,8]

tf.gather_nd(a,[0]).shape#→取0号班级的数据
tf.gather_nd(a,[0,1]).shape#取0号班级,一号学生的数据
tf.gather_nd(a,[0,1,2]).shape#取0号班级,一号学生的2号课程的数据
tf.gather_nd(a,[[0,1,2]]).shape



tf.gather_nd(a,[[0,0],[1,1]]).shape#第0号班级的第0个成绩与第1号班级的第一个成绩







#tf.boolean_mask,True代表要这个元素,False代表不要这个元素
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])

tf.boolean_mask(a,mask =[ [True,False,False],[False,True,True]]).shape
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丰。。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值