for epoch in range(self.opt.num_epoch): iterator = tqdm(self.train_dataloaders[0]) for i_batch, sample_batched in enumerate(iterator): global_step += 1 # switch model to training_tutorials mode, clear gradient accumulators self.model.train() self.optimizer.zero_grad() inputs = [sample_batched[col].to(self.opt.device) for col in self.opt.inputs_cols] outputs = self.model(inputs) targets = sample_batched['polarity'].to(self.opt.device)
时间: 2024-02-14 22:28:53 浏览: 102
这段代码是一个训练过程的循环。它使用了一个外部的参数 `num_epoch` 来指定训练的总轮数。每一轮训练中,通过 `tqdm` 库创建了一个进度条,用于显示训练的进度。然后在每个batch中,通过 `enumerate` 函数获取当前迭代的batch索引和对应的样本数据。接下来,全局步骤 `global_step` 自增1,模型切换到训练模式并清空梯度累加器 `optimizer.zero_grad()`。然后将样本数据放入设备中,并通过模型进行前向传播得到输出 `outputs`。最后将目标值 `polarity` 放入设备中,并进行后续的训练过程。
相关问题
def get_lr(self): if self.last_epoch > self.total_epoch: if self.after_scheduler: if not self.finished: self.after_scheduler.base_lrs = [base_lr * self.multiplier for base_lr in self.base_lrs] self.finished = True return self.after_scheduler.get_lr() return [base_lr * self.multiplier for base_lr in self.base_lrs] if self.multiplier == 1.0: return [base_lr * (float(self.last_epoch) / self.total_epoch) for base_lr in self.base_lrs] else: return [base_lr * ((self.multiplier - 1.) * self.last_epoch / self.total_epoch + 1.) for base_lr in self.base_lrs]
这是 GradualWarmupScheduler 类中的一个 get_lr 方法,该方法用于计算当前轮次(last_epoch)下的学习率。具体来说,该方法首先判断当前轮次是否超过总的训练轮数(total_epoch),如果超过了,就表示开始使用 after_scheduler(如果有),并将每个参数的初始学习率乘以 multiplier 倍数。如果没有 after_scheduler,则直接返回每个参数的初始学习率乘以 multiplier 倍数。如果当前 multiplier 的值为 1.0,则学习率会随着训练的进行线性地递增。否则,学习率会按照一个类似于线性的函数逐渐递增,其中乘积因子 (self.multiplier - 1.) * self.last_epoch / self.total_epoch + 1.
这段代码中加一个test loss功能 class LSTM(nn.Module): def __init__(self, input_size, hidden_size, num_layers, output_size, batch_size, device): super().__init__() self.device = device self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers self.output_size = output_size self.num_directions = 1 # 单向LSTM self.batch_size = batch_size self.lstm = nn.LSTM(self.input_size, self.hidden_size, self.num_layers, batch_first=True) self.linear = nn.Linear(65536, self.output_size) def forward(self, input_seq): h_0 = torch.randn(self.num_directions * self.num_layers, self.batch_size, self.hidden_size).to(self.device) c_0 = torch.randn(self.num_directions * self.num_layers, self.batch_size, self.hidden_size).to(self.device) output, _ = self.lstm(input_seq, (h_0, c_0)) pred = self.linear(output.contiguous().view(self.batch_size, -1)) return pred if __name__ == '__main__': # 加载已保存的模型参数 saved_model_path = '/content/drive/MyDrive/危急值/model/dangerous.pth' device = 'cuda:0' lstm_model = LSTM(input_size=1, hidden_size=64, num_layers=1, output_size=3, batch_size=256, device='cuda:0').to(device) state_dict = torch.load(saved_model_path) lstm_model.load_state_dict(state_dict) dataset = ECGDataset(X_train_df.to_numpy()) dataloader = DataLoader(dataset, batch_size=256, shuffle=True, num_workers=0, drop_last=True) loss_fn = nn.CrossEntropyLoss() optimizer = optim.SGD(lstm_model.parameters(), lr=1e-4) for epoch in range(200000): print(f'epoch:{epoch}') lstm_model.train() epoch_bar = tqdm(dataloader) for x, y in epoch_bar: optimizer.zero_grad() x_out = lstm_model(x.to(device).type(torch.cuda.FloatTensor)) loss = loss_fn(x_out, y.long().to(device)) loss.backward() epoch_bar.set_description(f'loss:{loss.item():.4f}') optimizer.step() if epoch % 100 == 0 or epoch == epoch - 1: torch.save(lstm_model.state_dict(), "/content/drive/MyDrive/危急值/model/dangerous.pth") print("权重成功保存一次")
以下是加入 Test Loss 功能后的代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
class LSTM(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, output_size, batch_size, device):
super().__init__()
self.device = device
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.output_size = output_size
self.num_directions = 1 # 单向LSTM
self.batch_size = batch_size
self.lstm = nn.LSTM(self.input_size, self.hidden_size, self.num_layers, batch_first=True)
self.linear = nn.Linear(65536, self.output_size)
def forward(self, input_seq):
h_0 = torch.randn(self.num_directions * self.num_layers, self.batch_size, self.hidden_size).to(self.device)
c_0 = torch.randn(self.num_directions * self.num_layers, self.batch_size, self.hidden_size).to(self.device)
output, _ = self.lstm(input_seq, (h_0, c_0))
pred = self.linear(output.contiguous().view(self.batch_size, -1))
return pred
if __name__ == '__main__':
# 加载已保存的模型参数
saved_model_path = '/content/drive/MyDrive/危急值/model/dangerous.pth'
device = 'cuda:0'
lstm_model = LSTM(input_size=1, hidden_size=64, num_layers=1, output_size=3, batch_size=256, device=device).to(device)
state_dict = torch.load(saved_model_path)
lstm_model.load_state_dict(state_dict)
# 加载测试数据集
test_dataset = ECGDataset(X_test_df.to_numpy())
test_loader = DataLoader(test_dataset, batch_size=256, shuffle=False, num_workers=0, drop_last=False)
# 定义损失函数和优化器
loss_fn = nn.CrossEntropyLoss()
optimizer = optim.SGD(lstm_model.parameters(), lr=1e-4)
# 开始训练
for epoch in range(200000):
print(f'epoch:{epoch}')
lstm_model.train()
epoch_bar = tqdm(dataloader)
for x, y in epoch_bar:
optimizer.zero_grad()
x_out = lstm_model(x.to(device).type(torch.cuda.FloatTensor))
loss = loss_fn(x_out, y.long().to(device))
loss.backward()
epoch_bar.set_description(f'loss:{loss.item():.4f}')
optimizer.step()
# 计算测试集上的平均损失
test_loss = 0.0
lstm_model.eval()
with torch.no_grad():
for x, y in test_loader:
x_out = lstm_model(x.to(device).type(torch.cuda.FloatTensor))
loss = loss_fn(x_out, y.long().to(device))
test_loss += loss.item() * x.size(0)
test_loss /= len(test_dataset)
print(f'Test Loss: {test_loss:.4f}')
if epoch % 100 == 0 or epoch == epoch - 1:
torch.save(lstm_model.state_dict(), "/content/drive/MyDrive/危急值/model/dangerous.pth")
print("权重成功保存一次")
```
在这个代码中,我们首先加载了测试数据集 `test_dataset` 和测试数据加载器 `test_loader`。在每个 epoch 完成后,我们计算测试集上的平均损失值。我们使用 `lstm_model.eval()` 将模型设为评估模式,并利用 `torch.no_grad()` 避免计算梯度,以加速计算。最后,我们输出测试集上的平均损失值。
阅读全文