下面的代码:

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 以匹配



来自 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) 的图像形状?

最佳答案

错误来自您最终的全连接层 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) 形状的输入定义的。

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

关于machine-learning - Conv2d 的预期参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51885408/

10-12 22:10