RuntimeError: Boolean value of Tensor with more than one value is ambiguous

hello im trying to work on image colorization using autoencoder and pytorch and i get
this error : this is mi code

class Imataset (Dataset):
    def __init__(self,data):
        self.sample = data   

    def __len__(self):
        return len(self.sample)
    
    def __getitem__(self,index):
        x=self.sample[index][0]     
        y=self.sample[index][1]   
        return x,y

class autoencoder(nn.Module):
    def __init__(self,input_size=256):
      super(autoencoder , self ).__init__() 
      self.encoder = nn.Sequential(
          nn.Conv2d(1,64,kernel_size=3,stride=1,padding=1),
          nn.BatchNorm2d(64),
          nn.ReLU(),
          nn.MaxPool2d(2,2),
          nn.Conv2d(64,128,kernel_size=3,stride=1,padding=1),
          nn.BatchNorm2d(128),
          nn.ReLU(),
          nn.MaxPool2d(2,2)

      )
      self.decoder = nn.Sequential(
          nn.Conv2d(128,64,kernel_size=3,stride=1,padding=1),
          nn.BatchNorm2d(64),
          nn.ReLU(),
          nn.Upsample(scale_factor=2),
          nn.Conv2d(64,2,kernel_size=3,stride=1,padding=1),
          nn.BatchNorm2d(2),
          nn.ReLU(),
          nn.Upsample(scale_factor=2)

      )
        
    def forward(self,x):
       x=self.encoder(x)
       x=self.decoder(x)
       self.encoder.to(device)
       self.decoder.to(device)
       return x

def normalisation(path):
   im = plt.imread(path)
   im = resize(im,(256,256))
   lab = rgb2lab(im)
   x = lab[:,:,0] / 255
   x= np.reshape(x,  (-1,)+x.shape )
   y = lab[:,:,1:] / 128 
   y = np.reshape(y,(2,256,256))
   return x , y 



optimizer=torch.optim.Adam(model.parameters(), lr=1e-3)
criterion =  nn.MSELoss
if torch.cuda.is_available():
  device = torch.device("cuda")
else:
  device = torch.device("cpu")
model = autoencoder().to('cuda')
batch_size=1
num_epochs=1

i = 0 
dataset =  []
path = "/content/drive/Shared drives/redouane/fake_faces/1m_faces_16_17_18_19/1m_faces_16_17_18_19/"
dirList = os.listdir(path)
for dir in dirList:
  for fil in  tqdm(os.listdir(os.path.join(path,dir))):
    path2 = os.path.join(path,dir)
    x , y = normalisation(os.path.join(path2,fil))
    dataset.append((x,y))
    i += 1 
    if(i%20 == 0):
      train_set,test_set = torch.utils.data.random_split(dataset,[15,5])
      train_loader= DataLoader(dataset=train_set,batch_size=batch_size,shuffle=False)    
      test_loader= DataLoader(dataset=test_set,batch_size=batch_size,shuffle=False)
      for epoch in tqdm(range(num_epochs)):
        loss=0
        j=0
        for x,y in train_loader:
           x= x.view(-1,1,256,256).to('cuda')
           y=y.view(-1,2,256,256).to('cuda')
           x = x.float()
           outputs= model(x)
           y = y.type(torch.cuda.LongTensor)
           train_loss=criterion(outputs,y)
           optimizer.zero_grad()
           train_loss.backward()
           optimizer.step()
           loss+= train_loss
           j+=1 
           print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.10f}'.format(epoch+1, num_epochs, j+1, total_step, train_loss))
      dataset = []  
torch.save(model,'model.ckpt')

--------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-82-743878e2b692> in <module>()
     22            outputs= model(x)
     23            y = y.type(torch.cuda.LongTensor)
---> 24            train_loss=criterion(outputs,y)
     25            optimizer.zero_grad()
     26            train_loss.backward()

2 frames
/usr/local/lib/python3.6/dist-packages/torch/nn/_reduction.py in legacy_get_string(size_average, reduce, emit_warning)
     35         reduce = True
     36 
---> 37     if size_average and reduce:
     38         ret = 'mean'
     39     elif reduce:

RuntimeError: Boolean value of Tensor with more than one value is ambiguous

i need help

You would have to create an object of nn.MSELoss for the criterion.
Change

criterion =  nn.MSELoss

to

criterion =  nn.MSELoss()
2 Likes