[英]Train model in Pytorch with custom loss how to set up optimizer and run training?
I am new to pytorch and I am trying to run a github model I found and test it.我是 pytorch 的新手,我正在尝试运行我找到的 github 模型并对其进行测试。 So the author's provided the model and the loss function.
所以作者提供了模型和损失函数。
like this:像这样:
#1. Inference the model
model = PhysNet_padding_Encoder_Decoder_MAX(frames=128)
rPPG, x_visual, x_visual3232, x_visual1616 = model(inputs)
#2. Normalized the Predicted rPPG signal and GroundTruth BVP signal
rPPG = (rPPG-torch.mean(rPPG)) /torch.std(rPPG) # normalize
BVP_label = (BVP_label-torch.mean(BVP_label)) /torch.std(BVP_label) # normalize
#3. Calculate the loss
loss_ecg = Neg_Pearson(rPPG, BVP_label)
Dataloading数据加载
train_loader = torch.utils.data.DataLoader(train_set, batch_size = 20, shuffle = True)
batch = next(iter(train_loader))
data, label1, label2 = batch
inputs= data
Let's say I want to train this model for 15 epochs.假设我想将这个模型训练 15 个 epochs。 So this is what I have so far: I am trying to set the optimizer and training, but I am not sure how to tie the custom loss and data loading to the model and set the 15 epoch training correctly.
所以这就是我到目前为止所拥有的:我正在尝试设置优化器和训练,但我不确定如何将自定义损失和数据加载与模型联系起来并正确设置 15 epoch 训练。
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
for epoch in range(15):
....
Any suggestions?有什么建议?
I assumed BVP_label is label1 of train_loader我假设 BVP_label 是 train_loader 的 label1
train_loader = torch.utils.data.DataLoader(train_set, batch_size = 20, shuffle = True)
# Using GPU
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = PhysNet_padding_Encoder_Decoder_MAX(frames=128)
model.to(device)
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
for epoch in range(15):
model.train()
for inputs, label1, label2 in train_loader:
rPPG, x_visual, x_visual3232, x_visual1616 = model(inputs)
BVP_label = label1 # assumed BVP_label is label1
rPPG = (rPPG-torch.mean(rPPG)) /torch.std(rPPG)
BVP_label = (BVP_label-torch.mean(BVP_label)) /torch.std(BVP_label)
loss_ecg = Neg_Pearson(rPPG, BVP_label)
optimizer.zero_grad()
loss_ecg.backward()
optimizer.step()
PyTorch training steps are as belows. PyTorch 训练步骤如下。
in the train loop在火车循环中
As you may know you can also check PyTorch Tutorials.您可能知道,您还可以查看 PyTorch 教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.