# AttributeError: 'tuple' object has no attribute 'size'

**URL:** <https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801>\
**Category:** vision\
**Created:** [December 3, 2019, 12:34am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801 "2019-12-03T00:34:00Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![idontknow](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/i/d2c977/32.png) [@idontknow](https://discuss.pytorch.org/u/idontknow)\
**Post date:** [December 3, 2019, 12:34am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/1 "2019-12-03T00:34:00Z")

</div>

Hi, I am working on omniglot images and I am struggling with this error. I believe the problem is with my dataset generation. Please help me figure it out. Here is the dataset code:

```auto
import os
from PIL import Image
import numpy as np
from torch.utils.data import Dataset
import torch
from torchvision import datasets, transforms
class Dataset(Dataset):
    def __init__ (self,data_txt,transformm):
        location_file = open(data_txt, 'r')
        locations = location_file.read().split()
        self.filenames = locations
        self.labels = []
        self.images = []
        self.transform = transformm
        self.path = os.getcwd()
        for address in locations:
            #label creation
            label = address.split('/')[0]
            self.labels.append(label)

    def __len__ (self):
        return len(self.filenames)

    def __getitem__ (self, idx):
        image = Image.open(os.path.join(self.path,'images_background', self.filenames[idx]))
        image = self.transform(image)
        return image, self.labels[idx]

```

Here is the full traceback  
Traceback (most recent call last):  
File “-/Documents/Code/AI/AI\_Learning/Omniglot2/omniglot.py”, line 79, in   
loss = crtieria(outputs, labels)  
File “-AppData\Local\Programs\Python\Python36\lib\site-packages\torch\nn\modules\module.py”, line 541, in **call**  
result = self.forward(\*input, \*\*kwargs)  
File “-\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\nn\modules\loss.py”, line 916, in forward  
ignore\_index=self.ignore\_index, reduction=self.reduction)  
File “-\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\nn\functional.py”, line 2009, in cross\_entropy  
return nll\_loss(log\_softmax(input, 1), target, weight, None, ignore\_index, None, reduction)  
File “-\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\nn\functional.py”, line 1834, in nll\_loss  
if input.size(0) != target.size(0):  
AttributeError: ‘tuple’ object has no attribute ‘size’

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [December 3, 2019, 12:36am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/2 "2019-12-03T00:36:08Z")

</div>

Could you please post the stack trace so that we can have a better look at your issue?  
I cannot find anything obviously wrong in the current code snippet.

---

<div class="post-metadata">

**Author:** ![idontknow](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/i/d2c977/32.png) [@idontknow](https://discuss.pytorch.org/u/idontknow)\
**Post date:** [December 3, 2019, 12:38am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/3 "2019-12-03T00:38:36Z")

</div>

I edited the original post you should be able to see it. Do you need the Network code aswell?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [December 3, 2019, 12:46am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/4 "2019-12-03T00:46:35Z")

</div>

Could you check the `type` of `outputs` and `labels`?  
I guess `labels` is passed as a `tuple` instead of a tensor.  
If so, you could return `labels` in your ` __getitem__ ` as:

```python
torch.tensor(self.labels[idx])

```

---

<div class="post-metadata">

**Author:** ![idontknow](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/i/d2c977/32.png) [@idontknow](https://discuss.pytorch.org/u/idontknow)\
**Post date:** [December 3, 2019, 4:15am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/5 "2019-12-03T04:15:32Z")

</div>

I still have a question, when I make my labels to a tensor like that it gives me error about labels being a string(I know that they are) and I am suppose to make them integers right? Labels must be integers?  
Do you have any suggestions for it?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [December 3, 2019, 4:17am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/6 "2019-12-03T04:17:47Z")

</div>

Yes, `nn.CrossEntropyLoss` expects the target to be a `LongTensor` containing the class indices in the range `[0, nb_classes-1]`.  
If your current labels are stored as string, you might want to use a `dict` and map these strings to the corresponding indices.

---

<div class="post-metadata">

**Author:** ![nickvu](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/n/9f8e36/32.png) [@nickvu](https://discuss.pytorch.org/u/nickvu)\
**Post date:** [May 22, 2020, 4:46pm UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/7 "2020-05-22T16:46:36Z")

</div>

I have a similar issue to this @ptrblck @idontknow  
I have a custom image dataset modeled closely after this official [pytorch tutorial](https://pytorch.org/tutorials/beginner/data_loading_tutorial.html).

The dataset passes a PIL image to a transform function:

```auto
class Resize(object):
    """Resize the image in a sample to a given size.
    Args:
        output_size (int): Desired size in pixels. Yields output_size by output_size image
    """

    def __init__ (self, output_size):
        assert isinstance(output_size, int)
        self.output_size = output_size

    def __call__ (self, sample):
        image = sample

        resized_image = image.resize((self.output_size, self.output_size))

        return resized_image

```

At the point where PIL Image.resize() is called, I get this error:

File “test.py”, line 52, in   
for samples in train\_dataloader:  
File “/Users/nick/opt/anaconda3/lib/python3.7/site-packages/torch/utils/data/dataloader.py”, line 345, in **next**  
data = self.\_next\_data()  
File “/Users/nick/opt/anaconda3/lib/python3.7/site-packages/torch/utils/data/dataloader.py”, line 385, in \_next\_data  
data = self.\_dataset\_fetcher.fetch(index) # may raise StopIteration  
File “/Users/nick/opt/anaconda3/lib/python3.7/site-packages/torch/utils/data/\_utils/fetch.py”, line 44, in fetch  
data = [self.dataset[idx] for idx in possibly\_batched\_index]  
File “/Users/nick/opt/anaconda3/lib/python3.7/site-packages/torch/utils/data/\_utils/fetch.py”, line 44, in   
data = [self.dataset[idx] for idx in possibly\_batched\_index]  
File “/Users/nick/opt/anaconda3/lib/python3.7/site-packages/torch/utils/data/dataset.py”, line 207, in **getitem**  
return self.datasets[dataset\_idx][sample\_idx]  
File “/Users/nick/Projects/Personal\_Projects/CNN/datasets/LDataset.py”, line 52, in **getitem**  
sample = self.transform(sample)  
File “/Users/nick/opt/anaconda3/lib/python3.7/site-packages/torchvision/transforms/transforms.py”, line 70, in **call**  
img = t(img)  
File “/Users/nick/Projects/Personal\_Projects/CNN/datasets/LTransforms.py”, line 24, in **call**  
resized\_image = image.resize((self.output\_size, self.output\_size))  
AttributeError: ‘tuple’ object has no attribute ‘resize’

---

<div class="post-metadata">

**Author:** ![nickvu](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/n/9f8e36/32.png) [@nickvu](https://discuss.pytorch.org/u/nickvu)\
**Post date:** [May 22, 2020, 6:44pm UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/8 "2020-05-22T18:44:03Z")

</div>

OK, this was the problem. Following the [pytorch tutorial](https://pytorch.org/tutorials/beginner/data_loading_tutorial.html) for making a custom dataset, my dataset would pass a sample as a dictionary: `{'image': image, 'label': label}`.  
Then the custom transforms would unpack this and access the image as sample[‘image’].

Interestingly, before being put in the dictionary, type(image) would be \<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=341x341 at 0x12D907210\> as expected. However, when retrieving it from sample[‘image’] it becomes: (\<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=341x341 at 0x12D907210\>,).

So it got converted into a tuple for some reason. Accessing the 0th element of the tuple and passing it along to transform fixes the issue.

---

<div class="post-metadata">

**Author:** ![hsynakcay](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/hsynakcay/32/32922_2.png) [@hsynakcay](https://discuss.pytorch.org/u/hsynakcay)\
**Post date:** [January 2, 2021, 2:29am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/9 "2021-01-02T02:29:31Z")

</div>

#KÜTÜPHANELER

import os  
from pathlib import Path  
from tqdm import tqdm  
from easydict import EasyDict as edict

import torch  
import torch.nn as nn  
import torch.optim as optim  
import torchvision.utils as vutils  
from torchvision import transforms as trans

from data.ms1m import get\_train\_loader  
from data.lfw import LFW

from backbone.arcfacenet import SEResNet\_IR  
from margin.ArcMarginProduct import ArcMarginProduct

from util.utils import save\_checkpoint, test  
#KONFİGÜRASYON

conf = edict()  
conf.train\_root = “dataset/MS1M/MS1M”  
conf.lwf\_test\_root = “dataset/lfw\_aligned\_112/lfw\_aligned\_112”  
conf.lwf\_file\_list =“dataset/lfw\_pair.txt”

conf.mode =“se\_ir” #model  
conf.depth = 50 #derinlik  
conf.margin\_type = “ArcFace”  
conf.feature\_dim = 512  
conf.scale\_siz = 32.0  
conf.batch\_size =96 # bir seferde 96 resim yüklenecek  
conf.lr = 0.01 #modele daha az resim verilirse lr’ düşürülmeli  
conf.milestones = [8,10,12]  
conf.total\_epoch = 14 # model 14 defa resimlerin üstünde geçecek 14 iterasyon sayısı

conf.save\_folder="./saved"  
conf.save\_dir = os.path.join(conf.save\_folder ,conf.mode +’\_’ + str(conf.depth))

conf.device = torch.device (“cuda:0” if torch.cuda.is\_available() else “cpu”) # modelin nerede çalışacağını söylüyoruz

conf.num\_workers = 4  
conf.pin\_memory = True

os.makedirs(conf.save\_dir,exist\_ok=True)

#VERİ YÜKLEME

transform = trans.Compose([  
trans.ToTensor(),  
trans.Normalize(mean=(0.5,0.5,0.5),std=(0.5,0.5,0.5))  
])  
trainloader = class\_num = get\_train\_loader(conf)

print("number of id ",class\_num)

print(trainloader.dataset)

################################################################  
Traceback (most recent call last):  
File “C:/Users/hsyna/Desktop/ArcFace/train.py”, line 59, in   
print(trainloader.dataset[0])  
AttributeError: ‘tuple’ object has no attribute ‘dataset’

I have an error too, how do I fix it?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [January 4, 2021, 3:15am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/10 "2021-01-04T03:15:05Z")

</div>

Your `get_train_loader` method seems to return a `tuple` instead of a `DataLoader` instance, so you would either have to change the return statement or index the returned `tuple`.  
PS: you can post code snippets by wrapping them into three backticks ```, which makes debugging easier. 😉

---

<div class="post-metadata">

**Author:** ![MANISH\_GOYAL](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/manish_goyal/32/35015_2.png) [@MANISH\_GOYAL](https://discuss.pytorch.org/u/MANISH_GOYAL)\
**Post date:** [April 23, 2021, 11:01pm UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/11 "2021-04-23T23:01:44Z")

</div>

from advertorch.attacks import LinfPGDAttack  
import torch.nn as nn  
import numpy as np

use\_cuda = torch.cuda.is\_available()  
device = torch.device(“cuda” if use\_cuda else “cpu”)

# print(use\_cuda)

model.to(device)  
torch.cuda.empty\_cache();

model = model.eval()

# x = torch.from\_numpy(train\_image[0].asnumpy())

# y = torch.from\_numpy(class\_ids[0])

x = torch.Tensor(batch[0][0].asnumpy())  
y = torch.Tensor(batch[6][0].asnumpy())  
print(type(x))

# print("x = ",batch[0][0])

# print(type(y))

# print("y = ",batch[6][0])

adversary = LinfPGDAttack(  
model, loss\_fn=nn.BCEWithLogitsLoss(reduction=“none”), eps=0.3,  
nb\_iter=40, eps\_iter=0.01, rand\_init=False, clip\_min=0.0, clip\_max=1.0,  
targeted=False)  
#nn.CrossEntropyLoss(reduction=“sum”)

x = torch.unsqueeze(x,0)

adv\_untargeted = adversary.perturb(x, y)

Output:

\<class ‘torch.Tensor’\>

* * *

AttributeError Traceback (most recent call last)  
 in   
30 x = torch.unsqueeze(x,0)  
31  
—\> 32 adv\_untargeted = adversary.perturb(x, y)

~.conda\envs\final\lib\site-packages\advertorch\attacks\iterative\_projected\_gradient.py in perturb(self, x, y)  
181 x + delta.data, min=self.clip\_min, max=self.clip\_max) - x  
182  
 → 183 rval = perturb\_iterative(  
184 x, y, self.predict, nb\_iter=self.nb\_iter,  
185 eps=self.eps, eps\_iter=self.eps\_iter,

~.conda\envs\final\lib\site-packages\advertorch\attacks\iterative\_projected\_gradient.py in perturb\_iterative(xvar, yvar, predict, nb\_iter, eps, eps\_iter, loss\_fn, delta\_init, minimize, ord, clip\_min, clip\_max, l1\_sparsity)  
64 for ii in range(nb\_iter):  
65 outputs = predict(xvar + delta)  
—\> 66 loss = loss\_fn(outputs, yvar)  
67 if minimize:  
68 loss = -loss

~.conda\envs\final\lib\site-packages\torch\nn\modules\module.py in \_call\_impl(self, \*input, \*\*kwargs)  
720 result = self.\_slow\_forward(\*input, \*\*kwargs)  
721 else:  
 → 722 result = self.forward(\*input, \*\*kwargs)  
723 for hook in itertools.chain(  
724 \_global\_forward\_hooks.values(),

~.conda\envs\final\lib\site-packages\torch\nn\modules\loss.py in forward(self, input, target)  
626  
627 def forward(self, input: Tensor, target: Tensor) → Tensor:  
 → 628 return F.binary\_cross\_entropy\_with\_logits(input, target,  
629 self.weight,  
630 pos\_weight=self.pos\_weight,

~.conda\envs\final\lib\site-packages\torch\nn\functional.py in binary\_cross\_entropy\_with\_logits(input, target, weight, size\_average, reduce, reduction, pos\_weight)  
2535 reduction\_enum = \_Reduction.get\_enum(reduction)  
2536  
 → 2537 if not (target.size() == input.size()):  
2538 raise ValueError(“Target size ({}) must be the same as input size ({})”.format(target.size(), input.size()))  
2539

AttributeError: ‘tuple’ object has no attribute ‘size’

Please Help ! ☹

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [April 23, 2021, 11:19pm UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/12 "2021-04-23T23:19:53Z")

</div>

Based on the error message it seems you are also passing the model output or target as a `tuple` while a tensor is expected. Check the `type()` of both objects and make sure they are valid tensors before passing it to the criterion.

---

<div class="post-metadata">

**Author:** ![MANISH\_GOYAL](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/manish_goyal/32/35015_2.png) [@MANISH\_GOYAL](https://discuss.pytorch.org/u/MANISH_GOYAL)\
**Post date:** [April 23, 2021, 11:57pm UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/13 "2021-04-23T23:57:40Z")

</div>

![Capture](https://discuss.pytorch.org/uploads/default/original/3X/d/d/dd2f00231ac4060fb3adb07ff97c3cd9b329adfb.png)

This is the value of x and y and their types that i’m passing. x being the input image and y as labels. It seems they are both tensors as needed.

Thank You so much for a quick response sir 🙂

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [April 24, 2021, 12:01am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/14 "2021-04-24T00:01:26Z")

</div>

In that case the model output is most likely creating the issue. 😉

---

<div class="post-metadata">

**Author:** ![MANISH\_GOYAL](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/manish_goyal/32/35015_2.png) [@MANISH\_GOYAL](https://discuss.pytorch.org/u/MANISH_GOYAL)\
**Post date:** [April 24, 2021, 12:07am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/15 "2021-04-24T00:07:46Z")

</div>

Thank You Sir ! I’ll check that 🙂

---

<div class="post-metadata">

**Author:** ![MANISH\_GOYAL](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/manish_goyal/32/35015_2.png) [@MANISH\_GOYAL](https://discuss.pytorch.org/u/MANISH_GOYAL)\
**Post date:** [April 24, 2021, 1:20am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/16 "2021-04-24T01:20:31Z")

</div>

The function is an inbuilt function in advertorch library of pytorch and the attack that I’m trying to do using that is PGD. Would you be able to explain a little what type of output should I expect from my model. Sorry, I am new to pytorch and tensorflows.

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [April 24, 2021, 7:02am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/17 "2021-04-24T07:02:03Z")

</div>

I’m not familiar with `advertorch` and don’t know which outputs are expected, so you could either check the implementation of the model in their repository as well as the documentation or check the output type manually.  
I’m still unsure, if the error is raised by `LinfPGDAttack` or if your model just returns a `tuple` while tensors are expected, so you might also want to check the return type of it.

---

<div class="post-metadata">

**Author:** ![MANISH\_GOYAL](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/manish_goyal/32/35015_2.png) [@MANISH\_GOYAL](https://discuss.pytorch.org/u/MANISH_GOYAL)\
**Post date:** [April 24, 2021, 7:13am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/18 "2021-04-24T07:13:04Z")

</div>

Ok Sir ! Thank You ! 🙂

---

<div class="post-metadata">

**Author:** ![bowen\_wu](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/bowen_wu/32/29527_2.png) [@bowen\_wu](https://discuss.pytorch.org/u/bowen_wu)\
**Post date:** [March 3, 2022, 10:50am UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/19 "2022-03-03T10:50:09Z")

</div>

Hi, I’m using custom dataset inherited from torch.utils.data.Dataset and DataLoader.  
Here is the code snippet and the output.

Note there is a change of type before and after variable assignment.

```auto
def __getitem__ (self, idx):
        chunk = self.chunks[idx]

        print("type:", type(chunk["gesture"][:self.t_prev_20fps+self.window_len_20fps].T))
        gesture = chunk["gesture"][:self.t_prev_20fps+self.window_len_20fps].T,
        print("assigned type:", type(gesture))
        assert 0

Output:
type: <class 'numpy.ndarray'>
assigned type: <class 'tuple'>

```

The variable ‘gesture’ was unintendedly modified to be a tuple. Though using index 0 fixes the issue, could anyone tell me why this is happening?

Is this relevant to the return type of dict?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [March 3, 2022, 8:15pm UTC](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/20 "2022-03-03T20:15:12Z")

</div>

You are appending a comma after the `gesture` definition:

```python
gesture = chunk["gesture"][:self.t_prev_20fps+self.window_len_20fps].T,

```

Remove it and the `tuple` shouldn’t be created.

[Next page](https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801.md?page=2)
