火炬大小不匹配

时间:2020-04-14 13:46:05

标签: python machine-learning pytorch

在尝试运行应该训练我的模型的代码时出现此错误:

RuntimeError: size mismatch, m1: [64 x 17920], m2: [5376 x 1024] at /pytorch/aten/src/THC/generic/THCTensorMathBlas.cu:290

我不确定ConvNet中是否有错误

我的训练集中有6354张图像,测试集中有1589张图像,尺寸分别为3、75、100。

这是我的代码:

class ConvNet(nn.Module):

def __init__(self):
    super().__init__()
    a = 64 
    b = 128 
    c = 256 

    d = 1024
    e = 2048

    self.conv1 = nn.Conv2d(3, a, 3)
    self.conv2 = nn.Conv2d(a, b, 3)
    self.conv3 = nn.Conv2d(b, c, 3)

    self.fc1 = nn.Linear(3*7*c, d) 
    self.fc2 = nn.Linear(d, e)
    self.fc3 = nn.Linear(e, 2)

def forward(self, x):
    x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
    x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2))
    x = F.max_pool2d(F.relu(self.conv3(x)), (2, 2))

    x = x.view(x.size(0), -1)
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = F.dropout(x, 0.5)
    x = self.fc3(x)
    return x

net = ConvNet()


epochs = 100
steps = 0
train_losses, test_losses = [], []
for e in range(epochs):
running_loss = 0
net.train()
for images, labels in train_loader:   
    if torch.cuda.is_available():
        images, labels = images.cuda(), labels.cuda()     
    optimizer.zero_grad()
    log_ps = net(images)
    loss = loss_function(log_ps, labels)
    loss.backward()
    optimizer.step()        
    running_loss += loss.item()        
else:
    test_loss = 0
    accuracy = 0        
    net.eval()
    with torch.no_grad():
        for images, labels in test_loader:
            if torch.cuda.is_available():
                images, labels = images.cuda(), labels.cuda()
            log_ps = net(images)
            test_loss += loss_function(log_ps, labels)                
            # ps = torch.exp(log_ps)
            top_p, top_class = log_ps.topk(1, dim=1)
            equals = top_class.long() == labels.long().view(*top_class.shape)
            accuracy += torch.mean(equals.type(torch.FloatTensor))                
    train_losses.append(running_loss/len(train_loader))
    test_losses.append(test_loss/len(test_loader))
    print("[Epoch: {}/{}] ".format(e+1, epochs),
          "[Training Loss: {:.3f}] ".format(running_loss/len(train_loader)),
          "[Test Loss: {:.3f}] ".format(test_loss/len(test_loader)),
          "[Test Accuracy: {:.3f}]".format(accuracy/len(test_loader)))

我不确定该如何匹配尺寸来训练我的模型。

0 个答案:

没有答案