Python 最佳训练模型未正确使用pytorch保存
我想在训练时保存最好的模型,但它会一直保存第一个训练过的模型Python 最佳训练模型未正确使用pytorch保存,python,deep-learning,nlp,pytorch,Python,Deep Learning,Nlp,Pytorch,我想在训练时保存最好的模型,但它会一直保存第一个训练过的模型 #Train the model for 4 epochs from collections import defaultdict #Define history and best accuracy history = defaultdict(list) best_accuracy = 0 for epoch in range(EPOCHS): print(f'Epoch: {epoch + 1} / {EPOCH
#Train the model for 4 epochs
from collections import defaultdict
#Define history and best accuracy
history = defaultdict(list)
best_accuracy = 0
for epoch in range(EPOCHS):
print(f'Epoch: {epoch + 1} / {EPOCHS}')
print('-' * 15)
#Call the train epoch method
train_acc, train_loss = train_epoch(model, train_data_loader, loss_fn, optimizer, device, scheduler, len(df_train))
#Print the loss and accuracy
print(f'Train loss: {train_loss}, Train accuracy: {train_acc}')
#Call the val epoch method
val_acc, val_loss = eval_model(model, val_data_loader, loss_fn, device, len(df_val))
#Print the validation loss and accuracy
print(f'Validation loss: {val_loss}, Validation accuracy: {val_acc}')
#Update the history dictionary
history['train_acc'].append(train_acc)
history['train_loss'].append(train_loss)
history['val_acc'].append(val_acc)
history['val_loss'].append(val_loss)
if val_acc > best_accuracy:
torch.save(model.state_dict(), 'best_model_state.bin')
best_accuracy = val_acc
这是加载最佳模型文件的代码,我得到了第一个模型的准确性
model.load_state_dict(torch.load("/content/best_model_state.bin"))
test_accuracy = eval_model(model, test_data_loader, loss_fn, device, len(df_test))
print("Test accuracy: ", test_accuracy[0].item())