loss_fn = nn.CrossEntropyLoss()
optimizer= optim.Adam(model.parameters(),lr = 0.01)#lr可选,但通常更好地指定指定
def MultiClassNN_train():
n_epochs = 100
batch_size = 10
for epoch in range(n_epochs):
model.train()
total_loss = 0
for i in range(0, len(X_train), batch_size):
Xbatch = X_train[i:i+batch_size]
ybatch = y_train[i:i+batch_size].type(torch.long)
optimizer.zero_grad()
outputs = model(Xbatch)
loss = loss_fn(outputs, ybatch)
loss.backward()
optimizer.step()
total_loss += loss.item()
avg_loss = total_loss / (len(X_train) // batch_size)
print(f'Epoch {epoch+1}, Average Loss: {avg_loss:.4f}')
# Evaluating on test set after each epoch
model.eval()
with torch.no_grad():
test_outputs = model(X_test)
test_loss = loss_fn(test_outputs,
y_test.type(torch.long))
predicted = torch.argmax(test_outputs, dim=1)
accuracy = (predicted == y_test).float().mean()
print(f'Test Loss: {test_loss:.4f}, Accuracy:
{accuracy:.4f}')
help将不胜感激。
您确定您没有更改原始数据集的任何列吗? 我只是尝试重现问题,我在代码中几乎没有更改,并且我的输出不同:
https://colab.research.google.com/drive/1MYV1BPK9WBLAZEQ8TYKIOCQ-PFSLZVSSS?usp =shareing