Error in Dataloader: AttributeError: 'int' object has no attribute 'numel'

NanaYang2929: <p>Hi, I am new to ML (and here), and this error has been haunting me for days. <img src="https://discuss.pytorch.org/images/emoji/apple/skull_and_crossbones.png?v=9" title=":skull_and_crossbones:" class="emoji" alt=":skull_and_crossbones:"> <img src="https://discuss.pytorch.org/images/emoji/apple/skull_and_crossbones.png?v=9" title=":skull_and_crossbones:" class="emoji" alt=":skull_and_crossbones:"> <img src="https://discuss.pytorch.org/images/emoji/apple/skull_and_crossbones.png?v=9" title=":skull_and_crossbones:" class="emoji" alt=":skull_and_crossbones:"><br>
I have checked (almost) all the solutions online but none solves my problem.<br>
Any help will be very much appreciated.</p>
<p>I am using a CNN to classify images into 11 classes.<br>
The challenge is that I have only a portion of the training set which are labelled images(about 3000)<br>
, the others are unlabelled (about 6000).<br>
I am trying to do the labelling before each training epoch, and if the probability for a data is higher than a certain threshold (eg. 0.7), I’ll add it (the image) and its corresponding label into two lists</p>
<pre><code class="lang-auto">def get_pseudo_labels(dataset, model, threshold=0.7):
    ...
    samples = []
    pseudolabels= []
    for batch in dataloader: # the labelled portion 
        img, _ = batch.      # Size [128(batch size), 3, 128, 128] 
        with torch.no_grad():
            logits = model(img.to(device))
        probs = softmax(logits)          # Size [128, 11]
        (max_probs, max_indices) = torch.max(probs, dim = 1)     
        for i, (max_prob, max_idx) in enumerate(zip(max_probs, max_indices)): 
            if max_prob &gt; threshold: 
              samples.append(img[i].cpu())      # img[i] tensor of size (3, 128, 128)
              pseudolabels.append(max_idx.cpu())   # 1 of the 11 classes  # img[i] tensor of size (1)
              #  have check the two lists' lengths, they are the same

    if len(samples) &gt; 1:        
      dataset = MyDataset(samples, pseudolabels)  # pseudo set
    else:
      dataset = None
</code></pre>
<p>then send the lists to instantiate a <code>MyDataset</code> class object like this:</p>
<pre><code class="lang-auto">from torch.utils.data import Dataset
class MyDataset(Dataset):
    def __init__(self, X, y=None):
        # Stacking tensors into one tensor
        self.data = torch.stack(X)  # size: torch.Size([98, 3, 128, 128]). # 3, 128, 128 is one img size 
        self.label = torch.stack(y)  # size: torch.Size([98]) # the 98 is an arbitrary number of the data with prob &gt; 0.7
    def __getitem__(self, idx):
        return self.data[idx], self.label[idx]
    def __len__(self):
        return len(self.data)
</code></pre>
<p>The code for training:</p>
<pre><code class="lang-auto">for epoch in range(n_epochs):

    if do_semi:   # if do semi-supervised labelling, i.e. feed the pseudo labels back to training set 
        pseudo_set = get_pseudo_labels(unlabeled_set, model)
        if pseudo_set != None:
          concat_dataset = ConcatDataset([train_set, pseudo_set]) 
          train_loader = DataLoader(concat_dataset, batch_size=batch_size, shuffle= True , num_workers=2, pin_memory=True)
        else:
          train_loader = DataLoader(train_set, batch_size=batch_size, shuffle= True , num_workers=2, pin_memory=True)
    # ---------- Training ----------
    model.train()
    # Iterate the training set by batches.
    for idx, batch in enumerate(train_loader):
         imgs, labels = batch   
         # if the batch has no problem, it yields:  
         # imgs shape: torch.Size([128, 3, 128, 128]) &lt;class 'torch.Tensor'&gt;
         # labels shape: torch.Size([128]) &lt;class 'torch.Tensor'&gt;
</code></pre>
<p>Here, in the beginning of the for loop, is where the error occurs.</p>
<pre><code class="lang-auto">AttributeError: Caught AttributeError in DataLoader worker process 1.
...
File "/usr/local/lib/python3.7/dist-packages/torch/utils/data/_utils/collate.py", line 52, in default_collate
    numel = sum([x.numel() for x in batch])
  File "/usr/local/lib/python3.7/dist-packages/torch/utils/data/_utils/collate.py", line 52, in &lt;listcomp&gt;
    numel = sum([x.numel() for x in batch])
AttributeError: 'int' object has no attribute 'numel'
</code></pre>
<p>The error looks like I have passed something which is not a tensor into the dataset. I have checked almost everywhere; the pseudo set is all fine, the error occurs in the duration of the dataloader is producing a batch. The weird part is, this error does not appear every time a pseudo set is added into training, it comes in the latter period but sooner or later, it definitely comes. Please, could anyone tell me where could it go wrong? Or recommend a better way to wrap up the pseudo set?<br>
Again, any help is very VERY MUCH appreciated. <img src="https://discuss.pytorch.org/images/emoji/apple/sob.png?v=9" title=":sob:" class="emoji" alt=":sob:"> <img src="https://discuss.pytorch.org/images/emoji/apple/sob.png?v=9" title=":sob:" class="emoji" alt=":sob:"> <img src="https://discuss.pytorch.org/images/emoji/apple/sob.png?v=9" title=":sob:" class="emoji" alt=":sob:"> <img src="https://discuss.pytorch.org/images/emoji/apple/sob.png?v=9" title=":sob:" class="emoji" alt=":sob:"> <img src="https://discuss.pytorch.org/images/emoji/apple/sob.png?v=9" title=":sob:" class="emoji" alt=":sob:"> <img src="https://discuss.pytorch.org/images/emoji/apple/sob.png?v=9" title=":sob:" class="emoji" alt=":sob:"></p>

NanaYang2929: <p>Update:<br>
Don’t know why but I kind of solve the problem…?<br>
Instead of sending two lists into the dataset, I send two numpy arrays and alter the dataset class as the following:</p>
<pre><code class="lang-auto">class MyDataset(Dataset):
    def __init__(self, X, y=None):
        self.data = torch.from_numpy(X).float()
        if y is not None:
            y = y.astype(np.int)
            self.label = torch.LongTensor(y)
        else:
            self.label = None
    def __getitem__(self, idx):
        if self.label is not None:
            return self.data[idx], self.label[idx] # -&gt; a batch 
        else:
            return self.data[idx]

    def __len__(self):
        return len(self.data)
</code></pre>
<p>And then I define my own simple collate function that works inside the dataloader (its work is outputting batches) like this:</p>
<pre><code class="lang-auto">def my_collate(batch):
    """Define collate_fn myself because the default_collate_fn throws errors like crazy"""
    # item: a tuple of (img, label)
    data = [item[0] for item in batch]
    target = [item[1] for item in batch]
    data = torch.stack(data)
    target = torch.LongTensor(target)
    return [data, target]
</code></pre>
<p>then use mine instead of the default_collate_fn:</p>
<pre><code class="lang-auto">train_loader = DataLoader(concat_dataset, batch_size=batch_size, collate_fn = my_collate, shuffle= True, num_workers=2, pin_memory=True)
</code></pre>
<p>Then it works. At least for the following training I don’t get errors anymore. Still dunno what causes that original error but hope ppl with the same problem find this useful.</p>

Joshua_Pan: <p>I think it’s because of the difference between the output of   <code>__getitem__</code> method of Concated two datasets( <code>train_set</code> and <code>pseudo_set</code>).  <code>__getitem__</code>  of <code>train_set</code> yields (image, int label) while <code>__getitem__</code> of <code>pseudo_set</code> yields (image, tensor label). After two datasets are concated, a set of indices of the final dataset yields a list of output of <code>__getitem__</code>. But in this case the outputs’ structures probably don’t agree.( (tensor,int) differs from (tensor, tensor)).And Dataloader doesn’t work. However, if you’re lucky enough to have all outputs of identical structure, it will work for a while. The new <code>collate</code> function you define apply <code>longtensor</code> to all <code>targets</code>, which cancels the difference between two kinds of outputs, I guess.</p>
<pre><code class="lang-auto">import torch
a = [1,torch.tensor(2)]
print(torch.LongTensor(a))
</code></pre>
<p>And this will yield <code>tensor([1, 2])</code>.</p>

NanaYang2929: <p>Exactly. I figured it out after posting the first reply(because the code of the original dataset is kinda not straightforward to me, it is a class of datasetfolder, and I couldn’t really look into it to see its datatype directly). Thank you for pointing it out!! <img src="https://discuss.pytorch.org/images/emoji/apple/sob.png?v=9" title=":sob:" class="emoji" alt=":sob:"> <img src="https://discuss.pytorch.org/images/emoji/apple/orange_heart.png?v=9" title=":orange_heart:" class="emoji" alt=":orange_heart:"></p>

Lemontree_YC: <p>You can read the source code of the class that you import your data, just like DatasetFolder.<br>
DatasetFolder use a list as labels, so you need to use the same type on your own labels.</p>