Save predictions from pytorch model

Im following the pytorch transfer learning tutorial and applying it to the kaggle seed classification task,Im just not sure how to save the predictions in a csv file so that i can make the submission, Any suggestion would be helpful,This is what i have ,

  use_gpu = torch.cuda.is_available()
 model = models.resnet50(pretrained=True)
for param in model.parameters():
    param.requires_grad = False

num_ftrs = model.fc.in_features
model.fc = torch.nn.Linear(num_ftrs, len(classes))
f use_gpu:
    model = model.cuda()

criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.fc.parameters(), lr=0.001, momentum=0.9)
exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)

loaders = {'train':train_loader, 'valid':valid_loader, 'test': test_loader}

model = train_model(loaders, model, criterion, optimizer, exp_lr_scheduler, num_epochs=50

Inside train_model, there is a loop iterating on batches:

for data in dataloaders[phase]:

Inside this loop is the following:

outputs = model(inputs)
_, preds = torch.max(, 1)

Above, the first line executes the forward pass. Inside outputs, you will find the score for each class, for each example in the batch.
The second line gets the most likely class for each example (the maximum likelihood prediction) by applying a max to the scores.

I suggest that you modify this function, so that you accumulate the predictions in a list. Then, you can convert this list of tensors into one big tensor, that you can then save using numpy.savetxt. You will need to convert the Torch tensor into a numpy array.

Thank you so much Carl,
Will try this out !