学习笔记,仅供参考,有错必究
文章目录
PyTorch基础
PyTorch介绍
- Torch
Torch是一个开源的机器学习的框架,早在2002年就发布了Torch的初版,Torch的编程语言为C和Lua。如今的Torch7依旧是热门的深度学习框架之一。
- PyTorch
PyTorch是在2017年1月由Facebook推出的。它是经典机器学习库Torch框架的一个端口,主要编程语言为python.
- PyTorch的快速发展
PyTorch CPU版安装
首先进入PyTorch官网;
按照自己的情况,选择想要安装的PyTorch版本,如下图所示:
将上图中,被红色长方形 框住的代码复制到cmd中,并进行如下修改:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple torch torchvision torchaudio
修改完成后,回车进行安装:
导包
# 导入常用的包
import torch
import numpy as np
构造tensor
a = torch.tensor([1, 2, 3], dtype = int)
print(a)
tensor([1, 2, 3])
b = torch.tensor([4, 5, 6], dtype = float)
print(b)
tensor([4., 5., 6.], dtype=torch.float64)
t1 = torch.tensor([[1, 2, 3],
[4, 5, 6]])
print(t1)
tensor([[1, 2, 3],
[4, 5, 6]])
tensor的基本属性
# 查看数据类型
a.dtype
b.dtype
torch.int64
torch.float64
# 查看数据维度
a.ndim
t1.ndim
1
2
# 查看数据的形状
a.shape
t1.shape
t1.size()
torch.Size([3])
torch.Size([2, 3])
torch.Size([2, 3])
生成数据
# 生成全1张量
torch.ones(2, 3)
tensor([[1., 1., 1.],
[1., 1., 1.]])
# 生成全0张量
torch.zeros(3, 3)
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
# 生成包含[0, 1)随机数的张量
torch.rand(3, 4)
tensor([[0.3797, 0.5408, 0.5703, 0.9994],
[0.3843, 0.6358, 0.0099, 0.0339],
[0.8164, 0.5019, 0.7004, 0.4033]])
# 生产包含随机整数的张量
torch.randint(0, 5, (2, 3))
tensor([[3, 3, 3],
[3, 1, 4]])
# 生成包含 服从正态分布的随机数的张量
torch.randn(3, 4)
tensor([[ 0.5376, -1.8396, 0.1551, -1.1469],
[ 0.3814, 0.0709, 1.2827, 0.3375],
[-0.6563, 0.9816, -0.7495, -1.4707]])
# 生成和某个张量形状一样的随机数张量
a = torch.tensor([[1, 2],
[4, 5],
[6, 7]])
b = torch.rand_like(a, dtype = float)
b
print(b.shape)
tensor([[0.8122, 0.4363],
[0.3702, 0.4267],
[0.8426, 0.4262]], dtype=torch.float64)
torch.Size([3, 2])
# 使用view改变张量的形状,类似于numpy中的reshape
c = b.view(6)
c
tensor([0.8122, 0.4363, 0.3702, 0.4267, 0.8426, 0.4262], dtype=torch.float64)
d = b.view(2, 3)
d
tensor([[0.8122, 0.4363, 0.3702],
[0.4267, 0.8426, 0.4262]], dtype=torch.float64)
e = d.reshape(6)
e
tensor([0.8122, 0.4363, 0.3702, 0.4267, 0.8426, 0.4262], dtype=torch.float64)
# 获取张量中的某个值,并转换为python中的标准数值
e[0]
e[0].item()
tensor(0.8122, dtype=torch.float64)
0.8122101766213651
# 将tensor变成numpy.array
f = np.array(d)
f
array([[ 0.81221018, 0.43634955, 0.37021041],
[ 0.4267468 , 0.84262264, 0.4261592 ]])
# 将numpy.array变成tensor
arr = np.array([[1, 2, 3]])
tens = torch.tensor(arr)
tens
tensor([[1, 2, 3]], dtype=torch.int32)