RuntimeError: stack expects each tensor to be equal size, but got [1, 691, 1228] at entry 0 and [1, 90, 90] at entry 1

Marcelle_Guedes: <p>Hello guys.<br>
I’m trying to run this example for my data.</p><aside class="onebox githubblob">
  <header class="source">
      <a href="https://github.com/eriklindernoren/PyTorch-GAN/blob/master/implementations/lsgan/lsgan.py" target="_blank" rel="noopener nofollow ugc">github.com</a>
  </header>
  <article class="onebox-body">
    <h4><a href="https://github.com/eriklindernoren/PyTorch-GAN/blob/master/implementations/lsgan/lsgan.py" target="_blank" rel="noopener nofollow ugc">eriklindernoren/PyTorch-GAN/blob/master/implementations/lsgan/lsgan.py</a></h4>
<pre><code class="lang-py">import argparse
import os
import numpy as np
import math

import torchvision.transforms as transforms
from torchvision.utils import save_image

from torch.utils.data import DataLoader
from torchvision import datasets
from torch.autograd import Variable

import torch.nn as nn
import torch.nn.functional as F
import torch

os.makedirs("images", exist_ok=True)

parser = argparse.ArgumentParser()
parser.add_argument("--n_epochs", type=int, default=200, help="number of epochs of training")
</code></pre>

  This file has been truncated. <a href="https://github.com/eriklindernoren/PyTorch-GAN/blob/master/implementations/lsgan/lsgan.py" target="_blank" rel="noopener nofollow ugc">show original</a>

  </article>
  <div class="onebox-metadata">
    
    
  </div>
  <div style="clear: both"></div>
</aside>
<p>
My data: Dataset = [1854,1,90,90]</p>
<pre><code class="lang-auto"></code></pre>
<p>‘’’<br>
transform = transforms.Compose([transforms.Grayscale(num_output_channels=1),transforms.ToTensor(),transforms.Normalize([0.5], [0.5])])<br>
dataset2 = datasets.ImageFolder(path_data_training_images, transform=transform)<br>
print(len(dataset2))</p>
<p>dataloader = torch.utils.data.DataLoader(dataset2, batch_size=5, shuffle=True, num_workers=0)<br>
print(“RBC”, np.shape(dataloader), type(dataloader), len(dataloader))</p>
<p>dataiter2 = iter(dataloader)<br>
print(len(dataiter2))<br>
images2, labels2 = dataiter2.next()</p>
<h1>Optimizers</h1>
<p>optimizer_G = torch.optim.RMSprop(generator.parameters(), lr=opt.lr)<br>
optimizer_D = torch.optim.RMSprop(discriminator.parameters(), lr=opt.lr)</p>
<p>Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor</p>
<h1>----------</h1>
<h1>Training</h1>
<h1>----------</h1>
<p>batches_done = 0<br>
for epoch in range(opt.n_epochs):</p>
<pre><code>for i, (imgs, _) in enumerate(dataloader):

    # Configure input
    real_imgs = Variable(imgs.type(Tensor))
    #print("Type of every element:", real_imgs.dtype,"Number of axes:", real_imgs.ndim,"Shape of tensor:", real_imgs.shape)
    print("Total number of elements (64*1*28*28): ", tf.size(real_imgs).numpy())

    # ---------------------
    #  Train Discriminator
    # ---------------------

    optimizer_D.zero_grad()

    # Sample noise as generator input
    z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], opt.latent_dim))))

    # Generate a batch of images
    fake_imgs = generator(z).detach()
    # Adversarial loss
    #print("img_real",np.shape(real_imgs), "img_fake", np.shape(fake_imgs))
    loss_D = -torch.mean(discriminator(real_imgs)) + torch.mean(discriminator(fake_imgs))

    loss_D.backward()
    optimizer_D.step()

    # Clip weights of discriminator
    for p in discriminator.parameters():
        p.data.clamp_(-opt.clip_value, opt.clip_value)

    # Train the generator every n_critic iterations
    if i % opt.n_critic == 0:

        # -----------------
        #  Train Generator
        # -----------------

        optimizer_G.zero_grad()

        # Generate a batch of images
        gen_imgs = generator(z)
        # Adversarial loss
        loss_G = -torch.mean(discriminator(gen_imgs))

        loss_G.backward()
        optimizer_G.step()

        print(
            "[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]"
            % (epoch, opt.n_epochs, batches_done % len(dataloader), len(dataloader), loss_D.item(), loss_G.item())
        )

    if batches_done % opt.sample_interval == 0:
        save_image(gen_imgs.data[:25], "images/%d.png" % batches_done, nrow=5, normalize=True)
    batches_done += 1
</code></pre>
<pre><code class="lang-auto">'''
</code></pre>
<p>But the error appears:<br>
RuntimeError: stack expects each tensor to be equal size, but got [1, 691, 1228] at entry 0 and [1, 90, 90] at entry 1</p>
<p>And when I use collate_fn, I have the following problem:</p>
<p>‘’’</p>
<pre><code class="lang-auto"></code></pre>
<p>def collate_fn(data):<br>
img, bbox = data<br>
zipped = zip(img, bbox)<br>
return list(zipped)<br>
‘’’</p>
<pre><code class="lang-auto"></code></pre>
<p>ValueError: too many values to unpack (expected 2)<br>
Any help please ?</p>

ptrblck: <p>Based on the error message the <code>collate_fn</code> fails to create a batch of the images returned by <code>Dataset.__getitem__</code>, since they have a different spatial resolution.<br>
Often, you would resize the images to a fixed size, which would avoid this error.<br>
To do so, you could use <code>torchvision.transforms.Resize</code> and add it to your <code>transform</code>.</p>
<p>Your second approach of using a custom <code>collate_fn</code> would also work, but note that you would have to pass the images one-by-one to the model if you are not padding or resizing them in the training loop.</p>
<p>PS: you can post code snippets by wrapping them into three backticks ```, which makes debugging a bit easier. <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=9" title=":wink:" class="emoji" alt=":wink:"></p>

Marcelle_Guedes: <p>Thank you! I included</p>
<blockquote>
<p>transforms.Resize((90,90)</p>
</blockquote>
<p>and now it’s working!</p>