pythonnumpypytorch

How to convert a pytorch tensor into a numpy array?


How do I convert a torch tensor to numpy?


Solution

  • copied from pytorch doc:

    a = torch.ones(5)
    print(a)
    

    tensor([1., 1., 1., 1., 1.])

    b = a.numpy()
    print(b)
    

    [1. 1. 1. 1. 1.]


    Following from the below discussion with @John:

    In case the tensor is (or can be) on GPU, or in case it (or it can) require grad, one can use

    t.detach().cpu().numpy()
    

    I recommend to uglify your code only as much as required.