📚 目录

  1. 安装 PyTorch
  2. 张量基础(Tensor)
  3. 自动求导(Autograd)
  4. 构建神经网络
  5. 训练模型流程
  6. 使用 GPU
  7. 保存和加载模型
  8. 参考资料与出站链接

安装 PyTorch

👉 官方安装推荐器:
https://pytorch.org/get-started/locally/

使用 pip:

pip install torch torchvision torchaudio

使用 conda:

conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia


张量基础(Tensor)

import torch

a = torch.tensor([1.0, 2.0, 3.0])
b = torch.ones(3)
c = torch.zeros(3)

print(a + b)
print(a * 2)
print(a.shape)


自动求导(Autograd)

x = torch.tensor(2.0, requires_grad=True)
y = x ** 2
y.backward()
print(x.grad)  # 输出:4.0


构建神经网络

import torch.nn as nn

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc = nn.Linear(10, 1)

    def forward(self, x):
        return self.fc(x)

model = Net()
print(model)


训练模型流程

import torch.optim as optim

criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)

inputs = torch.randn(5, 10)
targets = torch.randn(5, 1)

optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()


使用 GPU

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
inputs = inputs.to(device)


保存和加载模型

torch.save(model.state_dict(), 'model.pth')
model.load_state_dict(torch.load('model.pth'))
model.eval()


参考资料与出站链接


如果你打算把这个整理成文档(PDF、PPT 或博客文章),我也可以帮你排版优化或转换格式。需要吗?