# Pic should be PIL Image or ndarray. Got \<class 'torch.Tensor'\>

**URL:** <https://discuss.pytorch.org/t/pic-should-be-pil-image-or-ndarray-got-class-torch-tensor/94623>\
**Category:** vision\
**Created:** [August 31, 2020, 12:10am UTC](https://discuss.pytorch.org/t/pic-should-be-pil-image-or-ndarray-got-class-torch-tensor/94623 "2020-08-31T00:10:15Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![akcaymert](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/a/7c8e57/32.png) [@akcaymert](https://discuss.pytorch.org/u/akcaymert)\
**Post date:** [August 31, 2020, 12:10am UTC](https://discuss.pytorch.org/t/pic-should-be-pil-image-or-ndarray-got-class-torch-tensor/94623/1 "2020-08-31T00:10:15Z")

</div>

import torch  
import torchvision  
from torch.utils.data import Dataset,DataLoader  
from sklearn import preprocessing

class youtubeFacial(Dataset):

```
def __init__ (self,transform=None):
    
    raw_data = pd.read_csv('../input/fpoints/training.csv')
    raw_data.fillna(0,inplace = True)
    self.n_samples = raw_data.shape[0]
    raw_data['Image'] = raw_data['Image'].apply(lambda img: np.fromstring(img, sep = ' '))
    X = np.vstack(raw_data['Image'].values)
    X = X.reshape(-1, 1, 96, 96)
    X = X.astype('float64')
    self.X = torch.Tensor(X)
    Y = raw_data[raw_data.columns[:-1]].values
    Y = Y.astype('float64')
    self.Y = torch.Tensor(Y) 
    
    self.transform = transform
    
def __getitem__ (self,index):
    return self.transform(self.X[index]),self.transform(self.X[index])

    

def __len__ (self):
    return self.n_samples

```

and  
from torchvision import transforms, utils  
transform = transforms.Compose([  
transforms.Normalize((0.5), (0.5)),  
transforms.ToTensor()])  
dataset = youtubeFacial(transform)  
train\_loader = DataLoader(dataset = dataset,batch\_size = 4,shuffle = True)

but I am encountering this problem in the title during at the training time. how can i solve this problem ?

---

<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:** [August 31, 2020, 1:10am UTC](https://discuss.pytorch.org/t/pic-should-be-pil-image-or-ndarray-got-class-torch-tensor/94623/2 "2020-08-31T01:10:35Z")

</div>

Could you swap the `Normalize` and `ToTensor` transformations and rerun the code?  
I’m not sure, if the error message could be raised by this, so let me know, if this solves the issue.

---

<div class="post-metadata">

**Author:** ![akcaymert](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/a/7c8e57/32.png) [@akcaymert](https://discuss.pytorch.org/u/akcaymert)\
**Post date:** [August 31, 2020, 9:30am UTC](https://discuss.pytorch.org/t/pic-should-be-pil-image-or-ndarray-got-class-torch-tensor/94623/3 "2020-08-31T09:30:06Z")

</div>

Not working , i cant understand Could there be a problem with the data ?

---

<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:** [August 31, 2020, 4:46pm UTC](https://discuss.pytorch.org/t/pic-should-be-pil-image-or-ndarray-got-class-torch-tensor/94623/4 "2020-08-31T16:46:42Z")

</div>

Could you post the complete stack trace, please?

---

<div class="post-metadata">

**Author:** ![akcaymert](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/a/7c8e57/32.png) [@akcaymert](https://discuss.pytorch.org/u/akcaymert)\
**Post date:** [August 31, 2020, 10:39pm UTC](https://discuss.pytorch.org/t/pic-should-be-pil-image-or-ndarray-got-class-torch-tensor/94623/5 "2020-08-31T22:39:41Z")

</div>

Sure , i uploaded to link[Stack Trace](https://prnt.sc/u992eh) and i have tried return value of **getitem** as a dict dtype like pytorch DataLoader documentation

---

<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:** [September 1, 2020, 4:40am UTC](https://discuss.pytorch.org/t/pic-should-be-pil-image-or-ndarray-got-class-torch-tensor/94623/6 "2020-09-01T04:40:13Z")

</div>

Thanks for the stack trace. I would generally recommend to post it here directly as a code snippet instead of uploading pictures, as it would be easier to e.g. check it on a mobile device. 😉

I missed that you are already transforming the data to tensors, which would throw this error:

```python
self.X = torch.Tensor(X)

```

`transforms.ToTensor()` should be applied on `PIL.Image`s or numpy arrays. Since you already are dealing with tensors, you could skip this transformation.

---

<div class="post-metadata">

**Author:** ![akcaymert](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/a/7c8e57/32.png) [@akcaymert](https://discuss.pytorch.org/u/akcaymert)\
**Post date:** [September 1, 2020, 9:23am UTC](https://discuss.pytorch.org/t/pic-should-be-pil-image-or-ndarray-got-class-torch-tensor/94623/7 "2020-09-01T09:23:37Z")

</div>

oh it was completely careless of me , thanks ptrblck 😄 .Although I’m feeding my model as CxHxW type, facing a problem now: Expected tensor to be a tensor image of size (C, H, W). Got tensor.size() = torch.Size([30]).  
The values ​​I give as pictures and labels are as follows; torch.Size([7049, 1, 96, 96])  
torch.Size([7049, 30]) and My model output is 30 feature

**Stack trace ;**  
ValueError Traceback (most recent call last)  
 in   
----\> 1 X,Y = dataset[0].item

in **getitem** (self, index)  
25 def **getitem** (self,index):  
26 X\_transform = self.transform(self.X[index])  
—\> 27 Y\_transform = self.transform(self.Y[index])  
28 return self.X\_transform,self.Y\_transform  
29

/opt/conda/lib/python3.7/site-packages/torchvision/transforms/transforms.py in **call** (self, img)  
59 def **call** (self, img):  
60 for t in self.transforms:  
—\> 61 img = t(img)  
62 return img  
63

/opt/conda/lib/python3.7/site-packages/torchvision/transforms/transforms.py in **call** (self, tensor)  
164 Tensor: Normalized Tensor image.  
165 “”"  
–\> 166 return F.normalize(tensor, self.mean, self.std, self.inplace)  
167  
168 def **repr** (self):

/opt/conda/lib/python3.7/site-packages/torchvision/transforms/functional.py in normalize(tensor, mean, std, inplace)  
192 if tensor.ndimension() != 3:  
193 raise ValueError('Expected tensor to be a tensor image of size (C, H, W). Got tensor.size() = ’  
–\> 194 ‘{}.’.format(tensor.size()))  
195  
196 if not inplace:

ValueError: Expected tensor to be a tensor image of size (C, H, W). Got tensor.size() = torch.Size([30]).

---

<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:** [September 1, 2020, 10:26am UTC](https://discuss.pytorch.org/t/pic-should-be-pil-image-or-ndarray-got-class-torch-tensor/94623/8 "2020-09-01T10:26:28Z")

</div>

As the error message explains, `Normalize` expects an image tensor in the shape `[channels, height, width]` as its input, while you are trying to pass the target tensor to it, which won’t work.  
If you want to normalize the target, you could manually subtract the mean and divide by the standard deviation. However, make sure you really want and need to normalize the target, as it’s often not wanted.

---

<div class="post-metadata">

**Author:** ![akcaymert](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/a/7c8e57/32.png) [@akcaymert](https://discuss.pytorch.org/u/akcaymert)\
**Post date:** [September 1, 2020, 11:38am UTC](https://discuss.pytorch.org/t/pic-should-be-pil-image-or-ndarray-got-class-torch-tensor/94623/9 "2020-09-01T11:38:28Z")

</div>

You are right, thanks for all peter

---

<div class="post-metadata">

**Author:** ![Abhishek\_Maheshwari](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/abhishek_maheshwari/32/42195_2.png) [@Abhishek\_Maheshwari](https://discuss.pytorch.org/u/Abhishek_Maheshwari)\
**Post date:** [September 14, 2021, 9:34pm UTC](https://discuss.pytorch.org/t/pic-should-be-pil-image-or-ndarray-got-class-torch-tensor/94623/10 "2021-09-14T21:34:25Z")

</div>

I am having the same issue. I am new to Python and Pytorch.  
My code has three parts:

- first part is where I define the class function;
- third and final part is using the googlenet model
- following is the second part…followed by the error message:

import torch  
import torchvision  
import torch.nn as nn # All neural network modules, nn.Linear, nn.Conv2d, BatchNorm, Loss functions  
import torch.optim as optim # for all optimization algorithms, SGD, Adam, etc.  
import torchvision.transforms as transforms #transformations we can perform on our dataset  
from torch.utils.data import DataLoader #Gives easier dataset management and creates mini batches

#Set device  
device = torch.device(‘cuda’ if torch.cuda.is\_available() else ‘cpu’)

#hyperparameters  
in\_channel = 3  
num\_classes = 10  
learning\_rate = 1e-3  
batch\_size = 16  
num\_epochs = 1  
img\_size = 224

training\_data = Abhidataset(  
csv\_file = ‘Book1.csv’,  
root\_dir = ‘dataset\_1’,  
transform = transforms.ToTensor()  
)

#Load Data

train\_set, test\_set = torch.utils.data.random\_split(training\_data,[16,5])  
train\_loader = DataLoader(training\_data, batch\_size = batch\_size, shuffle = True, collate\_fn=batch\_size)  
test\_loader = DataLoader(training\_data, batch\_size = batch\_size, shuffle = True, collate\_fn=batch\_size)

## ERROR MESSAGE:

TypeError Traceback (most recent call last)  
 in   
11 losses=  
12  
—\> 13 for batch\_idx, (data, targets) in enumerate(train\_loader):  
14 #Get data to cuda if possible  
15 data = data.to(device=device)

~/opt/anaconda3/lib/python3.8/site-packages/torch/utils/data/dataloader.py in **next** (self)  
519 if self.\_sampler\_iter is None:  
520 self.\_reset()  
 → 521 data = self.\_next\_data()  
522 self.\_num\_yielded += 1  
523 if self.\_dataset\_kind == \_DatasetKind.Iterable and \

~/opt/anaconda3/lib/python3.8/site-packages/torch/utils/data/dataloader.py in \_next\_data(self)  
559 def \_next\_data(self):  
560 index = self.\_next\_index() # may raise StopIteration  
 → 561 data = self.\_dataset\_fetcher.fetch(index) # may raise StopIteration  
562 if self.\_pin\_memory:  
563 data = \_utils.pin\_memory.pin\_memory(data)

~/opt/anaconda3/lib/python3.8/site-packages/torch/utils/data/\_utils/fetch.py in fetch(self, possibly\_batched\_index)  
42 def fetch(self, possibly\_batched\_index):  
43 if self.auto\_collation:  
—\> 44 data = [self.dataset[idx] for idx in possibly\_batched\_index]  
45 else:  
46 data = self.dataset[possibly\_batched\_index]

~/opt/anaconda3/lib/python3.8/site-packages/torch/utils/data/\_utils/fetch.py in (.0)  
42 def fetch(self, possibly\_batched\_index):  
43 if self.auto\_collation:  
—\> 44 data = [self.dataset[idx] for idx in possibly\_batched\_index]  
45 else:  
46 data = self.dataset[possibly\_batched\_index]

in **getitem** (self, idx)  
19 label = self.img\_labels.iloc[idx, 1]  
20 if self.transform:  
—\> 21 image = self.transform(image)  
22 # if self.target\_transform:  
23 # #label = self.target\_transform(label)

~/opt/anaconda3/lib/python3.8/site-packages/torchvision/transforms/transforms.py in **call** (self, pic)  
95 Tensor: Converted image.  
96 “”"  
—\> 97 return F.to\_tensor(pic)  
98  
99 def **repr** (self):

~/opt/anaconda3/lib/python3.8/site-packages/torchvision/transforms/functional.py in to\_tensor(pic)  
100 “”"  
101 if not(F\_pil.\_is\_pil\_image(pic) or \_is\_numpy(pic)):  
 → 102 raise TypeError(‘pic should be PIL Image or ndarray. Got {}’.format(type(pic)))  
103  
104 if \_is\_numpy(pic) and not \_is\_numpy\_image(pic):

TypeError: pic should be PIL Image or ndarray. Got \<class ‘torch.Tensor’\>
