Machine learning 二元分类回归模型的精度计算
有人能告诉我为什么我的交叉熵损失函数会给出这个错误: 我的准确度方法:Machine learning 二元分类回归模型的精度计算,machine-learning,pytorch,cross-entropy,Machine Learning,Pytorch,Cross Entropy,有人能告诉我为什么我的交叉熵损失函数会给出这个错误: 我的准确度方法: def accuracy(outputs, labels): _, preds = torch.max(outputs, dim=1) return torch.tensor(torch.sum(preds == labels).item() / len(preds)) 定义模型的我的类: class PulsarLogisticRegression(nn.Module): def __init__
def accuracy(outputs, labels):
_, preds = torch.max(outputs, dim=1)
return torch.tensor(torch.sum(preds == labels).item() / len(preds))
定义模型的我的类:
class PulsarLogisticRegression(nn.Module):
def __init__(self):
super().__init__()
self.linear= nn.Linear(input_size,output_size)
def forward(self,xb):
xb = xb.view(xb.size(0), -1)
out= self.linear(xb)
return out
def training_step(self, batch):
inputs, targets = batch
# Generate predictions
out = self(inputs)
# Calcuate loss
loss = F.cross_entropy(out,targets)
return loss
def validation_step(self, batch):
inputs, targets = batch
# Generate predictions
out = self(inputs)
# Calculate loss
loss = F.cross_entropy(out,targets)
acc = accuracy(out, targets) # Calculate accuracy
return {'val_loss': loss, 'val_acc': acc} # fill this
def validation_epoch_end(self, outputs):
batch_losses = [x['val_loss'] for x in outputs]
epoch_loss = torch.stack(batch_losses).mean() # Combine losses
batch_accs = [x['val_acc'] for x in outputs]
epoch_acc = torch.stack(batch_accs).mean() # Combine accuracies
return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}
def epoch_end(self, epoch, result, num_epochs):
# Print result every 20th epoch
print("Epoch [{}], val_loss: {:.4f}, val_acc: {:.4f}".format(epoch, result['val_loss'], result['val_acc']))
错误:交叉熵错误预期为一维目标张量,但为其分配了多个目标
RuntimeError Traceback (most recent call last)
<ipython-input-88-cd9b8a9a3b02> in <module>()
----> 1 result = evaluate(model, val_loader) # Use the the evaluate function
2 print(result) 4 frames
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
2262 .format(input.size(0), target.size(0)))
2263 if dim == 2:
-> 2264 ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
2265 elif dim == 4:
2266 ret = torch._C._nn.nll_loss2d(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: 1D target tensor expected, multi-target not supported
运行时错误回溯(最近一次调用)
在()
---->1结果=评估(模型,val#加载程序)#使用评估功能
2打印(结果)4帧
/nll_损耗中的usr/local/lib/python3.6/dist-packages/torch/nn/functional.py(输入、目标、重量、尺寸平均值、忽略索引、减少、减少)
2262.格式(input.size(0)、target.size(0)))
2263如果尺寸=2:
->2264 ret=torch.\u C.\u nn.nll\u损失(输入、目标、重量、减少量、获取枚举(减少量)、忽略索引)
2265 elif dim==4:
2266 ret=torch.\u C.\u nn.nll\u loss2d(输入、目标、权重、减少、获取枚举(减少)、忽略索引)
运行时错误:需要1D目标张量,不支持多目标
我对机器学习非常陌生,我试图建立一个模型,根据5列数据预测一列数据。列中的值分别为0和1。所以它基本上是一个二元分类模型
我尝试的是:
正如我所说,我对这一领域相当陌生,一些解释建议使用挤压函数以某种方式将目标张量的形状减少到1D,但这似乎会在本课程的其他方法中引入一些其他错误
我正在寻找一个误差函数,这将帮助我获得正确的准确性