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

pytorch学习笔记

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

pytorch学习笔记

pytorch的简单基本方法 tensor与numpy数组的转化 torch.from_numpy() and tensor.numpy()
a np.array([2,3.3]) # 创建一个一行两列的数组
# output [2. 3.3]
b torch.from_numpy(a) # 转化为 tensor
# output tensor([2.0000, 3.3000], dtype torch.float64)
c b.numpy() # 将 tensor 转化为数组
# output [2. 3.3]
tensor 的维度查看 tensor.shape tensor.size()
a torch.Tensor([[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]])
print(a.shape)
# output torch.Size([4, 4])
print(a.size())
# output torch.Size([4, 4])
tensor 的数据随机生成 torch.rand() and torch.randn()
a torch.rand(size (2,3)) # 包含了从区间[0, 1)的均匀分布中抽取的一组随机数
b torch.randn(size (2,3)) # 包含了从标准正态分布 均值为0 方差为1 中抽取的一组随机数
# size 为这个 tensor 的维度
tensor 的维度变换 tensor.reshape() and tensor.view()
a torch.randn(size (4,1,28,28))
a.shape
# output torch.Size([4, 1, 28, 28])
b a.view(4,28*28)
b.shape
# output torch.Size([4, 784])
c a.reshape(4,784)
c.shape
# output torch.Size([4, 784])
如果要将一个 tensor 打平 打平成一维的 
d a.reshape(-1)
d.shape
# output torch.Size([3136])
e a.view(-1)
e.sh ape
# output torch.Size([3136])
tensor 添加维度 及 减少维度 tensor.unsqueeze() and tensor.squeeze()
a torch.rand(szie (4,1,28,28))
print(a.unsqueeze(0).shape)
print(a.unsqueeze(1).shape)
print(a.unsqueeze(2).shape)
print(a.unsqueeze(3).shape)
print(a.unsqueeze(4).shape)
# output 
torch.Size([1, 4, 1, 28, 28]) # 在 0 维度添加一个维度
torch.Size([4, 1, 1, 28, 28]) # 在 1 维度添加一个维度
torch.Size([4, 1, 1, 28, 28]) # 在 2 维度添加一个维度
torch.Size([4, 1, 28, 1, 28]) # 在 3 维度添加一个维度
torch.Size([4, 1, 28, 28, 1]) # 在 4 维度添加一个维度
a torch.rand(size (1,32,1,1))
print(a.squeeze().shape) # 如果 squeeze 中什么参数不填 就默认将所有维度为 1 的 进行去除
# output torch.Size([32]) 
print(a.squeeze(2).shape)
# output torch.Size([1, 32, 1])
tensor 的维度扩增 tensor.expand() and tensor.repeat()
# expand 不会分配新的内存 只是在存在的张量上创建一个新的视图 一个大小等于1的维度扩展到更大的尺寸
# tensor.expand() 仅仅针对于维度为 1 的进行变化 参数中的 -1 代表这个维度不发生变化
a torch.rand(size (2,3,1))
b a.expand(32,-1,-1,5)
b.shape
# output torch.Size([32, 2, 3, 5])
# 沿着特定的维度重复这个张量 这个函数重新分配内存
# tensor.repeat() 里面的参数是每个维度扩增的倍数 这个参数的维度和 a 的维度一致
a torch.rand(size (1,32,1,1))
b a.repeat(4,32,1,1)
print(b.shape)
# output torch.Size([4, 1024, 1, 1])
2 维的 tensor 矩阵 的转置 tensor.t()
# tensor.t() 是对矩阵进行转置 即行变列 列变行
a torch.Tensor([[1,2,3,4],[5,6,7,8]])
print(a)
# output 
tensor([[1., 2., 3., 4.],
 [5., 6., 7., 8.]])
print(a.t())
# output 
tensor([[1., 5.],
 [2., 6.],
 [3., 7.],
 [4., 8.]])
tensor 交换维度 (tensor.transpose())
注意 一次只能交换两个维度 交换多个维度会报错 如果交换多个维度 请使用 tensor.permute()
a torch.rand(size (2,3,4))
print(a.shape)
# output torch.Size([2, 3, 4])
print(a.transpose(0,1).shape)
# output torch.Size([3, 2, 4])
print(a.permute(2,1,0).shape)
# output torch.Size([4, 3, 2])
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/268004.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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