witnn/tools/Train.py

63 lines
2.2 KiB
Python
Raw Normal View History

2019-08-19 15:53:10 +08:00
from torch.utils.data import Dataset, DataLoader
import numpy as np
import torchvision.models as models
from torchvision import datasets, transforms
import torchvision
import torch.optim as optim
import torch.nn.functional as F
import torch.nn as nn
import torch
import os
import utils as utils
2019-09-17 23:20:24 +08:00
from tqdm import tqdm
2019-08-19 15:53:10 +08:00
2019-08-23 23:27:45 +08:00
def train(model, train_loader, optimizer, epoch=0):
2019-08-19 15:53:10 +08:00
model.train()
totalsize = train_loader.batch_sampler.sampler.num_samples
batchsize = int(totalsize / train_loader.batch_size / 5)+1
pbar = tqdm(totalsize)
2019-08-19 15:53:10 +08:00
for batch_idx, (data, target) in enumerate(train_loader):
2019-08-23 23:27:45 +08:00
data = utils.SetDevice(data)
target = utils.SetDevice(target)
2019-08-19 15:53:10 +08:00
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
2019-09-17 23:20:24 +08:00
pbar.update(train_loader.batch_size)
2019-08-23 23:27:45 +08:00
if batch_idx % batchsize == 0 and batch_idx > 0:
2019-09-17 23:20:24 +08:00
pbar.set_description("Loss:"+str(loss.item()))
pbar.close()
2019-08-19 15:53:10 +08:00
2019-08-23 23:27:45 +08:00
def test(model, test_loader):
2019-08-19 15:53:10 +08:00
with torch.no_grad():
model.eval()
test_loss = 0
correct = 0
for data, target in test_loader:
2019-08-23 23:27:45 +08:00
data = utils.SetDevice(data)
target = utils.SetDevice(target)
2019-08-19 15:53:10 +08:00
output = model(data)
# sum up batch loss
test_loss += F.nll_loss(output, target, reduction='sum').item()
# get the index of the max log-probability
pred = output.max(1, keepdim=True)[1]
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
2019-08-23 23:27:45 +08:00
accu = 100. * correct / len(test_loader.dataset)
2019-09-17 23:20:24 +08:00
# print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'
# .format(test_loss, correct, len(test_loader.dataset), accu))
2019-08-23 23:27:45 +08:00
return accu
2019-09-17 23:20:24 +08:00
def TrainEpochs(model, traindata, optimizer, testdata, epoch=100,testepoch=10, line=None):
epochbar = tqdm(total=epoch)
for i in range(epoch):
train(model, traindata, optimizer, epoch=i)
if line and i % testepoch == 0 and i > 0:
line.AppendData(test(model, testdata))
epochbar.update(1)
epochbar.close()