How to loop through a batch of data to do some operation per sample

This is my code for applying grad-cam:

    for idx, (data, target, meta) in enumerate(tqdm(dataloader_test)):
        print('idx', idx)
        data, target = map(lambda x:, (data, target))
        output = model(data)
        # Get the mean value of the gradients of every featuremap
        cam = np.zeros(grads.shape[1:])
        for i,w in enumerate(weights):
            cam += w*fmap[i,:]
        #cam = np.maximum(cam, 0)
        #normalize heatmap
        # make the heatmap to be a numpy array
        # impath = meta['impath']
        # impath = cv2.imread(impath)
        # print('shape data', data.shape)
        # data = torch.squeeze(data, dim=1)
        # print('squeeze data', data.shape)
        for data in idx:
            print('shape data', data.shape)
            npic = np.array(torchvision.transforms.ToPILImage()(data).convert('RGB'))
            cam = cv2.resize(cam,(npic.shape[1], npic.shape[0]))
            cv2.imwrite('./visualize/map'+str(count)+'.jpg', cam_img)
            count = count + 1

I have added a loop for data in idx: because I want to apply the heatmap per sample instead of per batch but I get this error

TypeError: 'int' object is not iterable

Any ideas how to solve it? Thank you very much

Hi @peony,

Should your for data in idx line be for data in range(idx)? You can’t iterative over an integer (which is why you get this error)

1 Like

Hello @AlphaBetaGamma96 ,

I tried your suggestion but I get:

TypeError: pic should be Tensor or ndarray. Got <class 'int'>.

I want to for loop over each sample in each batch to be able to apply this operation
npic = np.array(torchvision.transforms.ToPILImage()(data).convert('RGB'))

Ok, so that makes senses why it’s now an int. Why are you using the for data in idx loop anyway? It might be best to just remove it?

I am using it because for each data in batch, I want to apply the heatmap

perhaps change for data in range(idx) to for count in range(idx), perhaps you shouldn’t have the data object within the iterator?