pytorch线性回归
我尝试在ForestFires数据集上运行线性回归。 数据集在Kaggle上可用,我尝试的要点如下: 我面临两个问题:pytorch线性回归,pytorch,Pytorch,我尝试在ForestFires数据集上运行线性回归。 数据集在Kaggle上可用,我尝试的要点如下: 我面临两个问题: 预测输出的形状为32x1,目标数据形状为32 输入形状和目标形状不匹配:输入[32 x 1],目标[32]^ 使用视图,我重塑了预测张量 y_pred=y_pred.view(inputs.shape[0]) 为什么预测张量和实际张量的形状不匹配 pytorch的SGD永远不会收敛。我尝试使用 打印(火炬平均值((y_pred-标签)**2)) 此值不匹配 损失=标准(y_p
torch.unsqueze(labels,1)
或labels.view(-1,1)
手电筒未queze(输入、变暗、输出=无)→ 张量
返回在指定位置插入尺寸为1的新张量
返回的张量与此张量共享相同的基础数据
问题2
查看代码后,我意识到您已将size\u average
param添加到MSELOST中:
criterion = torch.nn.MSELoss(size_average=False)
平均尺寸(bool,可选)–不推荐使用(参见缩减)。默认情况下,损失是批次中每个损失元素的平均值。注意,对于某些损失,每个样品有多个元素。如果字段大小_average设置为False,则每个小批量的损失相加。当reduce为False时忽略。默认值:True
这就是为什么两个计算值不匹配的原因。这是示例代码:
import torch
import torch.nn as nn
loss1 = nn.MSELoss()
loss2 = nn.MSELoss(size_average=False)
inputs = torch.randn(32, 1, requires_grad=True)
targets = torch.randn(32, 1)
output1 = loss1(inputs, targets)
output2 = loss2(inputs, targets)
output3 = torch.mean((inputs - targets) ** 2)
print(output1) # tensor(1.0907)
print(output2) # tensor(34.9021)
print(output3) # tensor(1.0907)
伟大的这解决了问题1。但是,使用torch.mean((y_pred-标签)**2)计算的损耗与损耗=标准(y_pred,标签)不匹配。你能告诉我它们有什么不同吗?@Chandra我意识到你的代码使用了
size\u average
param。我已经更新了详细的答案是的。非常感谢。
import torch
import torch.nn as nn
loss1 = nn.MSELoss()
loss2 = nn.MSELoss(size_average=False)
inputs = torch.randn(32, 1, requires_grad=True)
targets = torch.randn(32, 1)
output1 = loss1(inputs, targets)
output2 = loss2(inputs, targets)
output3 = torch.mean((inputs - targets) ** 2)
print(output1) # tensor(1.0907)
print(output2) # tensor(34.9021)
print(output3) # tensor(1.0907)