Transformation error while training dataset

I am facing the transformation error while calling the train function in CNN model
Here is my code that i used for dataloader

#make a class for data
class OAIDataset(Dataset):
    def __init__(self, csv_file,root_dir, transform=None):
       # = pd.read_csv(csv_file, header=None) = csv_file
       self.root_dir = root_dir
       self.transform = transform

    def __len__(self):
       return len(

    def __getitem__(self,idx):
        img_name = os.path.join(self.root_dir, str(['ID'].iloc[idx])+'.npy')

        patches, p_id = np.load(img_name, allow_pickle= True)

        img_class = int([idx,2])

        side =[idx,1]

        if side ==1:
            image = np.array(patches['R'].astype('uint8'), 'L')                                              #[image['R':side]|image['L':side]]
            image = np.array(patches['L'].astype('uint8'), 'L')

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

        sample = {'image': image, 'grade':img_class}

        return sample

# Define our data transforms
trans = transforms.Compose([ transforms.ToTensor()])
        # Call the dataset
#trans =transforms.ToTensor()
train_data =OAIDataset(train_df,root_dirA,transform=trans )

test_data =OAIDataset(test_df,root_dirA,transform=trans)
from sklearn.model_selection import GroupKFold # import sklearn module

# creating kfold and make indices
kfold = GroupKFold(n_splits=5)

snapshots = []
#iterating over folds
for train_index, val_index in kfold.split(X=train_df, y=grades_dev, groups=groups_dev):
        print("\nTRAIN:", train_index, "TEST:", val_index)

        #Subset of a dataset at saccording to indices

        train_set =, train_index)

        val_set =, val_index)
        #load data(train and validation)
        train_loader =,batch_size=50,shuffle=True,num_workers=0)

        val_loader =,batch_size=50,shuffle=False,num_workers=0)
model = ConvNet()

def train_val_model(model, epoch):
    model.train() #set the model to training mode
    for epoch in range(epoch):
        losses= 0
        closs = 0

        for i,batch in enumerate(train_loader):
            image, grade = batch['image'], batch['grade']

            #image = torch.from_numpy(image).float()

            prediction = model(image)
            loss = costFunction(prediction,grade)
            closs += loss.item()
            # storing the loss
            losses +=[0]
            # losses.append(loss.item())
            # num_times = num_times + 1

Here is my error massages

Traceback (most recent call last):
  File "/home/fatema/Downloads/assignment3/", line 288, in <module>
  File "/home/fatema/Downloads/assignment3/", line 154, in train_val_model
    for i,batch in enumerate(train_loader):
  File "/home/fatema/miniconda3/lib/python3.6/site-packages/torch/utils/data/", line 560, in __next__
    batch = self.collate_fn([self.dataset[i] for i in indices])
  File "/home/fatema/miniconda3/lib/python3.6/site-packages/torch/utils/data/", line 560, in <listcomp>
    batch = self.collate_fn([self.dataset[i] for i in indices])
  File "/home/fatema/miniconda3/lib/python3.6/site-packages/torch/utils/data/", line 107, in __getitem__
    return self.dataset[self.indices[idx]]
  File "/home/fatema/Downloads/assignment3/", line 62, in __getitem__
    image = self.transform(image)
  File "/home/fatema/miniconda3/lib/python3.6/site-packages/torchvision/transforms/", line 49, in __call__
    img = t(img)
  File "/home/fatema/miniconda3/lib/python3.6/site-packages/torchvision/transforms/", line 76, in __call__
    return F.to_tensor(pic)
  File "/home/fatema/miniconda3/lib/python3.6/site-packages/torchvision/transforms/", line 48, in to_tensor
    img = torch.from_numpy(pic.transpose((2, 0, 1)))
ValueError: axes don't match array

Process finished with exit code 1

I tried to implement sever transformation but could not solved.

The raised ValueError is actually raised from the numpy array pic, which apparently does not have three dimensions:

x = np.random.randn(10, 10)
x.transpose((2, 0, 1))
> ValueError: axes don't match array

Could you print the shape of image before passing it to the transformation?

In getitem I have put ’ img_class = int([idx,2])’ in that it showed error like Traceback (most recent call last): File "/home/fatema/Downloads/numpy", line 107, in <module> print(i, sample['image'].shape, sample['grade'].shape) AttributeError: 'int' object has no attribute 'shape'
When i removed 'int ’ from imag_class,i am abled to print image shape but i have not got any information about img_class.
Here is my data set image shape.

Traceback (most recent call last):
  File "/home/fatema/miniconda3/lib/python3.6/site-packages/IPython/core/", line 3325, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-35-b3e87aaa979e>", line 2, in <module>
AttributeError: 'int' object has no attribute 'shape'
(64, 64)

The shape of the image is(64,64)
I am wondering that why i am not getting shape of ‘‘grade’’?

Is the AttributeError thrown for sample['image'] or sample['grade']?
Are you able to get some sample before the original error is raised?
If so, could you add the print statement regarding the shape into __getitem__ directly before calling self.transform and post the output here?

AttributeError seems comes from sample['grade']whenever i call '‘print(sample[‘grade’])’ it gives output*
(64, 64)
I am not quit sure what do you mean by print __getitem__? Now i called the ‘print’ function like this print(sample['image']) print(sample['grade'])
And got the result like thisprint(sample['image']) print(sample['grade']) [[175 177 176 ... 81 79 68] [175 175 174 ... 79 82 79] [173 172 173 ... 76 75 78] ... [122 120 121 ... 45 45 46] [121 121 120 ... 45 45 44] [122 122 123 ... 44 44 43]] 2