for epoch in range(config.num_epochs): print('Epoch [{}/{}]'.format(epoch + 1, config.num_epochs)) for i, (trains, labels) in enumerate(train_iter): outputs = model(trains) model.zero_grad() loss = F.cross_entropy(outputs, labels) loss.backward() optimizer.step() if total_batch % 1 == 0: # 每多少轮输出在训练集和验证集上的效果 true = labels.data.cpu() predic = torch.max(outputs.data, 1)[1].cpu() train_acc = metrics.accuracy_score(true, predic) dev_acc, dev_loss = evaluate(config, model, dev_iter) if dev_loss < dev_best_loss: dev_best_loss = dev_loss torch.save(model.state_dict(), config.save_path) improve = '*' last_improve = total_batch else: improve = '' time_dif = get_time_dif(start_time) msg = 'Iter: {0:>6}, Train Loss: {1:>5.2}, Train Acc: {2:>6.2%}, Val Loss: {3:>5.2}, Val Acc: {4:>6.2%}, Time: {5} {6}' print(msg.format(total_batch, loss.item(), train_acc, dev_loss, dev_acc, time_dif, improve)) text = msg.format(total_batch, loss.item(), train_acc, dev_loss, dev_acc, time_dif, improve) with open(f"{config.model_name}_result.txt", mode="a+", encoding="utf8") as f: f.write(text + "\n") model.train() total_batch += 1 if (total_batch - last_improve > config.require_improvement) or total_batch == 188: # 验证集loss超过1000batch没下降,结束训练 print("No optimization for a long time, auto-stopping...") flag = True break if flag: break test(config, model, test_iter)
时间: 2024-02-15 21:28:24 浏览: 187
optimal_epoch_2layer.zip_Nonlinear Optimal_identification
这是一个训练模型的代码片段,包括了模型的训练和验证过程。首先进入外层循环,遍历所有epoch,每个epoch都输出当前训练的进度。然后进入内层循环,遍历所有batch,对当前batch进行前向传播、反向传播和梯度更新。然后判断是否需要输出训练集和验证集上的效果,计算训练集上的准确率和验证集上的准确率和loss。如果当前的验证集loss比之前的最佳loss还要小,则保存当前的模型参数,并重置last_improve为当前total_batch的值。如果当前验证集loss没有下降,则不保存模型,并将last_improve的值保持不变。在循环过程中,total_batch的值会不断增加,flag标志位用于判断是否已经训练了很久但是效果没有提升,如果flag为True,则跳出循环,结束训练。最后调用了一个test函数,用于对测试集进行测试并输出结果。
阅读全文