Getting Input and target elements to fit

g33sean: <p>Hello, I am new to pytorch and I am just trying to get dcgan to work on mnist and I am really struggling with this error Target and input must have the same number of elements. target nelement (128) != input nelement (307328). I used the dataloader given in mnist and here is my code pasted below, it would be greatly appreciated if somebody could point me in the right direction.</p>
<p>import torch<br>
import torch.nn as nn<br>
import torch.optim as optim<br>
from torch.utils.data import DataLoader<br>
import torchvision.datasets as dset<br>
import torchvision.transforms as transforms<br>
import numpy as np<br>
from dcgan import weights_init, Generator, Discriminator</p>
<p>data_dir="/home/sean/Documents/Gans"<br>
params = {<br>
“bsize” : 128,# Batch size during training.<br>
‘imsize’ : 64,# Spatial size of training images. All images will be resized to this size during preprocessing.<br>
‘nc’ : 1,# Number of channles in the training images. For coloured images this is 3.<br>
‘nz’ : 100,# Size of the Z latent vector (the input to the generator).<br>
‘ngf’ : 64,# Size of feature maps in the generator. The depth will be multiples of this.<br>
‘ndf’ : 64, # Size of features maps in the discriminator. The depth will be multiples of this.<br>
‘nepochs’ : 10,# Number of training epochs.<br>
‘lr’ : 0.0002,# Learning rate for optimizers<br>
‘beta1’ : 0.5,# Beta1 hyperparam for Adam optimizer<br>
‘save_epoch’ : 2}# Save step.</p>
<p>device = torch.device(“cuda:0” if(torch.cuda.is_available()) else “cpu”)<br>
print(device, " will be used.\n")</p>
<p>transform = transforms.Compose([transforms.Scale(params[‘imsize’]),<br>
transforms.ToTensor(),<br>
transforms.Normalize([0.5], [0.5])])</p>
<p>mnist_data = dset.MNIST(root=data_dir,<br>
train=True,<br>
transform=transform,<br>
download=True)</p>
<p>dataloader = torch.utils.data.DataLoader(dataset=mnist_data,<br>
batch_size=params[‘bsize’],<br>
shuffle=True,drop_last=True)<br>
print(‘Finish Loading Dataset’)<br>
netG=Generator(params).to(device)<br>
netG.apply(weights_init)<br>
print(netG)</p>
<p>netD=Discriminator(params).to(device)<br>
netD.apply(weights_init)<br>
print(netD)</p>
<p>criterion=nn.BCELoss()</p>
<p>fixed_noise=torch.randn(64,params[‘nz’],1,1,device=device)</p>
<p>real_label = 1<br>
fake_label = 0</p>
<h1>Optimizer for the discriminator.</h1>
<p>optimizerD = optim.Adam(netD.parameters(), lr=params[‘lr’], betas=(params[‘beta1’], 0.999))</p>
<h1>Optimizer for the generator.</h1>
<p>optimizerG = optim.Adam(netG.parameters(), lr=params[‘lr’], betas=(params[‘beta1’], 0.999))</p>
<h2>Training Loop</h2>
<h1>Stores generated images as training progresses.</h1>
<p>img_list = []</p>
<h1>Stores generator losses during training.</h1>
<p>G_losses = []</p>
<h1>Stores discriminator losses during training.</h1>
<p>D_losses = []</p>
<p>iters = 0</p>
<p>print(“Starting Training Loop…”)<br>
print("-"*25)</p>
<p>for epoch in range(params[‘nepochs’]):<br>
for i, data in enumerate(dataloader, 0):<br>
############################<br>
# (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))<br>
###########################<br>
# train with real<br>
netD.zero_grad()<br>
real_cpu = data[0].to(device)<br>
batch_size = real_cpu.size(0)<br>
label = torch.full((batch_size,), real_label, device=device)</p>
<pre><code>    output = netD(real_cpu)
    errD_real = criterion(output, label)
    errD_real.backward()
    D_x = output.mean().item()

    # train with fake
    noise = torch.randn(batch_size, nz, 1, 1, device=device)
    fake = netG(noise)
    label.fill_(fake_label)
    output = netD(fake.detach())
    errD_fake = criterion(output, label)
    errD_fake.backward()
    D_G_z1 = output.mean().item()
    errD = errD_real + errD_fake
    optimizerD.step()
</code></pre>
<p>error is coming from the loss function at criterion</p>

ptrblck: <p>Could you post your model definitions?<br>
PS: you can wrap source code into three backticks (```), which will make it easier to debug <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=9" title=":wink:" class="emoji" alt=":wink:"></p>