[英]How to train a Pytorch net
我使用這個 Pytorch實現Segnet與我找到了對象分割預訓練的價值,並能正常工作。 現在,我想使用具有相似圖像的新數據集,從已有的值中恢復訓練。 我怎樣才能做到這一點?
我想我必須使用在存儲庫中找到的“ train.py”文件,但是我不知道要寫什么來替換“填充批處理”注釋。 這是代碼的一部分:
def train(epoch):
model.train()
# update learning rate
lr = args.lr * (0.1 ** (epoch // 30))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
# define a weighted loss (0 weight for 0 label)
weights_list = [0]+[1 for i in range(17)]
weights = np.asarray(weights_list)
weigthtorch = torch.Tensor(weights_list)
if(USE_CUDA):
loss = nn.CrossEntropyLoss(weight=weigthtorch).cuda()
else:
loss = nn.CrossEntropyLoss(weight=weigthtorch)
total_loss = 0
# iteration over the batches
batches = []
for batch_idx,batch_files in enumerate(tqdm(batches)):
# containers
batch = np.zeros((args.batch_size,input_nbr, imsize, imsize), dtype=float)
batch_labels = np.zeros((args.batch_size,imsize, imsize), dtype=int)
# fill the batch
# ...
# What should I write here?
batch_th = Variable(torch.Tensor(batch))
target_th = Variable(torch.LongTensor(batch_labels))
if USE_CUDA:
batch_th =batch_th.cuda()
target_th = target_th.cuda()
# initilize gradients
optimizer.zero_grad()
# predictions
output = model(batch_th)
# Loss
output = output.view(output.size(0),output.size(1), -1)
output = torch.transpose(output,1,2).contiguous()
output = output.view(-1,output.size(2))
target = target.view(-1)
l_ = loss(output.cuda(), target)
total_loss += l_.cpu().data.numpy()
l_.cuda()
l_.backward()
optimizer.step()
return total_loss/len(files)
如果我不得不猜測,他很有可能制作了一些Dataloader饋送器,以擴展Pytorch Dataloader類。 參見https://pytorch.org/tutorials/beginner/data_loading_tutorial.html
在頁面底部附近,您可以看到一個示例,其中他們在其數據加載器上循環
對於i_batch,在enumerate(dataloader)中采樣_batched:
例如,這對於圖像想要的是:
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=False, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batchSize, shuffle=True, num_workers=2)
for batch_idx, (inputs, targets) in enumerate(trainloader):
# Using the pytorch data loader the inputs and targets are given
# automatically
inputs, targets = inputs.cuda(), targets.cuda()
optimizer.zero_grad()
inputs, targets = Variable(inputs), Variable(targets)
作者不知道如何准確地加載他的文件。 您可以按照以下步驟進行操作: https : //pytorch.org/tutorials/beginner/data_loading_tutorial.html來創建自己的數據加載器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.