tf.squeeze()与tf.expand_dims()

本文总结了TensorFlow中的tf.squeeze()与tf.expand_dims()函数,它们用于调整张量维度,特别关注了-1参数的应用和不同维度扩展。通过实例演示了如何在实际项目中高效利用这两种技巧,帮助理解张量维度管理的关键。
部署运行你感兴趣的模型镜像

tf.squeeze()与tf.expand_dims()在变换维度时经常使用,今天来做下总结记录。

tf.squeeze(a,-1)与tf.expand_dims(a,-1)这里的-1指的是对最里面的那个轴(维度)进行压缩或者扩维。这里又容易让人联想到reshape(1,-1)与reshape(-1,1)关于reshape中的-1请看下篇。

tf.expand_dims()

tf.expand_dims(
    input, axis=None, name=None, dim=None
)

     input是一个张量,axis表示对这个张量哪个维度(轴)进行扩维。

     官方示例shape维度

# 't' is a tensor of shape [2]
shape(expand_dims(t, 0)) ==> [1, 2]
shape(expand_dims(t, 1)) ==> [2, 1]
shape(expand_dims(t, -1)) ==> [2, 1]
# 't2' is a tensor of shape [2, 3, 5]
shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5]
shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5]
shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]

tf.squeeze()

tf.squeeze(input, squeeze_dims=None, name=None)
 
Removes dimensions of size 1 from the shape of a tensor. 
从tensor中删除所有大小是1的维度

参数解释:

input:张量。 输入要挤压。
squeeze_dims:可选的ints列表。 默认为[]。 如果指定,只能挤压列出的尺寸。 维度索引从0开始。挤压不是1的维度是一个错误。
name:操作的名称(可选)。

给定张量输入,此操作返回相同类型的张量,并删除所有尺寸为1的尺寸。 如果不想删除所有尺寸1尺寸,可以通过指定squeeze_dims来删除特定尺寸1尺寸。
如果不想删除所有大小是1的维度,可以通过squeeze_dims指定需要删除的维度。

示例:

# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]
shape(squeeze(t)) ==> [2, 3]
Or, to remove specific size 1 dimensions:
 
# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]
shape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1]

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值