pytorch基础(二)----------张量的拼接、切片、索引以及数学运算

张量的操作

一、张量的拼接

1、torch.cat(input, dim=0, out=None)
功能:将张量按维度dim进行拼接
参数:input:要操作的张量
dim:要拼接的维度
2、torch.stack(input, dim=0, out=None)
功能:在新创建的维度上进行拼接
参数:input:要操作的张量
dim:要拼接的维度
cat和stack的区别是,cat方法不会扩展维度,而stack会扩展一个新的维度进行拼接

二、张量的切分

1、torch.chunk(input, chunks, dim=0)
功能:将张量按维度进行平均切分
返回值:张量列表
注意:若不能整除,最后一份的张量小于其他张量
参数:input:要操作的张量
chunks:要切分的份数
dim:维度
2、torch.split(input, split_size_or_sections, dim=0)
功能:将张量按维度进行切分
返回值:张量列表
参数:input:要切分的张量
split_size_or_sections:为int时,表示每一份的长度,为list时,按list元素切分
dim:维度
注意:split_size_or_sections在使用int时等于torch.chunk,在使用list时list内各元素之和要等于这个维度上长度(不等于就会报错)

三、张量的索引

1、torch.index_select(input, dim, index, out=None)
功能:在维度上,按index索引数据
返回值:索引到的所有数据拼接成新的张量输出
参数:input:要操作的张量
dim:维度
index:要索引的序号,索引的数据类型必须是torch.long
2、torch.masked_select(input, mask, out=None)
功能:按照mask中的True进行索引
返回值::一维张量
参数:input:要操作的张量
mask:与input相同的布尔类型的张量

四、张量的变换

1、torch.reshape(input, shape)
功能:变换张量的形状
注意:当张量在内存中连续时,新张量与input共享数据内存
参数:input:要操作的张量
shape:新张量的形状
2、torch.transpose(input, dim0, dim1)
功能:交换张量的两个维度
参数:input:要操作的张量
dim0:维度1
dim1:维度2
3、torch.t(input)
功能:二维张量的转置,对于矩阵而言等同于torch.transpose(input, 0, 1)
4、torch.squeeze(input, dim=None, out=None)
功能:压缩长度为1的维度
参数:dim:如果为None,移除所有长度为1的维度;如果指定维度,当且仅当该轴长度为1时,可以被移除
5、torch.unsqueeze(input, dim, out=None)
功能:依据dim扩展维度为1的维度

五、张量的数学运算

总共可以分为三大类:加减乘除、对数指数幂函数、三角函数
下面展示的是各种数学运算的方法
在这里插入图片描述
介绍一下经常用到而且比较特殊的几个:
1、torch.add(input, alpha=1, other, out=None)
功能:逐元素计算, i n p u t + a l p h a ∗ o t h e r input+alpha*other input+alphaother
参数:input:第一个张量
alpha:乘项因子
other:第二个张量
2、torch.addcdiv(input, value=1, tensor1, tensor2, out=None)
功能:逐元素计算, i n p u t + v a l u e ∗ t e n s o r 1 t e n s o r 2 input+value*\frac{tensor1}{tensor2} input+valuetensor2tensor1
3、torch.addcmul(input, value=1, tensor1, tensor2, out=None)
功能:逐元素计算, i n p u t + v a l u e ∗ t e n s o r 1 ∗ t e n s o r 2 input+value*tensor1*tensor2 input+valuetensor1tensor2

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值