栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

初学者的pytorch教程之学习笔记(1)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

初学者的pytorch教程之学习笔记(1)

import torch
t= torch.tensor([
    [1,1,1,1],
    [2,2,2,2],
    [3,3,3,3]
],dtype=torch.float32)

我们可以看到这个张量是一个有两个轴的二阶张量,第一个轴的长度是3,第2个轴的长度是4,第一个轴的元素是数组,第2个轴的元素是数字。

t.size()
torch.Size([3, 4])
t.shape
torch.Size([3, 4])
# 通过检查它的形状长度获得张量的秩
len(t.shape)
2
# 查看分量
t.numel()
12
# 重塑shape
t.reshape(2,6)
tensor([[1., 1., 1., 1., 2., 2.],
        [2., 2., 3., 3., 3., 3.]])
#改变秩
t.reshape(2,2,3)
tensor([[[1., 1., 1.],
         [1., 2., 2.]],

        [[2., 2., 3.],
         [3., 3., 3.]]])

下一步我们可以改变张量的形状。通过压缩(squeezing)和解缩(unsqueezing)它们
压缩一个张量可以移除所有长度为1的轴。而解缩一个张量则会增加-个长度为1的维度
这些函数允许我们放大或缩小张量的秩

print(t.reshape(1,12))
print(t.reshape(1,12).shape)
tensor([[1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.]])
torch.Size([1, 12])
print(t.reshape(1,12).squeeze())
print(t.reshape(1,12).squeeze().shape)
tensor([1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.])
torch.Size([12])
print(t.reshape(1,12).squeeze().unsqueeze(dim=0))
print(t.reshape(1,12).squeeze().unsqueeze(dim=0).shape)
tensor([[1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.]])
torch.Size([1, 12])
 # 通过构建一个flatten函数来压缩一个张量
# 压扁一个张量意味着除去所有的轴,只保留一个,创造了一个单轴的张量,它包含了张量的元素
# flatten的操作,是当我们从一个卷积层过度到全连接层时必须的操作
def flatten(t):
    t = t.reshape(1,-1)
    t = t.squeeze()
    return t
flatten(t)
tensor([1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.])
t.reshape(1,12)
tensor([[1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.]])
# cat函数组合张量
t1 = torch.tensor([
    [1,2],
    [2,3]
])
t2 = torch.tensor([
    [3,4],
    [5,6]
])
torch.cat((t1,t2),dim = 0)
tensor([[1, 2],
        [2, 3],
        [3, 4],
        [5, 6]])
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1005408.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号