分享
实验1:Pytorch基本操作
输入“/”快速插入内容
实验1:Pytorch基本操作
用户6705
用户6705
2025年11月30日修改
什么是 PyTorch ?
PyTorch是一个python库,它主要提供了两个高级功能:
•
GPU加速的张量计算
•
构建在反向自动求导系统上的深度神经网络
1.
定义数据
一般定义数据使用torch.Tensor , tensor的意思是张量,是数字各种形式的总称
代码块
Python
import torch
# 可以是一个数
x = torch.tensor(666)
print(x)
输出:tensor(666)
代码块
Python
# 可以是一维数组(向量)
x = torch.tensor([1,2,3,4,5,6])
print(x)
输出:tensor([1, 2, 3, 4, 5, 6])
代码块
Python
# 可以是二维数组(矩阵)
x = torch.ones(2,3)
print(x)
输出:tensor([[1., 1., 1.],
[1., 1., 1.]])
代码块
Python
# 可以是任意维度的数组(张量)
x = torch.ones(2,3,4)
print(x)
输出:
tensor([[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]],
[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]]])
Tensor支持各种各样类型的数据,包括:
torch.float32, torch.float64, torch.float16, torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64 。这里不过多描述。
创建Tensor有多种方法,包括:ones, zeros, eye, arange, linspace, rand, randn, normal, uniform, randperm, 使用的时候可以在线搜,下面主要通过代码展示。
代码块
Python
# 创建一个空张量
x = torch.empty(5,3)
print(x)
输出:
tensor([[1.4178e-36, 0.0000e+00, 4.4842e-44],
[0.0000e+00, nan, 0.0000e+00],
[1.0979e-05, 4.2008e-05, 2.1296e+23],
[1.0386e+21, 4.4160e-05, 1.0742e-05],
[2.6963e+23, 4.2421e-08, 3.4548e-09]])
代码块
Python
# 创建一个随机初始化的张量
x = torch.rand(5,3)
print(x)