自11月以来,我一直在自学这方面的知识,对此的任何帮助将不胜感激,谢谢您的关注,因为我似乎在转圈。我正在尝试使用与Mnist数据集一起使用的Pytorch CNN示例。现在,我正在尝试修改用于面部关键点识别的CNN。我正在使用7048个训练图像和关键点(每张脸15个关键点)和1783个测试图像的Kaggle数据集(CSV)。我分割训练数据集并将图像转换为jpeg,为关键点(形状15、2)制作了单独的文件。我已经制作了数据集和数据加载器,并且可以遍历和显示图像并绘制关键点。运行CNN时出现此错误。
> 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
以下是我已阅读的一些链接,我无法弄清问题所在 但可能会对其他人有所帮助。
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卷积神经网络接受64-x-64im Pytorch Validating Model Error: Expected input batch_size (3) to match target batch_size (4) 模型错误预期的输入批量大小为3的匹配目标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()
答案 0 :(得分:0)
要了解出了什么问题,可以在前进的每一步之后打印形状:
# 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)
的第一个线性层这将使您的output = model(data)
的最终形状为torch.Size([64, 30])
但是此代码在计算负对数似然损失时仍然会遇到问题:
预计输入将包含每个班级的分数。输入必须 是大小的2D张量(minibatch,C)。该标准要求上课 一维张量的每个值的索引(0到C-1)作为目标 小批量
其中类索引只是标签:
代表一个类的值。例如:
0-class0,1-class1,
由于您的最后nn层输出的softmax超过30个类,所以我假设这是您要分类的输出类, 因此目标转换:
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。 。