深度学习(1):pytorch
PyTorch简介
PyTorch是一个基于Python的深度学习框架,它提供了一种灵活、高效、易于学习的方式来实现深度学习模型。PyTorch最初由Facebook开发,被广泛应用于计算机视觉、自然语言处理、语音识别等领域。
PyTorch使用张量(tensor)来表示数据,可以轻松地处理大规模数据集,且可以在GPU上加速。
PyTorch提供了许多高级功能,如自动微分(automatic differentiation)、自动求导(automatic gradients)等,这些功能可以帮助我们更好地理解模型的训练过程,并提高模型训练效率。
PyTorch会将数据封装成张量(Tensor)进行计算,所谓张量就是元素为相同类型的多维矩阵。
张量可以在 GPU 上加速运行
1、tensor(张量)的创建
(1):tensor()
import torch
import numpy as np
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
#通过三目运算来查看计算设备说cuda或cpu
t = torch.tensor([1,2,3],dtype=torch.float64,device=device)
# tensor数据类型根据输入的数据自动判断
# dtype:指定数据类型
# device:指定计算设备
print(t)#tensor([1., 2., 3.], dtype=torch.float64)
print(t.dtype)#torch.float64
print(t.device)#cpu# 通过numpy创建
t1 = torch.tensor(np.array([1,2,3,4]))
print(t1)#tensor([1, 2, 3, 4], dtype=torch.int32)# 通过标量创建
t2 = torch.tensor(5)
print(t2)#tensor(5)
(2):Tensor
import torch# 不支持数据类型dtype属性,强制转为 torch.float32
# 不支持device属性
# 指定形状创建
t = torch.Tensor(2,3)
print(t)#tensor([[0., 0., 0.],[0., 0., 0.]])
print(t.dtype)#torch.float32
print(t.device)#cpu#通过数组创建
t1 = torch.Tensor([1,2,3])
print(t1)#tensor([1., 2., 3.])t2 = torch.linspace(start:1,end:10,steps:10)
print(t2)#tensor([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
(3):torch.tensor和torch.Tensor的区别
特性 | ttorch.Tensor() | torch.tensor() |
---|---|---|
数据类型推断 | 强制转为 torch.float32 | 根据输入数据自动推断(如整数→int64 ) |
显式指定 dtype | 不支持 | 支持(如 dtype=torch.float64 ) |
设备指定 | 不支持 | 支持(如 device='cuda' ) |
输入为张量时的行为 | 创建新副本(不继承原属性) | 默认共享数据(除非 copy=True ) |
推荐使用场景 | 需要快速创建浮点张量 | 需要精确控制数据类型或设备 |
2、随机数
import torch
# 随机数种子,让每次运行生成随机数相同
torch.manual_seed(0)# 随机生成符合标准正态分布的数,均值0,方差1
t = torch.randn(2,3)#形状(2,3)
print(t)#tensor([[ 1.5410, -0.2934, -2.1788],[ 0.5684, -1.0845, -1.3986]])#生成随机整数:start、end、size
t = torch.randint(0,10,(2,3))
print(t)#tensor([[6, 9, 8],[6, 6, 8]])# shape和size():表示张量的形状
print(t.shape)#torch.Size([2, 3])
print(t.size())#torch.Size([2, 3])# 生成0-1之间的随机数
t = torch.rand(2,3)
print(t)#tensor([[0.1610, 0.2823, 0.6816],[0.9152, 0.3971, 0.8742]])
3、设备切换
默认在cpu上运行,可以显式的切换到GPU:不同设备上的数据是不能相互运算的。
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
t = torch.tensor([1,2,3],device=device)
print(t)
t1 = torch.tensor([1, 2, 3])
t1 = t1.to(device)
print(t1)t2 = torch.tensor([1, 2, 3])
# t2 = t2.cuda()
print(t2)t3 = t2.cpu()
print(t3)
# 设备切换的三种方式
# 1、创建tensor时,显式指定device
# 2、使用to(),如果切换到cuda使用to('cuda'),切换到cpu使用to('cpu')
# 3、使用cuda()或cpu()
4、张量和numpy的转换
(1)张量转numpy
import numpy as np
import torcht = torch.tensor([1,2,3])
print(t)#tensor([1, 2, 3])
# numpy():张量转numpy数组,浅拷贝,修改numpy中的元素会影响tensor
a=t.numpy()
print(a)#[1 2 3]a[0]=100
print(t)#tensor([100, 2, 3])# numpy().copy():深拷贝,复制一个副本,修改副本不会影响tensor
b = t.numpy().copy()
b[0]=200
print(t)#tensor([100, 2, 3])
(2)numpy转张量
a = np.array([1,2,3])
print(a)#[1 2 3]
# from_numpy():numpy转tensor,浅拷贝
t = torch.from_numpy(a)
print(t)#tensor([1, 2, 3], dtype=torch.int32)
t[0] = 10
print(a)#[10 2 3]# tensor(a):numpy转tensor,深拷贝
t1 = torch.tensor(a)
t1[0] = 100
print(a)#[10 2 3]
5、tensor的常见操作
1、item():单个元素的数组获取元素值,不管数组的维度是多少维,只要数组中是当个元素就能获取
t = torch.tensor(10)
print(t.item())#10
t1 = torch.tensor([[10]])
print(t1.item())#10
2、运算方法:方法名后带有下划线表示原地修改,不带下划线表示返回新对象,不修改原始值
t = torch.tensor(10)
t1 = t.add(1)
print(t1)#tensor(11)
print(t)#tensor(10)print(t.add_(2))#tensor(12)
print(t)#tensor(12)
3、阿达码积
前提:
(1)两个矩阵形状相同
(2)两个矩阵相同位置的元素相乘,Cij=Aij X Bij
(3)运算符号:mul或*
t1 = torch.tensor([[1, 2, 3], [4, 5, 6]])t2 = torch.tensor([[1, 2, 3], [4, 5, 6]])t3 = t1 * t2print(t3)#tensor([[ 1, 4, 9],[16, 25, 36]])
4、矩阵运算:
(1)(m x n) x (n x p) = (m x p)
(2)第一个矩阵的每一行和第二个矩阵每一列的元素分别相乘之和,得到新矩阵的一个元素
(3)运算符号:matmul或@
t1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
t2 = torch.tensor([[1, 2], [4, 5], [3, 3]])
t3 = t1 @ t2
print(t3)#tensor([[18, 21],[42, 51]])
5、view():修改数组的形状,不改变内存存储顺序,效率较高
前提:
(1)tensor在内存中是连续的;总元素个数不能改变
(2)连续性:数据在内存中按C顺序存储,一般创建的tensor都是连续的
(3) 如果进行转置等操作可能会导致数据是不连续的,此时使用view()会报错
t1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
# is_contiguous():判断数据是否连续
print(t1.is_contiguous())#Truet2 = t1.transpose(1, 0)
print(t2)#tensor([[1, 4],[2, 5],[3, 6]])
print(t2.is_contiguous())#Flaset3 = t2.view(2, 3)
print(t3)#报错,因为t2不连续
6、交换维度
transpose():交换数组的维度,一次只能交换两个维度
permute():交换数组的维度,交换任意个维度
t1 = torch.randint(1, 10, (3, 4, 5))
print(t1.size())#torch.Size([3, 4, 5])t2 = torch.transpose(t1, 1, 0)
print(t2.size())#torch.Size([4, 3, 5])t3 = torch.permute(t1, (1, 2, 0))
print(t3.size())#torch.Size([4, 5, 3])
7、升维降维
squeeze():降维
unsqueeze():升维
t1 = torch.randint(1, 10, (1, 3, 1))
t2 = torch.squeeze(t1)
print(t2.size())#torch.Size([3])#指定删除维度的索引
t3 = torch.squeeze(t1, dim=0)
print(t3.size())#torch.Size([3, 1])# 如果删除的维度数不为1,则不做任何操作也不报错
t4 = torch.squeeze(t1, dim=1)
print(t4.size())#torch.Size([1, 3, 1])t5 = torch.unsqueeze(t1, dim=0)
print(t5.size())#torch.Size([1, 1, 3, 1])