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

peony: <p>This is my code for applying grad-cam:</p>
<pre><code class="lang-auto">
    for idx, (data, target, meta) in enumerate(tqdm(dataloader_test)):
        print('idx', idx)
        data, target = map(lambda x: x.to(device), (data, target))
        output = model(data)
        output[:,5].sum().backward()
        grads=grad[0].cpu().data.numpy().squeeze()
        fmap=activation[0].cpu().data.numpy().squeeze()
        tmp=grads.reshape([grads.shape[0],-1])
        # Get the mean value of the gradients of every featuremap
        weights=np.mean(tmp,axis=1)
        cam = np.zeros(grads.shape[1:])
        for i,w in enumerate(weights):
            cam += w*fmap[i,:]
        #relu
        cam=(cam&gt;0)*cam
        #cam = np.maximum(cam, 0)
        #print("cam.shape",cam.shape)
        #normalize heatmap
        cam=cam/cam.max()*224
        
        # 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]))
            heatmap=cv2.applyColorMap(np.uint8(cam),cv2.COLORMAP_JET)
            cam_img=npic*0.7+heatmap*0.3
            print(cam_img.shape)
            cv2.imwrite('./visualize/map'+str(count)+'.jpg', cam_img)
            count = count + 1
</code></pre>
<p>I have added a loop  <code>for data in idx:</code> because I want to apply the heatmap per sample instead of per batch but I get this error</p>
<p><code>TypeError: 'int' object is not iterable</code></p>
<p>Any ideas how to solve it? Thank you very much</p>

AlphaBetaGamma96: <p>Hi <a class="mention" href="/u/peony">@peony</a>,</p>
<aside class="quote no-group" data-username="peony" data-post="1" data-topic="181433">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/p/e5b9ba/48.png" class="avatar"> peony:</div>
<blockquote>
<p><code>TypeError: 'int' object is not iterable</code></p>
</blockquote>
</aside>
<p>Should your <code>for data in idx</code> line be <code>for data in range(idx)</code>? You can’t iterative over an integer (which is why you get this error)</p>

peony: <p>Hello <a class="mention" href="/u/alphabetagamma96">@AlphaBetaGamma96</a> ,</p>
<p>I tried your suggestion but I get:</p>
<pre><code class="lang-auto">

TypeError: pic should be Tensor or ndarray. Got &lt;class 'int'&gt;.
</code></pre>
<p>I want to for loop over each sample in each batch to be able to apply this operation<br>
<code>npic = np.array(torchvision.transforms.ToPILImage()(data).convert('RGB'))</code></p>

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

peony: <p>I am using it because for each data in batch, I want to apply the heatmap</p>

AlphaBetaGamma96: <p>perhaps change <code>for data in range(idx)</code> to <code>for count in range(idx)</code>, perhaps you shouldn’t have the <code>data</code> object within the iterator?</p>