前言
你好,我是醉墨居士,今天分享一下PyTorch的基本使用的快速入门教程,希望能够帮助各位快速掌握PyTorch的使用
简介
PyTorch 是一个开源的深度学习框架,由 Facebook 的人工智能研究团队(FAIR)开发。它在学术界和工业界都被广泛使用,为深度学习的研究和应用提供了强大的支持
软件包导入
本教程中我们使用torch和numpy这两个包
如果是ubuntu系统,可以看这个教程配置环境:https://blog.youkuaiyun.com/qq_67733273/article/details/144787375
import torch
import numpy as np
创建张量
- form list
print(torch.tensor([1, 2]), torch.tensor([[1, 2], [3, 4]]))
tensor([1, 2]) tensor([[1, 2],
[3, 4]])
- form numpy
print(torch.from_numpy(np.array([1, 2])))
tensor([1, 2])
- 全0填充
print(torch.zeros(2, 3))
tensor([[0., 0., 0.],
[0., 0., 0.]])
- 全1填充
print(torch.ones(2, 3))
tensor([[1., 1., 1.],
[1., 1., 1.]])
- 自定义数值全部填充
print(torch.full([2, 3], 6))
tensor([[6, 6, 6],
[6, 6, 6]])
- 对角矩阵
print(torch.eye(3, 3))
tensor([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
- 未初始化
print(torch.empty(2, 3))
tensor([[5.1981e-06, 0.0000e+00, 0.0000e+00],
[0.0000e+00, 1.5134e-21, 4.2892e-41]])
- 标准正态分布
print(torch.randn(2, 3))
tensor([[ 0.0711, 0.2728, -0.4199],
[ 1.0625, 0.9611, -2.0447]])
- 0 - 1浮点均匀分布
print(torch.rand(2, 3))
tensor([[0.2974, 0.6033, 0.7126],
[0.1599, 0.5974, 0.8983]])
- 1 - 9整数均匀分布
print(torch.randint(1, 10, [2, 3]))
tensor([[1, 2, 8],
[9, 3, 4]])
- 递增数列, 0 ~ 9,步长是2
print(torch.arange(0, 10, 2))
tensor([0, 2, 4, 6, 8])
- 等差数列,0 ~ 10, 共计4个数
print(torch.linspace(0, 10, 4))
tensor([ 0.0000, 3.3333, 6.6667, 10.0000])
- 指定类型创建
print(torch.FloatTensor([1, 2]), torch.LongTensor([1, 2]))
tensor([1., 2.]) tensor([1, 2])
类型操作
- 获取数据类型
print(torch.randn(2, 3).dtype)
torch.float32
- 转换数据类型
print(torch.randn(2, 3).to(torch.float64).dtype)
torch.float64
- 张量形状
print(torch.randn(2, 3).shape