Skip to content

Commit 7d219e7

Browse files
authored
Update pytorch with 2024 course.md
1 parent a9214b7 commit 7d219e7

File tree

1 file changed

+157
-0
lines changed

1 file changed

+157
-0
lines changed

docs/ai-ml/pytorch.md

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,3 +88,160 @@ Credit: 原作者 lifeihan
8888
读者可以尝试阅读下列文档学习 PyTorch 框架:
8989

9090
- [动手学深度学习](https://zh-v2.d2l.ai/)
91+
92+
# 2025年新增内容
93+
课程材料仓库:
94+
https://github.com/sast-summer-training-2024/sast2024-DP-and-Pytorch.git
95+
96+
https://www.bilibili.com/video/BV1FSYueTEWw/?share_source=copy_web&vd_source=5f41358f46c6dc60e03c3ff6ca5a8520
97+
## Pytorch的训练方法类似八股文,百分之99的模型都是这么训练的
98+
- 准备数据集
99+
- 定义模型
100+
- 定义损失函数与优化器
101+
- 在模型上进行训练
102+
- 存储模型参数
103+
104+
https://www.bilibili.com/video/BV1FSYueTEWw/?share_source=copy_web&vd_source=5f41358f46c6dc60e03c3ff6ca5a8520
105+
给出了一个具体的训练实例,建议对照着视频链接逐步操作。一些要点如下。
106+
107+
## 一些要点
108+
109+
### 模型定义
110+
在PyTorch中定义神经网络模型需要继承`torch.nn.Module`类,并实现以下两个核心方法:
111+
```python
112+
class TestModel(torch.nn.Module):
113+
def __init__(self):
114+
super().__init__() # 必须调用父类初始化
115+
self.layer = torch.nn.Linear(5, 2) # 定义全连接层
116+
117+
def forward(self, data):
118+
return self.layer(data) # 定义前向传播逻辑
119+
```
120+
- `__init__`方法用于定义网络层结构
121+
- `forward`方法实现具体的前向计算过程
122+
123+
### PyTorch梯度计算与模型优化
124+
梯度计算示例:
125+
```python
126+
test_model = TestModel()
127+
optimizer = torch.optim.SGD(test_model.parameters(), lr=1)
128+
loss_fn = torch.nn.MSELoss()
129+
130+
# 前向计算
131+
data = torch.rand((1, 5))
132+
y = test_model(data)
133+
134+
# 反向传播
135+
loss = loss_fn(torch.randn((1, 2)), y)
136+
loss.backward() # 自动计算梯度
137+
138+
# 参数更新
139+
optimizer.step() # 应用梯度更新
140+
optimizer.zero_grad() # 清空梯度缓存
141+
142+
# 无梯度计算模式
143+
with torch.no_grad():
144+
loss = loss_fn(...) # 不记录计算图
145+
```
146+
关键点:
147+
- `loss.backward()`自动计算梯度并存储在Parameter.grad中
148+
- 优化器通过`step()`方法更新参数
149+
- `zero_grad()`防止梯度累加
150+
- `torch.no_grad()`上下文管理器用于推理阶段
151+
152+
### PyTorch数据集处理
153+
自定义数据集实现:
154+
```python
155+
class MyDataSet(Dataset):
156+
def __init__(self, file: str):
157+
self.data = []
158+
# 多线程数据预处理
159+
with open(file) as fin:
160+
inputlist = list(fin)
161+
tlist = [threading.Thread(target=deal_segment,
162+
args=(inputlist[1000*i:1000*(i+1)], self.data))
163+
for i in range(math.ceil(len(inputlist)/1000))]
164+
for t in tqdm(tlist): # 启动所有线程
165+
t.start()
166+
for t in tlist: # 等待线程完成
167+
t.join()
168+
169+
def __getitem__(self, index):
170+
return self.data[index] # 返回单个样本
171+
172+
def __len__(self):
173+
return len(self.data)
174+
```
175+
数据加载器使用:
176+
```python
177+
train_loader = DataLoader(
178+
dataset=train_set,
179+
batch_size=32,
180+
shuffle=True # 训练集需要打乱顺序
181+
)
182+
```
183+
184+
### 训练实例
185+
模型定义:
186+
```python
187+
class MyModel(nn.Module):
188+
def __init__(self):
189+
super().__init__()
190+
self.emb = nn.Embedding(50000, 64) # 词嵌入层
191+
self.layer1 = nn.Linear(256*64, 64*128)
192+
self.ac1 = nn.ReLU() # 激活函数
193+
self.layer2 = nn.Linear(64*128, 16*16)
194+
self.out = nn.Linear(16*16, 2) # 输出层
195+
196+
def forward(self, data):
197+
hidden = self.emb(data).view(-1, 64*256)
198+
return self.out(self.ac2(...))
199+
```
200+
201+
训练流程:
202+
```python
203+
# 初始化训练组件
204+
model = MyModel().cuda()
205+
loss_fn = nn.CrossEntropyLoss()
206+
optimizer = SGD(model.parameters(), lr=1e-3)
207+
208+
# 训练循环
209+
for epoch in range(EPOCHS):
210+
for batch, (X, y) in enumerate(train_loader):
211+
pred = model(X.cuda())
212+
loss = loss_fn(pred, y.cuda())
213+
214+
loss.backward()
215+
optimizer.step()
216+
optimizer.zero_grad()
217+
218+
# 记录训练指标
219+
if batch % 20 == 0:
220+
wandb.log({
221+
"loss": loss,
222+
"acc": accuracy...
223+
})
224+
225+
# 保存模型
226+
torch.save(model.state_dict(), "model.pt")
227+
```
228+
229+
### 模型推理
230+
```python
231+
model = MyModel()
232+
model.load_state_dict(torch.load('model.pt'))
233+
model.eval() # 设置评估模式
234+
235+
with torch.no_grad(): # 禁用梯度计算
236+
ids = torch.tensor(tokenizer.encode(sentence).ids)
237+
out = torch.nn.functional.softmax(model(ids), dim=-1)
238+
print("预测概率:", out)
239+
print("预测类别:", torch.argmax(out).item())
240+
```
241+
242+
### 作业要求
243+
实现RNN文本分类任务:
244+
1. 使用GRU/LSTM单元(可手写或使用内置类)
245+
2. 支持可变长度输入(根据实际输入长度循环)
246+
3. 分类准确率超过80%
247+
4. 使用可视化工具绘制训练曲线

0 commit comments

Comments
 (0)