chunk、split、reshape、t、transpose、squeeze/unsqueeze、unbind、 rot90、full、模型的保存与加载、并行化、tensor与numpy的相互转化

一、切片

1. chunk

torch.chunk(tensor, chunks, dim=0)

给定维度(轴)上将输入张量平均分为chunk块最后一个可能小于平均值,返回一个存储着tensor的序列

import torch

a = torch.rand(3, 4)
print(a)
a_chunk = torch.chunk(a, 2, 1)
print(a_chunk[0], a_chunk[0].shape)
print(a_chunk[1], a_chunk[1].shape)

# 输出
tensor([[0.8129, 0.1860, 0.2501, 0.9933],
        [0.5175, 0.7930, 0.1708, 0.4814],
        [0.3094, 0.9449, 0.9941, 0.9578]])
tensor([[0.8129, 0.1860],
        [0.5175, 0.7930],
        [0.3094, 0.9449]]) torch.Size([3, 2])
tensor([[0.2501, 0.9933],
        [0.1708, 0.4814],
        [0.9941, 0.9578]]) torch.Size([3, 2])

2. split

torch.split(tensor, split_size_or_sections, dim=0)

按照某个维度按照split_size_or_sections给出的大小来将tensor分割成块,返回一个存储着tensor的序列

import torch

a = torch.rand(3, 4)
print(a)
a_chunk = torch.split(a, 1, 0)		# split_size_or_sections为实数
print(a_chunk[0], a_chunk[0].shape)
print(a_chunk[1], a_chunk[1].shape)
print(a_chunk[2], a_chunk[2].shape)

a_chunk = torch.split(a, [2, 1], 0)	# split_size_or_sections为序列
print(a_chunk[0], a_chunk[0].shape)
print(a_chunk[1], a_chunk[1].shape)

# 输出
tensor([[0.7652, 0.1922, 0.2849, 0.0250],	# 原tensor
        [0.6783, 0.4474, 0.7084, 0.7255],
        [0.5377, 0.9465, 0.4250, 0.3901]])
tensor([[0.7652, 0.1922, 0.2849, 0.0250]]) torch.Size([1, 4])		# 实数情况
tensor([[0.6783, 0.4474, 0.7084, 0.7255]]) torch.Size([1, 4])
tensor([[0.5377, 0.9465, 0.4250, 0.3901]]) torch.Size([1, 4])
tensor([[0.7652, 0.1922, 0.2849, 0.0250],	# 序列情况
        [0.6783, 0.4474, 0.7084, 0.7255]]) torch.Size([2, 4])
tensor([[0.5377, 0.9465, 0.4250, 0.3901]]) torch.Size([1, 4])

二、张量变形

1. reshape

torch.reshape(input, shape) → Tensor

该方法用来改变tensor的shape,修改的shape必须满足原来的tensor和reshape的tensor元素个数相等

2. t

torch.t(input) → Tensor

只针对2D的tensor转置

3. transpose

torch.transpose(input, dim0, dim1)

交换两个维度, 且transpose一次只能在两个维度间进行

4. squeeze/unsqueeze

torch.squeeze(input, dim=None, out=None)
torch.unsqueeze(input, dim)

维度压缩/扩展,返回一个tensor(张量),其中 input 中大小为1的所有维都已删除或添加维度

5. unbind

torch.unbind(input, dim=0) → seq

将tensor按照指定维度进行切分,并返回一个元组,包含了沿着指定维切片后的各个切片

6. flip

torch.flip(input, dims)

按照指定维度翻转张量(将某个维度里面张量的值前后替换),这里的dims可以是个序列

7. rot90

torch.rot90(input, k, dims)

按照指定维度翻转次数进行张量逆时针旋转90度,这里的dims可以是个序列

三、填充

torch.full(size, fill_value)

用于生成一个填充指定值的tensor

四、模型的保存与加载

torch.saves(state, dir):保存模型参数,优化器参数等等
torch.load(dir):加载模型

六、并行化

torch.get_num_threads():获得用于并行化CPU操作的OpenMP线程数
torch.set_num_threads(int):设定用于并行化CPU操作的OpenMP线程数

七、tensor与numpy的相互转化

torch.from_numpy(ndarry):ndarry转torch
a.numpy():torch转ndarry

本文只用于个人学习与记录,侵权立删

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值