Pytorch RuntimeError: size mismatch
I get the following error when I try to run this code for training a GAN for prediction:


  RuntimeError: size mismatch, m1: [128 x 1], m2: [1392 x 2784] at C:\w\1\s\tmp_conda_3.7_021303\conda\conda-bld\pytorch_1565316900252\work\aten\src\TH/generic/THTensorMath.cpp:752


Please comment if you see any other mistakes in the code or if you have some tips in general.

# Sample indices
def sample_idx(m, n):
    A = np.random.permutation(m)
    idx = A[:n]
    return idx

class Discriminator(nn.Module):
    def __init__(self):
        super(Discriminator, self).__init__()
        self.fc1 = nn.Linear(in_features = dim, out_features = dim*2)
        self.fc2 = nn.Linear(in_features = dim*2, out_features = dim)
        self.fc3 = nn.Linear(in_features = dim, out_features = int(dim/2))
        self.fc4 = nn.Linear(in_features = int(dim/2), out_features = 1)
        self.relu = nn.LeakyReLU(0.2)
        self.sigmoid = nn.Sigmoid()
        self.init_weight()

    def init_weight(self):
        layers = [self.fc1, self.fc2, self.fc3]
        [nn.init.xavier_normal_(layer.weight) for layer in layers]

    def forward(self, x):
        x = self.relu(self.fc1(x))
        x = self.relu(self.fc2(x))
        x = self.relu(self.fc3(x))
        x = self.sigmoid(self.fc4(x))
        return x



class Generator(nn.Module):
    def __init__(self):
        super(Generator, self).__init__()
        self.fc1 = nn.Linear(in_features = dim, out_features = dim*2)
        self.fc2 = nn.Linear(in_features = dim*2, out_features = dim)
        self.fc3 = nn.Linear(in_features = dim, out_features = int(dim/2))
        self.fc4 = nn.Linear(in_features = int(dim/2), out_features = 1)
        self.relu = nn.LeakyReLU(0.2)
        self.init_weight()

    def init_weight(self):
        layers = [self.fc1, self.fc2, self.fc3]
        [nn.init.xavier_normal_(layer.weight) for layer in layers]

    def forward(self, x):
        x = self.relu(self.fc1(x))
        x = self.relu(self.fc2(x))
        x = self.relu(self.fc3(x))
        x = self.fc4(x)
        return x

# 1. Mini batch size
mb_size = 128

# 4. Loss Hyperparameters
alpha = 10

# 5. Input Dim (Fixed)
dim = data.shape[1] - 1

# 6. Train Test Split
train_n = int(199476 * 0.8)
test_n = 199476 - int(199476 * 0.8)

X_train = data[:train_n,:-1]
y_train = data[:train_n, -1]

X_test = data[train_n:,:-1]
y_test = data[train_n:, -1]

# Nets
D = Discriminator()
G = Generator()

# Optimizers
optimD = torch.optim.Adam(D.parameters(), lr = 0.001)
optimG = torch.optim.Adam(G.parameters(), lr = 0.001)

# Loss
mse_loss = nn.MSELoss(reduction = 'elementwise_mean')

i = 1
for it in tqdm(range(10000)):
    mb_idx = sample_idx(train_n, mb_size)
    X_mb = X_train[mb_idx,:]
    X_mb = torch.tensor(X_mb).float()
    y_mb = y_train[mb_idx]        
    y_mb = torch.tensor(y_mb).float()

    # Train D
    G_sample = G(X_mb)
    D_loss1 = ((D(X_mb) + 1e-8).log()).mean() + ((1 - D(G_sample) + 1e-8).log()).mean()
    D_loss = - D_loss1
    D_loss.backward()
    optimD.step()
    optimD.zero_grad()

    # Train G
    G_sample = G(X_mb)
    D_prob.detach()
    G_loss1 = ((1 - D(G_sample) + 1e-8).log()).mean()
    G_mse_loss = mse_loss(G_sample, y_mb)
    G_loss = G_loss1 + alpha * G_mse_loss
    G_loss.backward()
    optimG.step()
    optimG.zero_grad()

    if it % 100 == 0:
        print("Iter: {}".format(it))
        print("D_loss: {:.4}".format(D_loss))
        print("Train loss: {:.4}".format(G_mse_loss))
        print()


As you mentioned, you are getting the error in the following line.

D_loss1 = ((D(X_mb) + 1e-8).log()).mean() + ((1 - D(G_sample) + 1e-8).log()).mean()



  I doubt the problematic part is: D(G_sample). Why?


Because G_sample = G(X_mb) is of shape [batch_size, 1] which cannot be given as an input to the Discriminator, D because it takes tensor of shape [batch_size, dim] as input.

That's why you are getting the error:

RuntimeError: size mismatch, m1: [128 x 1], m2: [1392 x 2784]


As you can see, you have an input of shape, [128 x 1] where batch_size = 128. But the Discriminator D is expecting an input of shape [batch_size x 1392]. Here, m2 is the shape of the weight matrix of fc1 layer in the Discriminator.
