Training loss does not decrease and test set is not working

Conca_Giulio: <p>Hi, I have a problem with a project I’m developing with Pytorch (Autoencoders for anomaly detection).</p>
<p>I have a very large dataset composed of over 400000 images, each of size (256,256,4), and in order to handle it in an efficient way I decided to implement a custom Dataset.<br>
The images are contained in a folder called DATASET, which contains two folders: one called “train”, which contains another folder called “clean” with all the images of the training set, and the other called “test”, inside of which there are other folders with images corresponding to specific labels.</p>
<p>The problem is that I train the network for 5 epochs, and the training loss after one epoch is around 0.185. In the following 4 epochs it decreases very slowly and and the end I got a loss that is around 0.1845, so from the first epoch the loss decreases of only 0.0005.</p>
<p>This is how I implement the Autoencoder:</p>
<pre><code class="lang-auto">class Encoder(nn.Module):
    
    def __init__(self, code_size):
        super().__init__()
        
        self.encoder_conv = nn.Sequential(
            nn.Conv2d(in_channels=4, out_channels=32, kernel_size=3, stride=2, padding=1),
            # OUTPUT = (W-F+2P)/S   + 1 = 256 - 3 + 2 / 2  +1 = 128
            nn.ReLU(),
            
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1),
            nn.ReLU(),
        
            nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=2, padding=1),
            nn.ReLU(),
            
            nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=2, padding=1),
            nn.ReLU(),
        )
        
        #flattening
        self.flatten = nn.Flatten(start_dim=1)
        
        #linear layer
        self.encoder_lin = nn.Sequential(
            nn.Linear(in_features=256*16*16, out_features=64),   #we first define a fcl of size 64
            nn.ReLU(),
            nn.Linear(in_features=64, out_features=code_size)   #we reduce its size defining another fcl with size = code_size
        )
        
    def forward(self, x):
        x = self.encoder_conv(x)
        x = self.flatten(x)
        x = self.encoder_lin(x)
        return x
</code></pre>
<p>and this is the decoder:</p>
<pre><code class="lang-auto">class Decoder(nn.Module):
    def __init__(self, code_size):
        super().__init__()
        
        # linear part of the decoder
        self.decoder_lin = nn.Sequential(
            nn.Linear(in_features=code_size, out_features=64),
            nn.ReLU(),
            nn.Linear(in_features=64, out_features=16*16*256),
            nn.ReLU()
        )
        
        # unflattening
        self.unflatten = nn.Unflatten(dim=1, unflattened_size=(256,16,16))
        
        # convolutional part of the decoder, where we execute the transpose convolution operation to undo the convolution
        self.decoder_conv = nn.Sequential(
            nn.ConvTranspose2d(in_channels=256, out_channels=128, kernel_size=3, stride=2, padding=1, output_padding=0),
            nn.ReLU(),
            
            nn.ConvTranspose2d(in_channels=128, out_channels=64, kernel_size=3, stride=2, padding=0, output_padding=0),
            nn.ReLU(),
            
            nn.ConvTranspose2d(in_channels=64, out_channels=32, kernel_size=3, stride=2, padding=0, output_padding=0),
            nn.ReLU(),
            
            nn.ConvTranspose2d(in_channels=32, out_channels=4, kernel_size=3, stride=2, padding=0, output_padding=1),
            nn.ReLU(),
        )
        
    def forward(self, x):
        x = self.decoder_lin(x)
        x = self.unflatten(x)
        x = self.decoder_conv(x)
        x = torch.sigmoid(x)  
        return x
</code></pre>
<p>This is how I check if the reconstructed image has the same size of the original one:</p>
<pre><code class="lang-auto">img, _ = train_dataset[0]
img = img.unsqueeze(0) # Add the batch dimension in the first axis
print('Before encoder:', img.shape)
img_enc = encoder(img)
print('After encoder:', img_enc.shape)
dec_img = decoder(img_enc)
print('After decoder:', dec_img.shape)
</code></pre>
<p>and the output is the following:<br>
Before encoder: torch.Size([1, 4, 256, 256])</p>
<p>After encoder: torch.Size([1, 10])</p>
<p>After decoder: torch.Size([1, 4, 256, 256])</p>
<p>Then I define the parameters for the training</p>
<pre><code class="lang-auto"># definition of a single optimizer for both networks
learning_rate = 5e-4
params_to_optimize = [
    {'params': encoder.parameters()},
    {'params': decoder.parameters(), "lr": 0.1}
]
optim = torch.optim.Adam(params_to_optimize, lr=learning_rate, weight_decay=1e-5)

# Check if the GPU is available
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")

# Moving the networks to the cpu
encoder.to(device)
decoder.to(device)
print("Device: ", device)
loss_function = torch.nn.MSELoss()
</code></pre>
<p>and this is the training function for a single epoch:</p>
<pre><code class="lang-auto">def training_single_epoch(encoder, decoder, loss_fn, device, dataloader, optimizer):
    encoder.train()
    decoder.train()
    losses = []
    for idx, (image_batch, _) in enumerate(dataloader): # iterating over the tuples returned by the dataloader (no need for lables)
        print("\nIdx of training batch:", idx, "/", len(dataloader))
        image_batch = image_batch.to(device)
        encoded_batch = encoder(image_batch)
        decoded_batch = decoder(encoded_batch)
        loss_batch = loss_fn(decoded_batch, image_batch)   # loss between final output and original image
        # backprop
        print("\nBackprop at index", idx, "/", len(dataloader))
        optimizer.zero_grad()
        loss_batch.backward()
        optimizer.step()
        
        # here we are appending the loss of this single batch
        losses.append(loss_batch.detach().cpu().numpy())
 
    # taking the average of the losses over a single epoch (so this is a scalar)
    avg_loss = np.mean(losses) 
    return avg_loss
</code></pre>
<p>What I do to train the model is simply iterating that function for num_epochs times:</p>
<pre><code class="lang-auto">num_epochs = 5

tr_losses = []

for ep in range(num_epochs):
    print("EPOCH:", ep+1, "/", num_epochs)
    # Training
    training_loss = training_single_epoch(encoder=encoder, 
                                          decoder=decoder,
                                          loss_fn=loss_function, 
                                          device=device,
                                          dataloader=train_dataloader,
                                          optimizer=optim)
    print("Training epoch:", ep+1, "/", num_epochs, ". Training loss:", training_loss)
    
    tr_losses.append(training_loss)
    
    # Save network parameters
    torch.save(encoder.state_dict(), 'encoder_params2.pth')
    torch.save(decoder.state_dict(), 'decoder_params2.pth')
</code></pre>
<p>The training takes about 1 hour and 45 minutes and the training loss, as already said, is about 0.185 after the first epoch and then decreases very slowly, and at the end of the 5th epoch it’s around 0.1845.<br>
What is the problem? I really don’t understand what I’m doing wrong.</p>
<p>And also, this is how I retrieve the loss for the validation set (but also for the test set), is it the right way to do it?</p>
<pre><code class="lang-auto"># Using the validation set to obtain the distribution of the losses over a set that has not been used for training
losses_validation = []
idx = 0
for sample in validation_dataset:
    print("Processing sample", idx, "/", len(validation_dataset))
    img = sample[0].unsqueeze(0).to(device)   # adding batch dimension
    label = sample[1]
    encoder.eval()
    decoder.eval()
    with torch.no_grad():
        encoded = encoder(img)
        decoded = decoder(encoded)
    loss = loss_function(img, decoded)
    losses_validation.append(loss)  
    idx = idx + 1
</code></pre>
<p>Another problem is that when I try to do the same with the test set, if it has more than 3500 samples the kernel crashes, I think this is due to the fact that the memory is full.<br>
What am I doiing wrong?</p>
<p>Thank you and sorry for the long text</p>

ptrblck: <p>How did you come up with the different learning rates as they show a huge difference in magnitude (<code>1e-1</code> vs. <code>5e-4</code>)?</p>

Conca_Giulio: <p>To be honest I need to try with different parameters and I just started with the configuration proposed by my professor. Besides the parameters, do you think that the implementation is correct?<br>
Does the way I build the encoder, the decoder and the optimizer make sense? And also the way I fdo the training and the way I feed the validation test to recover the loss?<br>
Because if it is correct I can start focusing on the parameters.</p>
<p>Thank you so much for your time</p>

Conca_Giulio: <p>And also, why in your opinion the kernel dies when I try to feed the test set to the network if its size is greater than 3000? If it is related to the RAM usage, is there a way I can fix it?<br>
Thanks again</p>

ptrblck: <aside class="quote no-group" data-username="Conca_Giulio" data-post="3" data-topic="187152">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/conca_giulio/48/63454_2.png" class="avatar"> Conca_Giulio:</div>
<blockquote>
<p>Besides the parameters, do you think that the implementation is correct?</p>
</blockquote>
</aside>
<p>Using an <code>nn.ReLU</code> as the last layer in <code>self.decoder_conv</code> followed by a <code>sigmoid</code> looks weird and I would probably remove the relu.</p>
<aside class="quote no-group" data-username="Conca_Giulio" data-post="4" data-topic="187152">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/conca_giulio/48/63454_2.png" class="avatar"> Conca_Giulio:</div>
<blockquote>
<p>why in your opinion the kernel dies when I try to feed the test set to the network if its size is greater than 3000? If it is related to the RAM usage, is there a way I can fix it?</p>
</blockquote>
</aside>
<p>Yes, it could be related to an OOM, but you would need to check the actual error message or <code>dmesg</code> to see if the OS killed the process.</p>

Conca_Giulio: <p>Thank you for the suggestion.<br>
The original images are like this:<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/c/c/cc97a09474edb6da10f7a49f565ebecac7afb647.png" data-download-href="https://discuss.pytorch.org/uploads/default/cc97a09474edb6da10f7a49f565ebecac7afb647" title="orig"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/c/c/cc97a09474edb6da10f7a49f565ebecac7afb647_2_503x499.png" alt="orig" data-base62-sha1="tbUgmobDIKQ4ShMIrMJZ2TjVv9l" width="503" height="499" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/c/c/cc97a09474edb6da10f7a49f565ebecac7afb647_2_503x499.png, https://discuss.pytorch.org/uploads/default/optimized/3X/c/c/cc97a09474edb6da10f7a49f565ebecac7afb647_2_754x748.png 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/c/c/cc97a09474edb6da10f7a49f565ebecac7afb647.png 2x" data-dominant-color="000003"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">orig</span><span class="informations">855×849 3.88 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div><br>
and this is the reconstruction I got, which is completely different:<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/4/1/41bed6e5ebde68f148f644894f27674e5c4e32fd.png" data-download-href="https://discuss.pytorch.org/uploads/default/41bed6e5ebde68f148f644894f27674e5c4e32fd" title="reconstr"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/4/1/41bed6e5ebde68f148f644894f27674e5c4e32fd_2_503x499.png" alt="reconstr" data-base62-sha1="9nBUfiD7yuIKGDL5CuDjOdNtEAt" width="503" height="499" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/4/1/41bed6e5ebde68f148f644894f27674e5c4e32fd_2_503x499.png, https://discuss.pytorch.org/uploads/default/optimized/3X/4/1/41bed6e5ebde68f148f644894f27674e5c4e32fd_2_754x748.png 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/4/1/41bed6e5ebde68f148f644894f27674e5c4e32fd.png 2x" data-dominant-color="7F7F7F"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">reconstr</span><span class="informations">855×849 4.8 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>Do you think that the problem might be in the structure of the autoencoder? I think the autoencoder I implemented is not super simple, and therefore I would like to keep this structure (also, to avoid overfitting I don’t want to create a structure that is too complex).<br>
But giving this result, either my autoencoder is too simple, or there is something wrong somewhere and I don’t understand where.</p>
<p>I obtain this kind of reconstruction fafter the training and for all the images inside the training set.<br>
My autoencoder is not able to reconstruct the input images, I don’t know if this is due to the wrong structure of the model or to the parameters I chose for the training, or maybe there is a mistake somewhere else.</p>
<p>What do you think?<br>
Thanks</p>

Conca_Giulio: <p>Update: I didn’t notice the relu after the last layer of the decoder, I removed it and now the performance are better in the sense that I obtain training losses that are way lower: after one epoch I get 0.009, then 0.0019, 0.001882, 0.00180 and 0.00168716.<br>
Also the reconstructed images are better, like this:<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/5/5/55ab6457cd4de518b4f6b2a6bf326826c2a6a10b.png" data-download-href="https://discuss.pytorch.org/uploads/default/55ab6457cd4de518b4f6b2a6bf326826c2a6a10b" title="rec2"><img src="https://discuss.pytorch.org/uploads/default/original/3X/5/5/55ab6457cd4de518b4f6b2a6bf326826c2a6a10b.png" alt="rec2" data-base62-sha1="cdRN0Z8Ex3FPKLeqYfDX8yyylTl" width="503" height="499" data-dominant-color="020203"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">rec2</span><span class="informations">855×849 14.6 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>Is there anything you would do to improve the performances? Maybe I should have used a larger number of epochs, because the autoencoder is still not able to reproduce the input in a good way.<br>
Problem is that the training takes around 2 hours and I don’t have a lot of time to complete this project.<br>
I will try to use a bigger training set, and I will add a linear fully connected layer in order to make the autoencoder more powerful. I will also try to increase the code size (from 16 to 20, not a lot to avoid overfitting) and I will train the model during the night, hopefully it will work. Anything else I should try?</p>
<p>Thanks</p>