我有(100,64,64,3)形状的输入数据(彩色图像),并尝试训练带有2个conv / pooling层的CNN进行二进制分类。我一直遇到尺寸不匹配错误。还尝试将图像重塑为(-1、3、64、64)大小
class SimpleCNN(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, kernel_size):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size, padding=0)
self.conv2 = nn.Conv2d(10, 20, kernel_size, padding=0)
self.fc1 = nn.Linear(hidden_dim*16*16, hidden_dim)
self.fc2 = nn.Linear(output_dim, output_dim)
def forward(self, x):
x = F.max_pool2d((self.conv1(x)), 2)
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return F.softmax(x)
net = SimpleCNN(in_channels, hidden_dim, out_channels, kernel_size)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)
losses = []
idx = []
count=1
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = Variable(images.view(-1, 3, n_pixel, n_pixel))
labels = Variable(labels)
# Intialize the hidden weight to all zeros
optimizer.zero_grad()
# Forward pass: compute the output class given a image
outputs = net(images)
# Compute the loss: difference between the output class and the pre-given label
loss = criterion(outputs, labels)
# Backward pass: compute the weight
loss.backward()
# Optimizer: update the weights of hidden nodes
optimizer.step()
count+=1
if (i+1) % 10 == 0:
idx.append(count)
losses.append(loss.data.numpy().tolist())
完整错误消息为
仅支持批次的空间目标(3D张量),但尺寸目标为:/pytorch/aten/src/THNN/generic/SpatialClassNLLCriterion.c:61'