Conv2d的预期参数

时间:2018-08-16 21:12:12

标签: machine-learning deep-learning conv-neural-network convolution pytorch

下面的代码:

import torch 
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch.utils.data as data_utils
import numpy as np

train_dataset = []
mu, sigma = 0, 0.1 # mean and standard deviation
num_instances = 20
batch_size_value = 10
for i in range(num_instances) :
    image = []
    image_x = np.random.normal(mu, sigma, 1000).reshape((1 , 100, 10))
    train_dataset.append(image_x)
labels = [1 for i in range(num_instances)]
x2 = torch.tensor(train_dataset).float()
y2 = torch.tensor(labels).long()
my_train2 = data_utils.TensorDataset(x2, y2)
train_loader2 = data_utils.DataLoader(my_train2, batch_size=batch_size_value, shuffle=False)    

# Device configuration
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

# Hyper parameters
num_epochs = 5
num_classes = 1
batch_size = 5
learning_rate = 0.001

# Convolutional neural network (two convolutional layers)
class ConvNet(nn.Module):
    def __init__(self, num_classes=1):
        super(ConvNet, self).__init__()
        self.layer1 = nn.Sequential(
            nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.layer2 = nn.Sequential(
            nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.fc = nn.Linear(7*7*32, num_classes)

    def forward(self, x):
        out = self.layer1(x)
        out = self.layer2(out)
        out = out.reshape(out.size(0), -1)
        out = self.fc(out)
        return out

model = ConvNet(num_classes).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

# Train the model
total_step = len(train_loader2)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader2):
        images = images.to(device)
        labels = labels.to(device)

        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)

        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i+1) % 100 == 0:
            print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' 
                   .format(epoch+1, num_epochs, i+1, total_step, loss.item()))

返回错误:

RuntimeError: size mismatch, m1: [10 x 1600], m2: [1568 x 1] at /pytorch/aten/src/THC/generic/THCTensorMathBlas.cu:249

在读取documentation for conv2d时,我尝试将第一个参数更改为10X100以匹配

  

input –形状的输入张量(minibatch×in_channels×iH×iW)

来自https://pytorch.org/docs/stable/nn.html#torch.nn.functional.conv2d

但随后收到错误:

RuntimeError: Given groups=1, weight[16, 1000, 5, 5], so expected input[10, 1, 100, 10] to have 1000 channels, but got 1 channels instead

所以我不确定是否已纠正了原始错误或只是导致了新错误?

如何设置Conv2d以匹配(10,100)的图像形状?

1 个答案:

答案 0 :(得分:2)

错误来自最终的完全连接层self.fc = nn.Linear(7*7*32, num_classes),而不是卷积层。

鉴于您的输入尺寸((10, 100)out = self.layer2(out)的形状为(batch_size, 32, 25, 2),因此out = out.reshape(out.size(0), -1)的形状为(batch_size, 32*25*2) = (batch_size, 1600)

另一方面,为形状为(batch_size, 32*7*7) = (batch_size, 1568)的输入定义了全连接层。

第二个卷积输出的形状与完全连接的层的预期形状之间的这种不匹配导致了错误(请注意轨迹中提到的形状如何与上述形状相对应)。