Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么在进行任何优化之前,我的错误率很低?_Python_Optimization_Neural Network_Pytorch_Cross Entropy - Fatal编程技术网

Python 为什么在进行任何优化之前,我的错误率很低?

Python 为什么在进行任何优化之前,我的错误率很低?,python,optimization,neural-network,pytorch,cross-entropy,Python,Optimization,Neural Network,Pytorch,Cross Entropy,我正在使用我为一个玩具示例建立的模型训练程序,并尝试在另一个示例中使用它。 唯一的区别是该模型用于回归,因此我使用MSE作为误差标准,现在它用于二元分类,因此我使用BCEWithLogitsLoss 模型非常简单: class Model(nn.Module): def __init__(self, input_size, output_size): super(Model, self).__init__() self.fc1 = nn.Sequentia

我正在使用我为一个玩具示例建立的模型训练程序,并尝试在另一个示例中使用它。 唯一的区别是该模型用于回归,因此我使用MSE作为误差标准,现在它用于二元分类,因此我使用BCEWithLogitsLoss

模型非常简单:

class Model(nn.Module):
    def __init__(self, input_size, output_size):
        super(Model, self).__init__()
        self.fc1 = nn.Sequential( 
            nn.Linear(input_size, 8*input_size),
            nn.PReLU() #parametric relu - same as leaky relu except the slope is learned
        )
        self.fc2 = nn.Sequential( 
            nn.Linear(8*input_size, 80*input_size),
            nn.PReLU()
        )
        self.fc3 = nn.Sequential( 
            nn.Linear(80*input_size, 32*input_size),
            nn.PReLU()
        )
        self.fc4 = nn.Sequential( 
            nn.Linear(32*input_size, 4*input_size),
            nn.PReLU()
        )                   
        self.fc = nn.Sequential( 
            nn.Linear(4*input_size, output_size),
            nn.PReLU()
        )
                        

    def forward(self, x, dropout=dropout, batchnorm=batchnorm):
        x = self.fc1(x)
        x = self.fc2(x)
        x = self.fc3(x)
        x = self.fc4(x)
        x = self.fc(x)

        return x
这就是我运行它的地方:

model = Model(input_size, output_size)

if (loss == 'MSE'):
    criterion = nn.MSELoss()
if (loss == 'BCELoss'):
    criterion = nn.BCEWithLogitsLoss()

optimizer = torch.optim.SGD(model.parameters(), lr = lr)

model.train()
for epoch in range(num_epochs):
    # Forward pass and loss
    train_predictions = model(train_features)
    print(train_predictions)
    print(train_targets)


    loss = criterion(train_predictions, train_targets)
    
    # Backward pass and update
    loss.backward()
    optimizer.step()

    # zero grad before new step
    optimizer.zero_grad()


    train_size = len(train_features)
    train_loss = criterion(train_predictions, train_targets).item() 
    pred = train_predictions.max(1, keepdim=True)[1] 
    correct = pred.eq(train_targets.view_as(pred)).sum().item()
    #train_loss /= train_size
    accuracy = correct / train_size
    print('\nTrain set: Loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        train_loss, correct, train_size,
        100. * accuracy))
然而,当我打印损耗时,由于某种原因,在我进行任何反向传递之前,损耗已经开始非常低(约0.6)!在随后的所有时期,它都保持在如此低的水平。 然而,预测向量看起来像随机垃圾

tensor([[-0.0447],
        [-0.0640],
        [-0.0564],
        ...,
        [-0.0924],
        [-0.0113],
        [-0.0774]], grad_fn=<PreluBackward>)
tensor([[0.],
        [0.],
        [0.],
        ...,
        [0.],
        [0.],
        [1.]])
epoch: 1, loss = 0.6842

> EdT2:在中间块

< P> BCELoss中的精度计算不出错。< /P> p=0.5的伯努利分布的熵为-ln(0.5)=0.693。这是你所期望的损失,如果

  • 您的数据分布均匀
  • 您的网络正在随机猜测
  • 你的人际网络总是预测一个统一的分布

  • 你的模型在第二种情况下。网络目前正在猜测每一个预测都有轻微的负面逻辑。这些将被解释为0类预测。由于您的数据似乎与0标签不平衡,因此您的精度将与总是预测0的模型相同。这只是随机权重初始化的产物。如果你继续重新初始化你的模型,你会发现有时它也会预测1。

    那么我应该改变损失吗?那么我应该用什么样的损失呢?BCELoss很好。但您可能希望通过不同的类权重来平衡它。或者将数据集采样更改为均匀加权。为什么您认为BCELoss的值应该高于您得到的值?我对训练数据进行了一些操作,并删除了足够多的行,因此留下了一个标签为50%0和50%1的文件。我为每个历元添加了一个精度打印,我总是得到训练数据的“精度:7508/15016(50%)”,这让我相信这里没有学习过程(尽管看起来BCELoss正在下降,这已经够奇怪了)。知道该怎么做吗?精度应该计算为<0表示类0,>0表示类1。您的计算精度如何?
    pred=train\u predictions.max(1,keepdim=True)[1]
    应该是
    pred=(train\u predicitions>0).long()
    ,如前一条评论所述。
    if (dataset == 'adult_train.csv'):
        input_size=9
        print_every = 1
        output_size = 1
        lr = 0.001
        num_epochs = 10
        loss='BCELoss'