Pytorch基本用法

📅 2026/6/26 6:28:36
Pytorch基本用法
1、了解张量与基本创建1.1什么是张量张量是pytorch中的基本数据结构可以看作是多维数组。1.2张量的创建torch.tensor根据数据创建张量torch.Tensor根据形状创建数量或根据数据创建张量torch.FloatTensor : 创建类型为torch.float32 (默认浮点类型)torch.DoubleTensor :创建类型为torch.float64torch.HalfTensor :创建类型为torch.float16torch.IntTensor :创建类型为torch.int32torch.LongTensor :创建类型为torch.int64(默认整型)torch.ShortTensor :创建类型为torch.int16torch.ByteTensor :创建类型为torch.uint8torch.BoolTensor :创建类型为torch.bool1.3代码演示import torch # 从标量创建 scalar torch.tensor(3.14159) print(f标量张量{scalar},维度{scalar.dim()}) # 从列表创建向量 vector torch.tensor([1,2,3,4]) print(f向量张量{vector},维度{vector.dim()}) # 从嵌套列表创建矩阵 matrix torch.tensor([[1,2,3],[4,5,6]]) print(f矩阵张量{matrix},维度{matrix.dim()}) # 从嵌套列表创建3维张量 tensor_3d torch.tensor([[[1,2],[3,4],[5,6],[7,8]]]) print(f3维张量{tensor_3d},维度{tensor_3d.dim()}) 根据torch.Tensor()函数创建张量 scalar1 torch.Tensor([3.1459]) print(f标量张量{scalar1},维度{scalar1.dim()}) vector1 torch.Tensor((1,2,3,4)) print(f向量张量{vector1},维度{vector1.dim()}) matrix1 torch.Tensor(2,3) print(f矩阵张量{matrix1},维度{matrix1.dim()}) tensor_3d1 torch.Tensor(2,2,2) print(f3维张量{tensor_3d1},维度{tensor_3d1.dim()}) 根据torch.IntTensor()函数创建张量 scalar2 torch.IntTensor([3.14159]) print(f标量张量{scalar2},维度{scalar2.dim()}) matrix2 torch.IntTensor(2,3) print(f矩阵张量{matrix2},维度{matrix2.dim()})2、pytorch统一值张量2.1 创建方法import torch device torch.device(cuda if torch.cuda.is_avaliable() else cpu) # 所有值为1 ones torch.ones((2,3),devicedevice) print(fones:{ones} device:{ones.device}) # 所有值为0 zeros torch.zeros((2,3),devicedevice) print(fzeros:{zeros} device:{zeros.device}) # 所有值为6 sixes torch.full((2,3),6,devicedevice) print(fsixes:{sixes} device:{sixes.device}) like_ones torch.ones_like(sixes,devicedevice) print(flike_ones:{like_ones} device:{like_ones.device}) like_zeros torch.zeros_like(sixes,devicedevice) print(flike_zeros:{like_zeros} device:{like_zeros.device}) like_sixes torch.full_like(sixes,6,devicedevice) print(flike_sixes:{like_sixes} device:{like_sixes.device})有问题欢迎在评论区讨论环境配置、bug等都可以发在评论区看到都会给大家解决暑期打算更新YOLO相关模块的详细讲解