Q u i c k S t a r t QuickStart QuickStart
常用工具函数
dir()
打开工具箱子,输出里面的工具或者小工具箱子
help()
输入工具使用方法,不过可以自己去看文档
Working with data
PyTorch 有两个用于处理数据的基本工具:torch.utils.data.DataLoader
和 torch.utils.data.Dataset
。Dataset
存储样本及其对应的标签,而 DataLoader
则在 Dataset
周围封装一个可迭代对象。
PyTorch 提供了特定领域的库,例如 TorchText、TorchVision 和 TorchAudio,它们都包含数据集。
Ep:
import torch
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
# Download training data from open datasets.
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor(),
)
# Download test data from open datasets.
test_data = datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor(),
)
batch_size = 64
# Create data loaders.
train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)
for X, y in test_dataloader:
print(f"Shape of X [N, C, H, W]: {X.shape}")
print(f"Shape of y: {y.shape} {y.dtype}")
break
torch.utils.data.Dataset
简介
- Stores the samples and their corresponding labels
- All datasets that represent a map from keys to data samples should subclass it
用法
-
Overwrite according to demand :
-
__init__
: Read data & preprocess 读资料与前处理 -
__getitem__
:Supporting fetching a data sample for a given key. 读取一笔一笔的资料的时候,看资料是什么东西 -
__len__
:Return the size of the dataset by many :class:~torch.utils.data.Sampler
implementations and the default options of :class:~torch.utils.data.DataLoader
. -
__getitems__
:Speed up batched samples loading. Accepts list of indices of samples of batch. Returns list of samples.
-
torch.utils.data.DataLoader
简介
- wraps an iterable around the
Dataset
(group data in batches, enables multiprocessing)
Creating Models
在 PyTorch 中定义一个神经网络,我们需要创建一个继承自 nn.Module
的类。我们在 __init__
函数中定义网络的层,并在 forward
函数中指定数据如何通过网络传递。为了加速神经网络中的运算,我们将其移动到加速器上,例如 CUDA、MPS、MTIA 或 XPU。如果当前加速器可用,我们将使用它。否则,我们将使用 CPU。
Ep :
from torch import nn
device = torch.accelerator.current_accelerator().type if torch.accelerator.is_available() else "cpu"
print(f"Using {device} device")
# Define model
class NeuralNetwork(nn.Module):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28*28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10)
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
model = NeuralNetwork().to(device)
print(model)
Optimizing the Model Parameters
To train a model, we need a loss function and an optimizer.
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
在一个单一的训练循环中,模型对训练数据集(以批次形式输入)进行预测,并反向传播预测误差以调整模型的参数。
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset)
model.train()
for batch, (X, y) in enumerate(dataloader):
X, y = X.to(device), y.to(device)
# Compute prediction error
pred = model(X)
loss = loss_fn(pred, y)
# Backpropagation
loss.backward()
optimizer.step()
optimizer.zero_grad()
if batch % 100 == 0:
loss, current = loss.item(), (batch + 1) * len(X)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
We also check the model’s performance against the test dataset to ensure it is learning.
def test(dataloader, model, loss_fn):
size = len(dataloader.dataset)
num_batches = len(dataloader)
model.eval()
test_loss, correct = 0, 0
with torch.no_grad():
for X, y in dataloader:
X, y = X.to(device), y.to(device)
pred = model(X)
test_loss += loss_fn(pred, y).item()
correct += (pred.argmax(1) == y).type(torch.float).sum().item()
test_loss /= num_batches
correct /= size
print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
训练过程会进行多次迭代(epoch)。在每个 epoch 期间,模型学习参数以做出更好的预测。我们在每个 epoch 打印模型的准确率和损失;我们希望看到准确率随着每个 epoch 的增加而增加,损失随着每个 epoch 的增加而减少。
epochs = 5
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train(train_dataloader, model, loss_fn, optimizer)
test(test_dataloader, model, loss_fn)
print("Done!")
Saving Models
一种常见方法 : 序列化内部状态字典(包含模型参数)。
torch.save(model.state_dict(), "model.pth")
print("Saved PyTorch Model State to model.pth")
Loading Models
加载模型的过程包括:
- 重新创建模型结构(架构)
- 将状态字典(state_dict)加载到模型中。
model = NeuralNetwork().to(device)
model.load_state_dict(torch.load("model.pth", weights_only=True))
This model can now be used to make predictions.
classes = [
"T-shirt/top",
"Trouser",
"Pullover",
"Dress",
"Coat",
"Sandal",
"Shirt",
"Sneaker",
"Bag",
"Ankle boot",
]
model.eval()
x, y = test_data[0][0], test_data[0][1]
with torch.no_grad():
x = x.to(device)
pred = model(x)
predicted, actual = classes[pred[0].argmax(0)], classes[y]
print(f'Predicted: "{predicted}", Actual: "{actual}"')
T e n s o r Tensor Tensor
Tensors are a specialized data structure that are very similar to arrays and matrices. In PyTorch, we use tensors to encode the inputs and outputs of a model, as well as the model’s parameters.
张量类似于 NumPy 的 ndarrays,不同之处在于张量可以在 GPU 或其他硬件加速器上运行。事实上,张量和 NumPy 数组通常可以共享相同的底层内存,无需复制数据 。
import torch
import numpy as np
很多Tensor的方法与属性与ndarray相同
初始化
tensor对象的创建依托于torch的函数
数据直创
数据类型是自动推断的
data = [[1,2][3,4]]
x_data = torch.tensor(data)
Numpy数组
n d a r r a y ↔ t e n s o r ndarray \leftrightarrow tensor ndarray↔tensor
np_array = np.array(data)
x_np =torch.from_numpy(np_array)
从另一张量
新张量保留参数张量的属性(形状,数据类型),除非显式覆盖
x_ones = torch.ones_like(x_data)
print(x_ones)
x_rand = torch.rand_like(x_data,dtype=torch.float)# overrides the datatype of x_data
print(x_rand)
使用随机值或常量值
shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
print(rand_tensor)
print(ones_tensor)
print(zeros_tensor)
属性
-
shape
-
dtype
-
device
存储Tensor的设备
操作
超过 1200 种张量运算,包括算术、线性代数、矩阵作(转置、 indexing, slicing)、sampling 等, 资料库进行了全面描述。
这些操作都可以在 CPU 和 Accelerator 上运行,例如 CUDA、MPS、MTIA 或 XPU。
移动到加速器进行运算
认情况下,张量是在 CPU 上创建的。
需要将张量显式移动到加速器(在检查加速器可用性之后)。
复制大型张量 跨设备在时间和内存方面可能很昂贵!
# We move our tensor to the current accelerator if available
if torch.accelerator.is_available():
tensor = tensor.to(torch.accelerator.current_accelerator())
一些基础操作
索引与切片
基本与numpy相同
import torch
import numpy as np
# 创建三维数组
arr_3d = np.array([
[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]]
])
# 选取每个二维子数组的第 1 行
print(arr_3d[:,0]) # 输出: [[1 2 3] [7 8 9]]
# 选取所有元素的最后一列
print(arr_3d[:,:, -1]) # 输出: [[3 6] [9 12]]
print(arr_3d[..., -1]) # 输出: [[3 6] [9 12]]
联接张量
用于沿给定维度连接一系列张量 , 另请参见 torch.stack
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
算数运算
# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
# ``tensor.T`` returns the transpose of a tensor
y1 = tensor @ tensor.T # @ 是 Python 中用于矩阵乘法的运算符
y2 = tensor.matmul(tensor.T) # matmul 是 torch.Tensor 对象的矩阵乘法方法
y3 = torch.rand_like(y1)
torch.matmul(tensor, tensor.T, out=y3) # torch.matmul 是 PyTorch 提供的用于执行矩阵乘法的函数。out 参数用于指定存储结果的张量
# This computes the element-wise product. z1, z2, z3 will have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)
z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
单元素Tensor
可以将其转换为 Python 数值使用
agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item)) # Out :12.0 <class 'float'>
就地操作
在 PyTorch 中,方法名后面带有下划线 _
的通常表示就地操作(in-place operation) ,会修改原始Tensor
print(f"{tensor} \n")
tensor.add_(5) #将每个元素加 5
print(tensor)
使用Numpy桥接
CPU 和 NumPy 数组上的张量可以共享其底层内存 locations 的 Locations
更改一个位置将更改另一个位置
T e n s o r → N u m p y Tensor \rightarrow Numpy Tensor→Numpy
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]
张量的变化反映在 NumPy 数组中。
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]
N u m p y → T e n s o r Numpy \rightarrow Tensor Numpy→Tensor
n = np.ones(5)
t = torch.from_numpy(n)
NumPy 数组中的更改反映在张量中。
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]