问题
I have input data (colored images) in the shape of (100, 64, 64, 3) and tried to train a CNN with 2 conv/pooling layers on it for binary classification. I keep encountering size mismatch error. Also attempted reshape the images into (-1, 3, 64, 64) size
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())
The full error msg is
only batches of spatial targets supported (3D tensors) but got targets of dimension: 1 at /pytorch/aten/src/THNN/generic/SpatialClassNLLCriterion.c:61'
来源:https://stackoverflow.com/questions/58325886/how-to-solve-dimension-mismatch-error-for-cnn-on-images-in-pytorch