深度学习 -- 初步认识Torch
深度学习 – 初步认识Torch
文章目录
- 深度学习 -- 初步认识Torch
- 一,认识人工智能
- 1.1 人工智能的本质
- 1.2 人工智能的实现过程
- 二,认识Torch
- 2.1简介
- 2.2 概述
- 2.3 Tensor的创建
- 2.3.1 torch.tensor
- 2.3.2 torch.Tensor
- 三,创建线性和随机张量
- 3.1创建线性张量
- 3.2 随机张量
- 3.2.1 随机数种子
- 3.2.2 随机张量
- 四,Tensor常见属性
- 4.1常见属性
- 4.2 切换设备
- 4.3类型转换
一,认识人工智能
1.1 人工智能的本质
- 本质是数学计算
- 数学是理论关键
- 计算机是实现关键:算力
- 新的有效算法,需要更大的算力
NLP(说话,听)、CV(眼睛)、自动驾驶、机器人(肢体动作)、大模型
1.2 人工智能的实现过程
三要素:数据、网络、算力
① 神经网络:找到合适的数学公式;
② 训练:用已有数据训练网络,目标是求最优解;
③ 推理:用模型预测新样本;
二,认识Torch
2.1简介
PyTorch是一个基于Python的深度学习框架,它提供了一种灵活、高效、易于学习的方式来实现深度学习模型。PyTorch最初由Facebook开发,被广泛应用于计算机视觉、自然语言处理、语音识别等领域。
PyTorch使用张量(tensor)来表示数据,可以轻松地处理大规模数据集,且可以在GPU上加速。
PyTorch提供了许多高级功能,如**自动微分(automatic differentiation)、自动求导(automatic gradients)**等,这些功能可以帮助我们更好地理解模型的训练过程,并提高模型训练效率。
2.2 概述
PyTorch会将数据封装成张量(Tensor)进行计算,所谓张量就是元素为相同类型的多维矩阵。
张量可以在 GPU 上加速运行。
-
张量是一个多维数组,通俗来说可以看作是扩展了标量、向量、矩阵的更高维度的数组。张量的维度决定了它的形状(Shape),例如:
-
标量 是 0 维张量,如
a = torch.tensor(5)
-
向量 是 1 维张量,如
b = torch.tensor([1, 2, 3])
-
矩阵 是 2 维张量,如
c = torch.tensor([[1, 2], [3, 4]])
-
更高维度的张量,如3维、4维等,通常用于表示图像、视频数据等复杂结构。
-
动态计算图:PyTorch 支持动态计算图,这意味着在每一次前向传播时,计算图是即时创建的。
-
GPU 支持:PyTorch 张量可以通过
.to('cuda')
移动到 GPU 上进行加速计算。 -
自动微分:通过
autograd
模块,PyTorch 可以自动计算张量运算的梯度,这对深度学习中的反向传播算法非常重要。 -
PyTorch中有3种数据类型:浮点数、整数、布尔。其中,浮点数和整数又分为8位、16位、32位、64位,加起来共9种。原因是:场景不同,对数据的精度和速度要求不同。通常,移动或嵌入式设备追求速度,对精度要求相对低一些。精度越高,往往效果也越好,自然硬件开销就比较高。
-
2.3 Tensor的创建
2.3.1 torch.tensor
根据指定的数据创建张量
import torch#使用tensor创建张量
def text1():t1=torch.tensor([1,2,3],dtype=torch.float32,device='cuda')print(t1)print(t1.shape)print(t1.size())#和shapS作用一样print(t1.dtype)if __name__ == '__main__':text1()
tensor([1., 2., 3.], device='cuda:0')
torch.Size([3])
torch.Size([3])
torch.float32
2.3.2 torch.Tensor
根据形状创建张量,其也可用来创建指定数据的张量
#使用Tensor构造函数,构建张量
#强制将数据类型装换位float32
def text2():t1=torch.Tensor([1,2,3])print(t1)print(t1.size())print(t1.dtype)if __name__ == '__main__':# text1()text2()
python
tensor([1., 2., 3.])
torch.Size([3])
torch.float32
torch.Tensor与torch.tensor区别
特性 | torch.Tensor() | torch.tensor() |
---|---|---|
数据类型推断 | 强制转为 torch.float32 | 根据输入数据自动推断(如整数→int64 ) |
显式指定 dtype | 不支持 | 支持(如 dtype=torch.float64 ) |
设备指定 | 不支持 | 支持(如 device='cuda' ) |
输入为张量时的行为 | 创建新副本(不继承原属性) | 默认共享数据(除非 copy=True ) |
推荐使用场景 | 需要快速创建浮点张量 | 需要精确控制数据类型或设备 |
三,创建线性和随机张量
3.1创建线性张量
import torch
import numpy as np
# 设置打印精度
torch.set_printoptions(sci_mode=False)def test01():#创建线性张量r1=torch.arange(1,10,2)print(r1)#在指定空间按照元素个数生成张量r2=torch.linspace(1,10,10)#创建一个从一到十的线性张量print(r2)r3=torch.linspace(3,10000,10)#创建一个从3到10000的线性张量print(r3)if __name__ == '__main__':test01()
tensor([1, 3, 5, 7, 9])
tensor([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
tensor([ 3.0000, 1113.7778, 2224.5557, 3335.3335, 4446.1113, 5556.8887,6667.6665, 7778.4443, 8889.2227, 10000.0000])
3.2 随机张量
使用torch.randn 创建随机张量
3.2.1 随机数种子
随机数种子(Random Seed)是一个用于初始化随机数生成器的数值。随机数生成器是一种算法,用于生成一个看似随机的数列,但如果使用相同的种子进行初始化,生成器将产生相同的数列。
import torchdef test01():torch.manual_seed(1)print(torch.initial_seed())
1
3.2.2 随机张量
在 PyTorch 中,种子影响所有与随机性相关的操作,包括张量的随机初始化、数据的随机打乱、模型的参数初始化等。通过设置随机数种子,可以做到模型训练和实验结果在不同的运行中进行复现。
def test02():#首先设置随机数种子torch.manual_seed(225)#生成一个5*5的矩阵,1到3的随机数x = torch.randint(1, 6, (5, 5))print(x)#randn 生成正太分布的随机数Ss1=torch.randn(2,3)print(s1)
tensor([[5, 1, 5, 3, 3],[2, 5, 4, 3, 2],[1, 4, 3, 2, 3],[1, 2, 5, 3, 4],[4, 1, 5, 5, 2]])
tensor([[ 0.5403, 1.1903, 0.5832],[ 1.5792, 1.5763, -0.6938]])
四,Tensor常见属性
张量有device、dtype、shape等常见属性
4.1常见属性
import torchdef test01():x = torch.tensor([1, 2, 3])print(x.dtype)# torch.int64print(x.device)# cpuprint(x.requires_grad)# Falseprint(x.shape)# torch.Size([3]),表示一维向量,长度为3print(x.size())# torch.Size([3]),表示一维向量,长度为3print(x.ndimension())# 1,张量维度print(x.numel())# 3,元素总数print(x.dim())# 1,张量维度数if __name__ == '__main__':test01()
torch.int64
cpu
False
torch.Size([3])
torch.Size([3])
1
3
1
4.2 切换设备
import torchdef test01():#在创建当量时制定devicex = torch.randint(1, 3, (5, 5), device='cuda')print(x)#使用to方法将数据移动到GPU#转换后要重新赋值y=torch.tensor([1,2,3])y = y.to('cuda')print(y.device)#使用cuda()或cpu()方法 z=torch.tensor([1,2,3],device='cuda')z=z.cpu()print(z.device)if __name__ == '__main__':test01()
tensor([[2, 2, 1, 2, 2],[1, 2, 1, 2, 1],[1, 1, 2, 1, 1],[1, 2, 1, 2, 2],[2, 2, 2, 1, 2]], device='cuda:0')
cuda:0
cpu
4.3类型转换
import torchdef test01():#在创建当量时制定devicex = torch.randint(1, 3, (5, 5), device='cuda')print(x)#使用to方法将数据移动到GPU#转换后要重新赋值y=torch.tensor([1,2,3])y = y.to('cuda')print(y.device)#使用cuda()或cpu()方法 z=torch.tensor([1,2,3],device='cuda')z=z.cpu()print(z.device)def test02():data = torch.tensor([1,2,3])#创建张量print(data.dtype)#使用type()方法转换数据类型data = data.type(torch.float32)print(data.dtype)data = data.type(torch.int32)print(data.dtype)#使用类型方法data = data.float()#转换为float32print(data.dtype)data = data.int()#转换为int32print(data.dtype)data = data.long()#转换为int64print(data.dtype)data = data.short()#转换为int16print(data.dtype)#使用dtype属性data = torch.tensor([1,2,3],dtype=torch.float32)#转换为float32print(data.dtype)if __name__ == '__main__':# test01()test02()
torch.int64
torch.float32
torch.int32
torch.float32
torch.int32
torch.int64
torch.int16
torch.float32