Pytorch CNN错误:预期输入batch_size(4)匹配目标batch_size(64) [英] Pytorch CNN error: Expected input batch_size (4) to match target batch_size (64)
问题描述
自11月以来,我一直在自学这方面的知识,对此的任何帮助将不胜感激,谢谢您的关注,因为我似乎在转圈.我正在尝试使用与Mnist数据集一起使用的Pytorch CNN示例.现在,我正在尝试修改CNN以进行面部关键点识别.我正在使用7048个训练图像和关键点(每张脸15个关键点)和1783个测试图像的Kaggle数据集(CSV).我分割训练数据集并将图像转换为jpeg,并为关键点(形状15、2)制作了单独的文件.我已经制作了数据集和数据加载器,并且可以遍历和显示图像并绘制关键点.运行CNN时出现此错误.
I've been teaching myself this since November and any help on this would be really appreciated, thank you for looking, as I seem to be going round in circles. I am trying to use a Pytorch CNN example that was used with the Mnist dataset. Now I am trying to modify the CNN for facial key point recognition. I am using the Kaggle dataset (CSV) of 7048 training images and key points (15 key points per face) and 1783 test images. I split training dataset and converted the images to jpeg, made separate file for the key points (shape 15, 2). I have made dataset and data loader and can iterate through and display images and plot key points. When I run the CNN I am getting this error.
> Net(
(conv1): Conv2d(1, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
(conv2): Conv2d(32, 64, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
(conv2_drop): Dropout2d(p=0.5)
(fc1): Linear(in_features=589824, out_features=100, bias=True)
(fc2): Linear(in_features=100, out_features=30, bias=True)
)
Data and target shape: torch.Size([64, 96, 96]) torch.Size([64, 15, 2])
Data and target shape: torch.Size([64, 1, 96, 96]) torch.Size([64, 15, 2])
Traceback (most recent call last):
File "/home/keith/PycharmProjects/FacialLandMarks/WorkOut.py", line 416, in <module>
main()
File "/home/keith/PycharmProjects/FacialLandMarks/WorkOut.py", line 412, in main
train(args, model, device, train_loader, optimizer, epoch)
File "/home/keith/PycharmProjects/FacialLandMarks/WorkOut.py", line 324, in train
loss = F.nll_loss(output, target)
File "/home/keith/Desktop/PycharmProjects/fkp/FacialLandMarks/lib/python3.6/site-packages/torch/nn/functional.py", line 1788, in nll_loss
.format(input.size(0), target.size(0)))
ValueError: Expected input batch_size (4) to match target batch_size (64).
Process finished with exit code 1
以下是我已阅读的一些链接,我无法弄清问题所在 但可能会对其他人有所帮助.
Here are some links I have read, I could not figure out the problem but may help some one else.
https://github.com/pytorch/pytorch/issues/11762 如何修改PyTorch卷积神经网络以接受64 x 64图像并正确输出预测? pytorch卷积神经网络接受64-x-64im Pytorch验证模型错误:预期输入batch_size(3)匹配目标batch_size(4) 模型错误预期的输入批量大小为3的匹配目标ba
https://github.com/pytorch/pytorch/issues/11762 How do I modify this PyTorch convolutional neural network to accept a 64 x 64 image and properly output predictions? pytorch-convolutional-neural-network-to-accept-a-64-x-64-im Pytorch Validating Model Error: Expected input batch_size (3) to match target batch_size (4) model-error-expected-input-batch-size-3-to-match-target-ba
这是我的代码:
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5, stride=1, padding=(2, 2))
self.conv2 = nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=(2, 2))
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(64 * 96 * 96, 100)
self.fc2 = nn.Linear(100, 30) # 30 is x and y key points
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 64 * 96 * 96)
# x = x.view(x.size(0), -1)
# x = x.view(x.size()[0], 30, -1)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return F.log_softmax(x, dim=1)
def train(args, model, device, train_loader, optimizer, epoch):
model.train()
for batch_idx, batch in enumerate(train_loader):
data = batch['image']
target = batch['key_points']
print('Data and target shape: ', data.shape, ' ', target.shape)
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
data = data.unsqueeze(1).float()
print('Data and target shape: ', data.shape, ' ', target.shape)
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
# def test(args, model, device, test_loader):
# model.eval()
# test_loss = 0
# correct = 0
# with torch.no_grad():
# for data, target in test_loader:
# data, target = data.to(device), target.to(device)
# output = model(data)
# test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss
# pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability
# correct += pred.eq(target.view_as(pred)).sum().item()
#
# test_loss /= len(test_loader.dataset)
# print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
# test_loss, correct, len(test_loader.dataset),
# 100. * correct / len(test_loader.dataset)))
def main():
# Training settings
parser = argparse.ArgumentParser(description='Project')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=10, metavar='N', # ======== epoch
help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.01, metavar='LR',
help='learning rate (default: 0.01)')
parser.add_argument('--momentum', type=float, default=0.5, metavar='M',
help='SGD momentum (default: 0.5)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
help='how many batches to wait before logging training status')
args = parser.parse_args()
use_cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
device = torch.device("cuda" if use_cuda else "cpu")
kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
train_data_set = FaceKeyPointDataSet(csv_file='faces/Kep_points_and_id.csv',
root_dir='faces/',
transform=transforms.Compose([
# Rescale(96),
ToTensor()
]))
train_loader = DataLoader(train_data_set, batch_size=args.batch_size,
shuffle=True)
print('Number of samples: ', len(train_data_set))
print('Number of train_loader: ', len(train_loader))
model = Net().to(device)
print(model)
optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)
for epoch in range(1, args.epochs + 1):
train(args, model, device, train_loader, optimizer, epoch)
# test(args, model, device, test_loader)
if __name__ == '__main__':
main()
推荐答案
要了解出了什么问题,可以在前进的每一步之后打印形状:
to understand what went wrong you can print shape after every step in forward :
# Input data
torch.Size([64, 1, 96, 96])
x = F.relu(F.max_pool2d(self.conv1(x), 2))
torch.Size([64, 32, 48, 48])
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
torch.Size([64, 64, 24, 24])
x = x.view(-1, 64 * 96 * 96)
torch.Size([4, 589824])
x = F.relu(self.fc1(x))
torch.Size([4, 100])
x = F.dropout(x, training=self.training)
torch.Size([4, 100])
x = self.fc2(x)
torch.Size([4, 30])
return F.log_softmax(x, dim=1)
torch.Size([4, 30])
- 您的
maxpool2d
图层可减少要素图的高度和宽度. - 视图"应为
x = x.view(-1, 64 * 24 * 24)
- 大小的第一个线性层:
self.fc1 = nn.Linear(64 * 24 * 24, 100)
- Your
maxpool2d
layers reduce the height and width of your feature maps. - The 'view' should be
x = x.view(-1, 64 * 24 * 24)
- the first linear layer of size :
self.fc1 = nn.Linear(64 * 24 * 24, 100)
这将使您的output = model(data)
最终形状为torch.Size([64, 30])
this will give your output = model(data)
final shape of torch.Size([64, 30])
但是此代码在计算负对数似然损失时仍然会遇到问题:
But this code will still face a problem in calculating the Negative Log Likelihood Loss :
预计输入将包含每个班级的分数.输入必须 成为大小的2D张量(minibatch,C).该标准要求上课 一维张量的每个值的下标(0到C-1)作为目标 小批量
The input is expected to contain scores for each class. input has to be a 2D Tensor of size (minibatch, C). This criterion expects a class index (0 to C-1) as the target for each value of a 1D tensor of size minibatch
其中类索引只是标签:
代表一个类的值.例如:
values representing a class. For example:
0-class0、1-class1,
0 - class0, 1 - class1,
由于您的最后一个nn层输出了超过30个类的softmax,所以我假设这是您要分类的输出类, 因此目标转换:
Since your last nn layer outputs a softmax over 30 classes, i'm assuming that is the output classes you want to classify into, so transformation for target :
target = target.view(64, -1) # gives 64X30 ie, 30 values per channel
loss = F.nll_loss(x, torch.max(t, 1)[1]) # takes max amongst the 30 values as class label
这是当目标是超过30个类别的概率分布时,如果没有,则可以在此之前进行soft-max.因此,这30个值中的最大值将代表最高的概率-因此,该类正是您的输出所代表的类,因此您将计算两个值之间的nll. .
This is when the target is a probability distribution over 30 classes, if not can do a soft-max before that. Thus the maximum value in the 30 values will represent the highest probability - thus that class which is exactly what your output represents and thus you calculate a nll between the two values. .
这篇关于Pytorch CNN错误:预期输入batch_size(4)匹配目标batch_size(64)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!