tensorflow2之切片

  • tf.gather:按axisindices获取索引对应的tensor
a = tf.Variable([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]])
idx_a = tf.Variable([0, 2])
tf.gather(a, idx_a)
# 返回: [[1,2,3,4,5],  [11,12,13,14,15]]

tf.gather(a, idx_a, axis=1)
# 返回: [[1,3],  [6,8], [11,13]]
a = tf.Variable([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]])
idx_b = tf.Variable([[0, 1], [0, 3], [2, 4]])
tf.gather_nd(a, idx_b)
# 返回: [2, 4, 15]

idx_c = [[0], [1]]
tf.gather_nd(a, idx_c)
# 返回:[[1,2,3,4,5], [6,7,8,9,10]]
c = [[1, 2], [3, 4], [5, 6]]
mask = np.array([True, True, False])
tf.boolean_mask(c, mask)
# 返回:[[1, 2], [3, 4]]

c = tf.constant([[-1,1,-1],[2,2,-2],[3,-3,3]],dtype=tf.float32)
tf.boolean_mask(c,c<0)
c[c<0]
#  返回结果相同:均为获取张量`c`小于零的元素,返回一维数组
  • tf.where
    • 返回Trueidx
    • True则返回x对应的元素,否则返回y对应的元素
tf.where([True, False, True, True])
# 返回: [[0], [2], [3]]
tf.where(([[True, False], [False, True], [True, True]]))
# 返回:[[0, 0], [1, 1], [2, 0], [2, 1]]

tf.where([True, False, False, True], [1,2,3,4], [100,200,300,400])
# 返回:[1, 200, 300, 4]]
tf.where([True, False, False, True], [1,2,3,4], [100])
# 返回:[1, 100, 100, 4]
tf.where([True, False, False, True], [1,2,3,4], 100)
# 返回:[1, 100, 100, 4]
tf.where([True, False, False, True], 1, 100)
# 返回:[1, 100, 100, 1]

c = tf.constant([[-1,1,-1],[2,2,-2],[3,-3,3]],dtype=tf.float32)
# 返回符合条件的位置坐标
tf.where(c < 0)
# 将小于零的值替换为nan
tf.where(c<0,tf.fill(c.shape,np.nan),c) 
indices = tf.constant([[4], [3], [1], [7]])
updates = tf.constant([9, 10, 11, 12])
# 用update来填充indices至目标shape
tf.scatter_nd(indices, updates, shape=tf.constant([8]))

# 除[0,0],[2,1]外,其它位置元素全部用0填充
tf.scatter_nd([[0,0],[2,1]],[c[0,0],c[2,1]],c.shape)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值