【发布时间】:2021-05-22 17:26:58
【问题描述】:
我正在使用神经网络来预测 Red Wine 数据集的质量,该数据集可用于 UCI 机器学习,使用 Pytorch 和交叉熵损失作为损失函数。
这是我的代码:
input_size = len(input_columns)
hidden_size = 12
output_size = 6 #because there are 6 classes
#Loss function
loss_fn = F.cross_entropy
class WineQuality(nn.Module):
def __init__(self):
super().__init__()
# input to hidden layer
self.linear1 = nn.Linear(input_size, hidden_size)
# hidden layer and output
self.linear2 = nn.Linear(hidden_size, output_size)
def forward(self, xb):
out = self.linear1(xb)
out = F.relu(out)
out = self.linear2(out)
return out
def training_step(self, batch):
inputs, targets = batch
# Generate predictions
out = self(inputs)
# Calcuate loss
loss = loss_fn(out,torch.argmax(targets, dim=1))
return loss
def validation_step(self, batch):
inputs, targets = batch
# Generate predictions
out = self(inputs)
# Calculate loss
loss = loss_fn(out, torch.argmax(targets, dim=1))
return {'val_loss': loss.detach()}
def validation_epoch_end(self, outputs):
batch_losses = [x['val_loss'] for x in outputs]
epoch_loss = torch.stack(batch_losses).mean() # Combine losses
return {'val_loss': epoch_loss.item()}
def epoch_end(self, epoch, result, num_epochs):
# Print result every 100th epoch
if (epoch+1) % 100 == 0 or epoch == num_epochs-1:
print("Epoch [{}], val_loss: {:.4f}".format(epoch+1, result['val_loss']))
model = WineQuality()
def evaluate(model, val_loader):
outputs = [model.validation_step(batch) for batch in val_loader]
return model.validation_epoch_end(outputs)
def fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD):
history = []
optimizer = opt_func(model.parameters(), lr)
for epoch in range(epochs):
# Training Phase
for batch in train_loader:
loss = model.training_step(batch)
loss.backward()
optimizer.step()
optimizer.zero_grad()
# Validation phase
result = evaluate(model, val_loader)
model.epoch_end(epoch, result, epochs)
history.append(result)
return history
loss_value = evaluate(model, valid_dl)
#model=WineQuality()
epochs = 1000
lr = 1e-5
history = fit(epochs, lr, model, train_loader, val_loader)
我可以看到模型很好并且损失减少了。问题是当我必须对示例进行预测时:
def predict_single(input, target, model):
inputs = input.unsqueeze(0)
predictions = model(inputs)
prediction = predictions[0].detach()
print("Input:", input)
print("Target:", target)
print("Prediction:", prediction)
return prediction
input, target = val_df[1]
prediction = predict_single(input, target, model)
这会返回:
Input: tensor([0.8705, 0.3900, 2.1000, 0.0650, 4.1206, 3.3000, 0.5300, 0.2610])
Target: tensor([6.])
Prediction: tensor([ 3.6465, 0.2800, -0.4561, -1.6733, -0.6519, -0.1650])
我想看看这些 logit 与什么相关联,因为我知道最高 logit 与预测的类相关联,但我想查看那个类。我还应用了 softmax 以概率重新调整这些值:
prediction = F.softmax(prediction)
print(prediction)
output = model(input.unsqueeze(0))
_,pred = output.max(1)
print(pred)
输出如下:
tensor([0.3296, 0.1361, 0.1339, 0.1324, 0.1335, 0.1346])
tensor([0])
我不知道那个张量([0])是什么。我期望我的预测标签,如果目标是 6,则为 6.1 之类的值。但我无法获得这个。
【问题讨论】:
-
应用softmax后应该使用
argmax。 -
@Frightera 是的,我做到了,但我总是收到张量([0]),而不是我的课程从 3 到 8
-
可能只是你的模型总是预测类
0。您的模型是否经过适当的训练?你的数据集平衡了吗? -
是的,就像 Ivan 说的 max 函数工作正常。 softmax 函数只计算它是每个类的概率,然后 max 函数查看哪个概率最高,并将该类作为模型的预测输出。您的模型是否经过适当训练?
-
@Ivan 我认为我的模型训练有素......我损失了 0.1
标签: deep-learning neural-network pytorch prediction multilabel-classification