jsparrow
jsparrow

Reputation: 1

How to access individual data points of MNIST data and check their size, shape etc from trainset object using torchvision's import dataset

the following code is

    from torchvision import datasets, transforms
    trainset = datasets.MNIST('./data/', download=True, train=True, transform=transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307,), (0.3081,))]))

I would like to visualize the first data point in the trainset variable above. I want to have a look at the pixel values of the first data point by doing something like print(trainset[0]) or check the size by doing print(trainset[0].size) or check the shape by doing print(trainset[0].shape) etc.

Upvotes: 0

Views: 1335

Answers (2)

Madhoolika
Madhoolika

Reputation: 444

To Visualize the data, you could plot it.

import matplotlib.pyplot as plt
plt.imshow(trainset.data[0], cmap='gray')

plot of 1st image in the dataset

To look at the pixel values of the 1st image:

print(trainset.data[0])

To find the shape of 1st image:

trainset.data[0].shape
>>>torch.Size([28, 28])

Instead of 0, you could replace it with any i, where i = size of the dataset

Upvotes: 1

Nicolas Gervais
Nicolas Gervais

Reputation: 36624

For shape:

trainset.data.shape
torch.Size([60000, 28, 28])

For the first example:

trainset.data[0]
tensor([[[0, 0, 0,  ..., 0, 0, 0],
         [0, 0, 0,  ..., 0, 0, 0],
         [0, 0, 0,  ..., 0, 0, 0],
         ...,
         [0, 0, 0,  ..., 0, 0, 0],
         [0, 0, 0,  ..., 0, 0, 0],
         [0, 0, 0,  ..., 0, 0, 0]]], dtype=torch.uint8)

Upvotes: 0

Related Questions