TensorFlow 切片操作

1、切片操作

import tensorflow as tf
import numpy as np
print(tf.__version__)
print(np.__version__)

# 切片 start:end  [A:B)
a = tf.range(10)
print(a)

在这里插入图片描述

print(a[-1:])
print(a[-2:])
print(a[:2])
print(a[:-1])

在这里插入图片描述

2、部分维度切片

# 取部分维度数据
a = tf.random.normal([4, 28, 28, 3])
print(a.shape)

在这里插入图片描述

print(a[0].shape)
print(a[0,1,:,:].shape)
print(a[:,:,:,0].shape)
print(a[:,:,:,2].shape)
print(a[:,0,:,:].shape)
print(a[0:2,:,:,:].shape)

在这里插入图片描述

3、隔行(step)切片采样

# 步长 隔行采样[A:B:step) 
print(a[:,0:28:2,0:28:2,:].shape)
print(a[:,:14,:14,:].shape)
print(a[:,14:,14:,:].shape)
print(a[:,::2,::2,:].shape)
print(a[:,2:26:2,2:26:2,:].shape)

在这里插入图片描述

4、逆序切片

# 逆序切片 [B:A:-1)
a = tf.range(4)
print(a)

在这里插入图片描述

print(a[::-1])
print(a[::-2])
print(a[2::-2])

在这里插入图片描述

5、截取一列

sub = tf.random.uniform((3, 3)) # 随机创建 3*3的数组
print(sub.numpy()) # 以numpy格式显示
print(sub[..., 1].numpy(), sub[..., 1].shape) # 截取第二列

在这里插入图片描述

索引

a = tf.random.normal([4, 35, 8])
print(a.shape)
# 数据 0维度数据  索引2,3 组合的数据
b1 = tf.gather(a, axis=0, indices=[2, 3])
print(b1.shape)

# 重新排列 0维数据  [0, 1, 2, 3] ==> [1, 0, 3, 2]
b = tf.gather(a, axis=0, indices=[1, 0, 3, 2])
print(b.shape)

# 抽取 1维 7,9,15 索引数据
c = tf.gather(a, axis=1, indices=[7, 9, 15])
print(c.shape)

# 抽取 2维 3,4,6 索引数据
d = tf.gather(a, axis=2, indices=[3, 4, 6])
print(d.shape)

在这里插入图片描述

# tf.gather_nd
# 抽取 给定索引值数据 组合
b = tf.gather_nd(a, [0, 1])
print(b.shape)

c = tf.gather_nd(a, [0, 1, 2])
print(c.shape)

d = tf.gather_nd(a, [[0, 1, 2]])
print(d.shape)

在这里插入图片描述

# 抽取 不同索引数据 组合
b = tf.gather_nd(a, [[0, 1], [1, 1]])
print(b.shape)

c = tf.gather_nd(a, [[0, 0, 0], [1, 1, 1], [2, 2, 2]])
print(c.shape)

d = tf.gather_nd(a, [[[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]])
print(d.shape)

在这里插入图片描述

# tf.boolean_mask
a = tf.random.normal([4, 28, 28, 3])
print(a.shape)

# 抽取 True所在索引的数据
b = tf.boolean_mask(a, mask=[True,True,False,False])
print(b.shape)

c = tf.boolean_mask(a, mask=[True,True,False], axis=3)
print(c.shape)

在这里插入图片描述

a = tf.ones([2, 3, 4])

d = tf.boolean_mask(a, mask=[[True, False, False], [False, True, True]])
print(d.shape)

在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

廷益--飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值