IndexError: too many indices for tensor of dimension 0

Hi all,

I am new to python programming in deep learning. And I was executing some basic code of classifying the MNIST dataset, but I keep encountering this error:

IndexError: too many indices for tensor of dimension 0

Each time i execute this part of my code:

dataiter = iter(training_loader)
images, labels = dataiter.next()
fig = plt.figure(figsize = (25, 4))

for idx in np.arange(20):
ax = fig.add_subplot(2, 10, idx+1)
plt.imshow(im_convert(images[idx]))
ax.set_title([labels[idx].item()])

I need HELP with this!

Could you print the shape of images before executing the for loop?
Also, what does im_convert do?

No I am not able to print out the shape of images before the loop. The im_convert method is as follows:

def im_convert(tensor):
image = tensor.clone().detach().numpy()
image = image.transpose(1,2,0)
image = image*np.array((0.5, 0.5, 0.5)) + np.array((0.5, 0.5, 0.5))
image = image.clip(0, 1)
return image

PS i keep getting the same error when i execute this part of my code too:

epochs = 12
for i in range(epochs):
for inputs, labels in training_loader:
inputs = inputs.view(inputs.shape[0], -1)
outputs = model(inputs)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()

The error gets point out at this line – for inputs, labels in training_loader:

while in the first part of code I posted, the error gets point out at this line — images, labels = dataiter.next()

many many thanks for your reply :slight_smile:

In this case the error might be in the Dataset itself, in particular in __getitem__.
Could you post the code of your Dataset or the __getitem__ method?

def __getitem__(self, index):
    """
    Args:
        index (int): Index

    Returns:
        tuple: (image, target) where target is index of the target class.
    """
    img, target = self.data[index], int(self.targets[index])

    # doing this so that it is consistent with all other datasets
    # to return a PIL Image
    img = Image.fromarray(img.numpy(), mode='L')

    if self.transform is not None:
        img = self.transform(img)

    if self.target_transform is not None:
        target = self.target_transform(target)

    return img, target

This is the getitem method in dataset

Thanks for the code!
Could you now print self.data and self.targets before indexing them?
Also, have you defined self.target_transform or is it None?

I printed self.data and self.targets before indexing them.

I have not defined self.target_transform is None

Could you post the output here and if possible the shape of both?