title: How can I fix "ValueError: Target size (torch.Size([128])) must be the same as input size (torch.Size([128, 1]))" error?
body: <p>I am trying to train GAN with below code:</p>
  <pre><code>def run_a_gan(D, G, D_solver, G_solver, discriminator_loss, generator_loss, show_every=250, 
               batch_size=128, noise_size=96, num_epochs=10):
   &quot;&quot;&quot;
   Train a GAN!
   
   Inputs:
   - D, G: PyTorch models for the discriminator and generator
   - D_solver, G_solver: torch.optim Optimizers to use for training the
     discriminator and generator.
   - discriminator_loss, generator_loss: Functions to use for computing the generator and
     discriminator loss, respectively.
   - show_every: Show samples after every show_every iterations.
   - batch_size: Batch size to use for training.
   - noise_size: Dimension of the noise to use as input to the generator.
   - num_epochs: Number of epochs over the training dataset to use for training.
   &quot;&quot;&quot;
   iter_count = 0
   for epoch in range(num_epochs):
     for x, _ in loader_train:
       if len(x) != batch_size:
         continue
       D_solver.zero_grad()
       real_data = x.to(device)
       logits_real = D(2* (real_data - 0.5))
  
       g_fake_seed = sample_noise(batch_size, noise_size, dtype=real_data.dtype, device=real_data.device)
       fake_images = G(g_fake_seed).detach()
       logits_fake = D(fake_images.view(batch_size, 1, 28, 28))
  
       d_total_error = discriminator_loss(logits_real, logits_fake)
       d_total_error.backward()        
       D_solver.step()
  
       G_solver.zero_grad()
       g_fake_seed = sample_noise(batch_size, noise_size, dtype=real_data.dtype, device=real_data.device)
       fake_images = G(g_fake_seed)
  
       gen_logits_fake = D(fake_images.view(batch_size, 1, 28, 28))
       g_error = generator_loss(gen_logits_fake)
       g_error.backward()
       G_solver.step()
  
       if (iter_count % show_every == 0):
         print('Iter: {}, D: {:.4}, G:{:.4}'.format(iter_count,d_total_error.item(),g_error.item()))
         imgs_numpy = fake_images.data.cpu()#.numpy()
         show_images(imgs_numpy[0:16])
         plt.show()
         print()
       iter_count += 1
  
  
  </code></pre>
  <p>with</p>
  <pre><code>fix_random_seed(0)
  
  # Make the discriminator
  D = discriminator().to(device)
  
  # Make the generator
  G = generator().to(device)
  
  # Use the function you wrote earlier to get optimizers for the Discriminator and the Generator
  D_solver = get_optimizer(D)
  G_solver = get_optimizer(G)
  # Run it!
  run_a_gan(D, G, D_solver, G_solver, discriminator_loss, generator_loss)
  
  </code></pre>
  <p>But I got an error that given in this issue:</p>
  <pre><code>
  ---------------------------------------------------------------------------
  
  ValueError                                Traceback (most recent call last)
  
  &lt;ipython-input-19-bc85cbbdf398&gt; in &lt;module&gt;()
       11 G_solver = get_optimizer(G)
       12 # Run it!
  ---&gt; 13 run_a_gan(D, G, D_solver, G_solver, discriminator_loss, generator_loss)
  
  2 frames
  
  &lt;ipython-input-18-701b71b7afd2&gt; in run_a_gan(D, G, D_solver, G_solver, discriminator_loss, generator_loss, show_every, batch_size, noise_size, num_epochs)
       28       logits_fake = D(fake_images.view(batch_size, 1, 28, 28))
       29 
  ---&gt; 30       d_total_error = discriminator_loss(logits_real, logits_fake)
       31       d_total_error.backward()
       32       D_solver.step()
  
  &lt;ipython-input-14-e1f56d791cff&gt; in discriminator_loss(logits_real, logits_fake)
       17   N = logits_real.shape[0]
       18   device = logits_real.device
  ---&gt; 19   loss = (bce_loss(logits_real, torch.ones(N).to(dtype).to(device)))+(bce_loss(logits_fake, torch.zeros(N).to(dtype).to(device)))
       20 
       21   ##############################################################################
  
  /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in binary_cross_entropy_with_logits(input, target, weight, size_average, reduce, reduction, pos_weight)
     2578 
     2579     if not (target.size() == input.size()):
  -&gt; 2580         raise ValueError(&quot;Target size ({}) must be the same as input size ({})&quot;.format(target.size(), input.size()))
     2581 
     2582     return torch.binary_cross_entropy_with_logits(input, target, weight, pos_weight, reduction_enum)
  
  ValueError: Target size (torch.Size([128])) must be the same as input size (torch.Size([128, 1]))
  
  
  </code></pre>
  <p>Actually, before this 2 code snippet, I did not get any error related to my implementation. All expected results return true values but when I'm trying to do these steps I failed, how can I solve this problem? I think the real problem consist of array size, but I do not know where I need to look.</p>
  <p>After Ivan's answer I updated such code snippets like this:</p>
  <pre><code>  logits_real_loss = bce_loss(logits_real, torch.ones(N, 1).to(dtype).to(device))
    logits_fake_loss = bce_loss(logits_fake, torch.zeros(N, 1).to(dtype).to(device))
    loss = logits_real_loss + logits_fake_loss  
  
  </code></pre>
  <p>and</p>
  <pre><code>  N = logits_fake.shape[0]
    device = logits_fake.device
    loss = (bce_loss(logits_fake, torch.ones(N,1).to(dtype).to(device)))
  
  </code></pre>
  <p>But I am getting other value error:</p>
  <pre><code>---------------------------------------------------------------------------
  
  ValueError                                Traceback (most recent call last)
  
  &lt;ipython-input-15-b089f365cd5e&gt; in &lt;module&gt;()
        2   d_loss = discriminator_loss(logits_real, logits_fake)
        3   print(&quot;Maximum error in d_loss: %g&quot;%rel_error(d_loss_true, d_loss))
  ----&gt; 4 test_discriminator_loss(answers['logits_real'], answers['logits_fake'],answers['d_loss_true'])
  
  2 frames
  
  &lt;ipython-input-15-b089f365cd5e&gt; in test_discriminator_loss(logits_real, logits_fake, d_loss_true)
        1 def test_discriminator_loss(logits_real, logits_fake, d_loss_true):
  ----&gt; 2   d_loss = discriminator_loss(logits_real, logits_fake)
        3   print(&quot;Maximum error in d_loss: %g&quot;%rel_error(d_loss_true, d_loss))
        4 test_discriminator_loss(answers['logits_real'], answers['logits_fake'],answers['d_loss_true'])
  
  &lt;ipython-input-14-15d437ae3425&gt; in discriminator_loss(logits_real, logits_fake)
       17   N = logits_real.shape[0]
       18   device = logits_real.device
  ---&gt; 19   logits_real_loss = bce_loss(logits_real, torch.ones(N, 1).to(dtype).to(device))
       20   logits_fake_loss = bce_loss(logits_fake, torch.zeros(N, 1).to(dtype).to(device))
       21   loss = logits_real_loss + logits_fake_loss
  
  /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in binary_cross_entropy_with_logits(input, target, weight, size_average, reduce, reduction, pos_weight)
     2578 
     2579     if not (target.size() == input.size()):
  -&gt; 2580         raise ValueError(&quot;Target size ({}) must be the same as input size ({})&quot;.format(target.size(), input.size()))
     2581 
     2582     return torch.binary_cross_entropy_with_logits(input, target, weight, pos_weight, reduction_enum)
  
  ValueError: Target size (torch.Size([10, 1])) must be the same as input size (torch.Size([10]))
  
  </code></pre>
  <p>how can I proceed?</p>