How to predict only one test sample in pytorch model?

I want to give an input to the model and predict the class label.How can I write my code?Please answer.Thanks in advance!

You can use the batch size as 1 if you want to do single sample using pytorch test data loader.

If not you can create tensor of same size and shape as u r input and just pass it as model(input)

Thanks a lot for answering! I get :
predict is: tensor([[0.1559, 0.4340, 0.3785, 0.0226, 0.0032, 0.0519, 0.1933]],
device=‘cuda:0’, grad_fn=)
When tensor is converted to numpy: predict is: [[-0.2556236 0.03545919 -0.38335416 0.3578361 -0.42080054 0.3241588
0.24587154]] .I want to get class label,and how can I predict class label?Thanks in advance!

Try using pred_out, pred_index = torch.max(pred, 1)

Also, try wrapping your inference code with the wrapper: with torch.no_grad():

Thanks a lot! pred_out is: tensor([0.6067])
pred_index is: tensor([1])
The outputs are not same when I run again and again.Why this happens?Please answer how to get same result when it is run again and again.Thanks in advance!

Sure.

For getting deterministic results, you need to set the seed.

Refer to this post: Reproducibility with all the bells and whistles

1 Like

can you explain why:

torch.max(output.data, 1)

works?

I was reading the docs (https://pytorch.org/docs/stable/generated/torch.max.html) and it’s still not entirely clear to me. This is the sentence that doesn’t make sense to me:

Returns a namedtuple (values, indices) where values is the maximum value of each row of the input tensor in the given dimension dim.

I don’t understand what the max value of a row mean given a specific slice of a tensor. Rows only exist in 2D tensors (matrices), at least to me. Can you clarify?