def train(net, train_iter, val_iter, num_epochs, lr, wd, devices, lr_period, lr_decay): global val_acc, metric trainer = torch.optim.SGD(net.patameters(), lr=lr, momentum=0.9, weight_decay=wd) scheduler = torch.optim.lr_scheduler.StepLR(trainer, lr_period, lr_decay) num_batches, timer = len(train_iter), d2l.Timer() legend = ['train loss', 'train acc'] # 画出来的图的线条标签 if val_iter is not None: legend.append('valid acc') animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs], legend=legend) net = nn.DataParallel(net, device_ids=0).to(device) for epoch in range(num_epochs): # 开始训练 net.train() metric = d2l.Accumulator(3) for i, (features, labels) in enumerate(train_iter): timer.start() l, acc = d2l.train_batch_ch13(net, features, labels, loss, trainer, devices) metric.add(l, acc, labels.shape[0]) timer.stop() if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1: animator.add(epoch + (i + 1) / num_batches, (metric[0] / metric[2], metric[1] / metric[2], None)) if val_iter is not None: val_acc = d2l.evaluate_accuracy_gpu(net, val_iter) animator.add(epoch + 1, (None, None, val_acc)) scheduler.step() measures = (f'train loss {metric[0] / metric[2]:.3f},'f'train acc {metric[1] / metric[2]:.3f}') if val_iter is not None: measures += f', val acc {val_acc :.3f}'检查并优化
时间: 2024-03-05 22:54:26 浏览: 154
在这段代码中,有一个拼写错误,应该是 `net.parameters()` 而不是 `net.patameters()`,所以修改一下即可:
```python
def train(net, train_iter, val_iter, num_epochs, lr, wd, devices, lr_period, lr_decay):
global val_acc, metric
trainer = torch.optim.SGD(net.parameters(), lr=lr, momentum=0.9, weight_decay=wd)
scheduler = torch.optim.lr_scheduler.StepLR(trainer, lr_period, lr_decay)
num_batches, timer = len(train_iter), d2l.Timer()
legend = ['train loss', 'train acc'] # 画出来的图的线条标签
if val_iter is not None:
legend.append('valid acc')
animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs], legend=legend)
net = nn.DataParallel(net, device_ids=0).to(device)
for epoch in range(num_epochs):
# 开始训练
net.train()
metric = d2l.Accumulator(3)
for i, (features, labels) in enumerate(train_iter):
timer.start()
l, acc = d2l.train_batch_ch13(net, features, labels, loss, trainer, devices)
metric.add(l, acc, labels.shape[0])
timer.stop()
if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
animator.add(epoch + (i + 1) / num_batches, (metric[0] / metric[2], metric[1] / metric[2], None))
if val_iter is not None:
val_acc = d2l.evaluate_accuracy_gpu(net, val_iter)
animator.add(epoch + 1, (None, None, val_acc))
scheduler.step()
measures = (f'train loss {metric[0] / metric[2]:.3f},'
f'train acc {metric[1] / metric[2]:.3f}')
if val_iter is not None:
measures += f', val acc {val_acc :.3f}'
```
此外,您也需要确认您已经正确引入了相关的库,比如 `torch`、`nn`、`d2l` 等。
阅读全文