epochs = 100 #训练的次数
loss_epoch = [] # 记录损失
for epoch in range(epochs):
total_loss = 0.0 # 损失初始化为0
train_samples = 0 # 训练样本数初始化为0
for train_x, train_y in dataloader:
# 将1个batch的数据送给模型
y_pred = mode1(train_x.type(torch.float32))
# 计算损失
loss = loss_fn(y_pred, train_y.type(torch.float32))
# 梯度清零
optimizer.zero_grad()
# 自动微分
loss.backward()
# 优化更新参数
optimizer.step()
# 累计损失和样本数
total_loss += loss.item()
train_samples += len(train_y)
# 计算平均损失
epoch_loss = total_loss / train_samples
# 记录平均损失
loss_epoch.append(epoch_loss)
报错:
d:\miniconda3\envs\DeepLearn\Lib\site-packages\torch\nn\modules\loss.py:626: UserWarning: Using a target size (torch.Size([32])) that is different to the input size (torch.Size([32, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.
return F.mse_loss(input, target, reduction=self.reduction)
d:\miniconda3\envs\DeepLearn\Lib\site-packages\torch\nn\modules\loss.py:626: UserWarning: Using a target size (torch.Size([4])) that is different to the input size (torch.Size([4, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.
return F.mse_loss(input, target, reduction=self.reduction)