简体   繁体   中英

pytorch: Convert a tuple of FloatTensors into a numpy array

I just got a torchvision.datasets object with MNIST data

train_dataset= dsets.MNIST(root='./data',train=True,transform=transforms.ToTensor(),download=True)

I want to convert this tuple into a set of numpy arrays of shape 60000x28x28 and labels of 60000

I know that the form that the data is provided, can be directly applied into a pytorch neuron in order to be used as training data, but I would like to convert this data into numpy arrays.

the first thing I did was to divide the tuples of (data,labels) with zip(*train_dataset)

data,labels = zip(*train_dataset)

labels is easy to convert into a numpy array, however I have not been able to convert "data" into a numpy array the way I would like. When I try to convert all of the data into numpy.array like

data[:].numpy()

I receive an error telling me 'tuple' object has no attribute 'numpy'. and if I convert this data[:] into numpy, just the first dimension (the 60000 data) is converted into numpy.array but the rest remains as Tensors.

I can convert all of the data using a loop (actually I did it) and it works, however it is really slow. Has anyone done any conversion like this before?

Thanks.

Maybe something like this will work for you:

train_dataset.train_data.numpy()  #contains (60000, 28, 28) numpy array
train_dataset.train_labels.numpy() # contains labels

It seems like there are two tensor in data. You need to check if the variable data only contains one tensor, then the command tensor.numpy() should work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM