我有一个问题,我已经解决了一个星期了。我正在尝试构建CIFAR-10分类器,但是每个批次之后我的损失值随机跳跃,即使在同一批次上也没有提高准确性(我甚至不能用一批配套模型),所以我想是唯一的可能的原因是 - 权重没有更新。
我的模块类
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中的顺序模块,但是我传递给优化器的参数似乎是正确的)
答案 0 :(得分:0)
商品数据集是用于从文件夹加载图片的数据集,以及包含列类别作为标签的csv文件, id 作为图片文件ID < / p>
我建议使用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_set,这将为您提供索引 i 以及使用标签编码器编码的图像和标签元组那是在Dataset里面。
祝你好运!