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:
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