【问题标题】:PyTorch Model is not trainingPyTorch 模型没有训练
【发布时间】:2018-01-03 16:11:14
【问题描述】:

我有一个问题,我已经无法解决一个星期。我正在尝试构建 CIFAR-10 分类器,但是每批后我的损失值随机跳跃,即使在同一批次上,准确性也没有提高(我什至不能用一批过拟合模型),所以我猜唯一可能的原因is - 权重没有更新。

我的模块类

class Net(nn.Module):
def __init__(self):
    super(Net, self).__init__()
    self.conv_pool = nn.Sequential(
        nn.Conv2d(3, 64, 3, padding=1),
        nn.ReLU(),
        nn.MaxPool2d(2, 2),
        nn.Conv2d(64, 128, 3, padding=1),
        nn.ReLU(),
        nn.MaxPool2d(2, 2),
        nn.Conv2d(128, 256, 3, padding=1),
        nn.ReLU(),
        nn.MaxPool2d(2, 2),
        nn.Conv2d(256, 512, 3, padding=1),
        nn.ReLU(),
        nn.MaxPool2d(2, 2),
        nn.Conv2d(512, 512, 1),
        nn.ReLU(),
        nn.MaxPool2d(2, 2))

    self.fcnn = nn.Sequential(
        nn.Linear(512, 2048),
        nn.ReLU(),
        nn.Linear(2048, 2048),
        nn.ReLU(),
        nn.Linear(2048, 10)
    )

def forward(self, x):
    x = self.conv_pool(x)
    x = x.view(-1, 512)
    x = self.fcnn(x)
    return x

我正在使用的优化器:

net = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

我的火车功能:

def train():
for epoch in range(5):  # loop over the dataset multiple times
    for i in range(0, df_size):
        # get the data

        try:
            images, labels = loadBatch(ds, i)
        except BaseException:
            continue

        # wrap 
        inputs = Variable(images)

        optimizer.zero_grad()

        outputs = net(inputs)

        loss = criterion(outputs, Variable(labels))

        loss.backward()
        optimizer.step()
        acc = test(images,labels)
        print("Loss: " + str(loss.data[0]) + " Accuracy %: " + str(acc) + " Iteration: " + str(i))

        if i % 40 == 39:
            torch.save(net.state_dict(), "model_save_cifar")

    print("Finished epoch " + str(epoch))

我正在使用 batch_size = 20,image_size = 32 (CIFAR-10)

loadBatch 函数返回 LongTensor 20x3x32x32 的图像和 LongTensor 20x1 的标签的元组

如果您能帮助我或提出可能的解决方案,我将非常高兴(我猜这是因为 NN 中的顺序模块,但我传递给优化器的参数似乎是正确的)

【问题讨论】:

  • 乍一看,我觉得很好。您也可以发布您的测试功能吗?
  • @blckbird 如果您有兴趣,请查看我的答案。测试函数只是遍历 test_set 并将输出标签与 train_set 标签进行比较

标签: python machine-learning computer-vision conv-neural-network pytorch


【解决方案1】:

好的,伙计们,我发现了问题所在。我试图自己将图像转换为张量,似乎我弄乱了图像的尺寸+我正在按顺序而不是分批观看 SGD 步骤。现在我每 25 批检查一次,大部分时间都可以,取决于 NN 和数据。这是我加载数据的代码,希望对大家有帮助

Goods dataset是从文件夹加载图片的Dataset,csv文件包含category列作为标签,id作为图片文件id

我建议使用pytorch图像处理功能和Pillow Image.Open

batch_size = 8
img_size = 224

transformer = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])



class GoodsDataset(Dataset):
    def __init__(self, csv_file, root_dir):
        """
        Args:
            csv_file (string): Path to the csv file with annotations.
            root_dir (string): Directory with all the images.
            transform (callable, optional): Optional transform to be applied
                on a sample.
        """
        self.data = pd.read_csv(csv_file)
        self.root_dir = root_dir
        self.le = preprocessing.LabelEncoder()
        self.le.fit(self.data.loc[:, 'category'])

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        img_name = os.path.join(self.root_dir, str(self.data.loc[idx, 'id']) + '.jpg')
        image = (Image.open(img_name))
        good = self.data.iloc[idx, :].as_matrix()
        label = self.le.transform([good[2]])
        return [transformer(image), label]

那么你可以使用:

train_ds = GoodsDataset("topthree.csv", "resized")
train_set = dataloader = torch.utils.data.DataLoader(train_ds, batch_size = batch_size, shuffle = True)

在您的 train 函数中,使用 enumerate 遍历 train_set,这将为您提供索引 i 以及图像和标签的元组,使用 Label Encoder 进行编码strong> 在数据集中。

祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-11
    • 2018-02-20
    • 2021-11-18
    • 2020-09-15
    • 2021-04-05
    • 2021-07-01
    • 2019-11-06
    • 1970-01-01
    相关资源
    最近更新 更多