Pytorch tensor to numpy array

前端 未结 6 1339
名媛妹妹
名媛妹妹 2021-02-01 01:31

I have a pytorch Tensor of size torch.Size([4, 3, 966, 1296])

I want to convert it to numpy array using the following code:

<
6条回答
  •  無奈伤痛
    2021-02-01 02:07

    Your question is very poorly worded. Your code (sort of) already does what you want. What exactly are you confused about? x.numpy() answer the original title of your question:

    Pytorch tensor to numpy array

    you need improve your question starting with your title.

    Anyway, just in case this is useful to others. You might need to call detach for your code to work. e.g.

    RuntimeError: Can't call numpy() on Variable that requires grad.
    

    So call .detach(). Sample code:

    # creating data and running through a nn and saving it
    
    import torch
    import torch.nn as nn
    
    from pathlib import Path
    from collections import OrderedDict
    
    import numpy as np
    
    path = Path('~/data/tmp/').expanduser()
    path.mkdir(parents=True, exist_ok=True)
    
    num_samples = 3
    Din, Dout = 1, 1
    lb, ub = -1, 1
    
    x = torch.torch.distributions.Uniform(low=lb, high=ub).sample((num_samples, Din))
    
    f = nn.Sequential(OrderedDict([
        ('f1', nn.Linear(Din,Dout)),
        ('out', nn.SELU())
    ]))
    y = f(x)
    
    # save data
    y.numpy()
    x_np, y_np = x.detach().cpu().numpy(), y.detach().cpu().numpy()
    np.savez(path / 'db', x=x_np, y=y_np)
    
    print(x_np)
    

    cpu goes after detach. See: https://discuss.pytorch.org/t/should-it-really-be-necessary-to-do-var-detach-cpu-numpy/35489/5


    Also I won't make any comments on the slicking since that is off topic and that should not be the focus of your question. See this:

    Understanding slice notation

提交回复
热议问题