gpt4 book ai didi

python - Pytorch CNN错误: Expected input batch_size (4) to match target batch_size (64)

转载 作者:行者123 更新时间:2023-11-30 08:48:26 25 4
gpt4 key购买 nike

自十一月以来,我一直在自学这一点,对此的任何帮助将非常感激,感谢您的关注,因为我似乎在兜圈子。我正在尝试使用与 Mnist 数据集一起使用的 Pytorch CNN 示例。现在我正在尝试修改CNN以进行面部关键点识别。我使用的 Kaggle 数据集 (CSV) 包含 7048 个训练图像和关键点(每张脸 15 个关键点)和 1783 个测试图像。我分割了训练数据集并将图像转换为 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-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()

最佳答案

要了解出了什么问题,您可以在前进的每一步之后打印形状:

# 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 层会减少特征图的高度和宽度。
  • “ View ”应为 x = x.view(-1, 64 * 24 * 24)
  • 第一个线性层的大小:self.fc1 = nn.Linear(64 * 24 * 24, 100)

这将为您提供 output = model(data) 最终形状 torch.Size([64, 30])

但是这段代码在计算负对数似然损失时仍然会遇到问题:

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,

由于您的最后一个 nn 层输出超过 30 个类别的 softmax,我假设这是您想要分类的输出类别,所以目标的转换:

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 个类别的概率分布时,如果不是可以在此之前进行软最大值。因此,30 个值中的最大值将代表最高概率 - 因此该类正是您的输出所代表的,因此您可以计算两个值之间的 nll。 。

关于python - Pytorch CNN错误: Expected input batch_size (4) to match target batch_size (64),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54928638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com