以下代码 :
import torch import torch.nn as nnimport torchvisionimport torchvision.transforms as transformsimport torch.utils.data as data_utilsimport numpy as nptrain_dataset = []mu, sigma = 0, 0.1 # mean and standard deviationnum_instances = 20batch_size_value = 10for 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 configurationdevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')# Hyper parametersnum_epochs = 5num_classes = 1batch_size = 5learning_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 outmodel = ConvNet(num_classes).to(device)# Loss and optimizercriterion = nn.CrossEntropyLoss()optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)# Train the modeltotal_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
阅读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)
?
回答:
错误来自于你的最后一个全连接层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)
的输入定义的。
你的第2个卷积层输出与全连接层预期形状之间的这种不匹配导致了错误(请注意,错误信息中提到的形状与上述形状对应)。