目标
利用Tensorflow 2.x API 实现以下两个目标:
- 对张量(tensor)切片。
- 在张量(tensor)的指定索引处插入数据。
提取张量切片
一维张量
t1 = tf.constant([0,1,2,3,4,5,6,7])
tf.slice(t1, begin=[1], size=[3]) # 利用tf.slice()切片
t1[0:4] # 利用索引切片
t1[-3:]
高维张量
t2 = tf.constant([[0,1,2,3,4],
[5,6,7,8,9],
[10,11,12,13,14],
[15,16,17,18,19]])
tf.slice(t2, begin=[1,1], size=[1,2])
t2[:-1, 0:3]
tf.strided_slice :通过设定步长来提取张量切片
tf.gather :从张量的单个轴中提取特定索引
# 两种方式等价
tf.gather(t1,indices=[0,3,6])
t1[::3]
字符串tensor也适用:
alphabet = tf.constant(list