train.py 7.6 KB
Newer Older
H
hypox64 已提交
1
import os
H
hypox64 已提交
2 3 4 5 6 7
import sys
sys.path.append("..")
sys.path.append("../..")
from cores import Options
opt = Options()

H
hypox64 已提交
8 9
import random
import datetime
H
hypox64 已提交
10
import time
H
hypox64 已提交
11 12

import numpy as np
H
HypoX64 已提交
13 14
import matplotlib
matplotlib.use('Agg')
H
hypox64 已提交
15
from matplotlib import pyplot as plt
H
hypox64 已提交
16 17 18 19 20 21 22
import cv2

import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
from torch import optim

H
HypoX64 已提交
23 24
from util import mosaic,util,ffmpeg,filt,data
from util import image_processing as impro
H
hypox64 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
from models import unet_model,BiSeNet_model


'''
--------------------------Get options--------------------------
'''
opt.parser.add_argument('--lr',type=float,default=0.001, help='')
opt.parser.add_argument('--finesize',type=int,default=360, help='')
opt.parser.add_argument('--loadsize',type=int,default=400, help='')
opt.parser.add_argument('--batchsize',type=int,default=8, help='')
opt.parser.add_argument('--model',type=str,default='BiSeNet', help='BiSeNet or UNet')

opt.parser.add_argument('--maxepoch',type=int,default=100, help='')
opt.parser.add_argument('--savefreq',type=int,default=5, help='')
opt.parser.add_argument('--maxload',type=int,default=1000000, help='')
40
opt.parser.add_argument('--continue_train', action='store_true', help='')
H
hypox64 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
opt.parser.add_argument('--startepoch',type=int,default=0, help='')
opt.parser.add_argument('--dataset',type=str,default='./datasets/face/', help='')
opt.parser.add_argument('--savename',type=str,default='face', help='')


'''
--------------------------Init--------------------------
'''
opt = opt.getparse()
dir_img = os.path.join(opt.dataset,'origin_image')
dir_mask = os.path.join(opt.dataset,'mask')
dir_checkpoint = os.path.join('checkpoints/',opt.savename)
util.makedirs(dir_checkpoint)
util.writelog(os.path.join(dir_checkpoint,'loss.txt'), 
              str(time.asctime(time.localtime(time.time())))+'\n'+util.opt2str(opt))
H
hypox64 已提交
56 57 58 59

def Totensor(img,use_gpu=True):
    size=img.shape[0]
    img = torch.from_numpy(img).float()
H
hypox64 已提交
60
    if opt.use_gpu != -1:
H
hypox64 已提交
61 62 63
        img = img.cuda()
    return img

H
hypox64 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
def loadimage(imagepaths,maskpaths,opt,test_flag = False):
    batchsize = len(imagepaths)
    images = np.zeros((batchsize,3,opt.finesize,opt.finesize), dtype=np.float32)
    masks = np.zeros((batchsize,1,opt.finesize,opt.finesize), dtype=np.float32)
    for i in range(len(imagepaths)):
        img = impro.resize(impro.imread(imagepaths[i]),opt.loadsize)
        mask = impro.resize(impro.imread(maskpaths[i],mod = 'gray'),opt.loadsize)      
        img,mask = data.random_transform_image(img, mask, opt.finesize, test_flag)
        images[i] = (img.transpose((2, 0, 1))/255.0)
        masks[i] = (mask.reshape(1,1,opt.finesize,opt.finesize)/255.0)
    images = Totensor(images,opt.use_gpu)
    masks = Totensor(masks,opt.use_gpu)

    return images,masks


'''
--------------------------checking dataset--------------------------
'''
print('checking dataset...')
imagepaths = sorted(util.Traversal(dir_img))[:opt.maxload]
maskpaths = sorted(util.Traversal(dir_mask))[:opt.maxload]
data.shuffledata(imagepaths, maskpaths)
if len(imagepaths) != len(maskpaths) :
    print('dataset error!')
    exit(0)
img_num = len(imagepaths)
print('find images:',img_num)
imagepaths_train = (imagepaths[0:int(img_num*0.8)]).copy()
maskpaths_train = (maskpaths[0:int(img_num*0.8)]).copy()
imagepaths_eval = (imagepaths[int(img_num*0.8):]).copy()
maskpaths_eval = (maskpaths[int(img_num*0.8):]).copy()

'''
--------------------------def network--------------------------
'''
if opt.model =='UNet':
    net = unet_model.UNet(n_channels = 3, n_classes = 1)
elif opt.model =='BiSeNet':
    net = BiSeNet_model.BiSeNet(num_classes=1, context_path='resnet18')

105
if opt.continue_train:
H
hypox64 已提交
106
    if not os.path.isfile(os.path.join(dir_checkpoint,'last.pth')):
107
        opt.continue_train = False
H
hypox64 已提交
108
        print('can not load last.pth, training on init weight.')
109
if opt.continue_train:
H
hypox64 已提交
110 111 112 113
    net.load_state_dict(torch.load(os.path.join(dir_checkpoint,'last.pth')))
    f = open(os.path.join(dir_checkpoint,'epoch_log.txt'),'r')
    opt.startepoch = int(f.read())
    f.close()
H
hypox64 已提交
114
if opt.use_gpu != -1:
H
hypox64 已提交
115
    net.cuda()
H
hypox64 已提交
116
    cudnn.benchmark = True
H
hypox64 已提交
117

H
hypox64 已提交
118
optimizer = torch.optim.Adam(net.parameters(), lr=opt.lr)
H
hypox64 已提交
119

H
hypox64 已提交
120 121 122 123 124
if opt.model =='UNet':
    criterion = nn.BCELoss()
elif opt.model =='BiSeNet':
    criterion = nn.BCELoss()
    # criterion = BiSeNet_model.DiceLoss()
H
hypox64 已提交
125

H
hypox64 已提交
126 127 128 129
'''
--------------------------train--------------------------
'''
loss_plot = {'train':[],'eval':[]}
H
hypox64 已提交
130
print('begin training......')
H
hypox64 已提交
131 132 133
for epoch in range(opt.startepoch,opt.maxepoch):
    random_save = random.randint(0, int(img_num*0.8/opt.batchsize))
    data.shuffledata(imagepaths_train, maskpaths_train)
H
hypox64 已提交
134 135

    starttime = datetime.datetime.now()
H
hypox64 已提交
136
    util.writelog(os.path.join(dir_checkpoint,'loss.txt'),'Epoch {}/{}.'.format(epoch + 1, opt.maxepoch),True)
H
hypox64 已提交
137
    net.train()
H
hypox64 已提交
138
    if opt.use_gpu != -1:
H
hypox64 已提交
139 140
        net.cuda()
    epoch_loss = 0
H
hypox64 已提交
141 142
    for i in range(int(img_num*0.8/opt.batchsize)):
        img,mask = loadimage(imagepaths_train[i*opt.batchsize:(i+1)*opt.batchsize], maskpaths_train[i*opt.batchsize:(i+1)*opt.batchsize], opt)
H
hypox64 已提交
143

H
hypox64 已提交
144 145 146 147 148 149 150 151 152 153 154
        if opt.model =='UNet':
            mask_pred = net(img)
            loss = criterion(mask_pred, mask)
            epoch_loss += loss.item()
        elif opt.model =='BiSeNet':
            mask_pred, mask_pred_sup1, mask_pred_sup2 = net(img)
            loss1 = criterion(mask_pred, mask)
            loss2 = criterion(mask_pred_sup1, mask)
            loss3 = criterion(mask_pred_sup2, mask)
            loss = loss1 + loss2 + loss3
            epoch_loss += loss1.item()
H
hypox64 已提交
155 156 157 158 159

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

H
HypoX64 已提交
160
        if i%100 == 0:
H
hypox64 已提交
161 162 163
            data.showresult(img,mask,mask_pred,os.path.join(dir_checkpoint,'result.png'),True)
        if  i == random_save:
            data.showresult(img,mask,mask_pred,os.path.join(dir_checkpoint,'epoch_'+str(epoch+1)+'.png'),True)
H
hypox64 已提交
164 165
    epoch_loss = epoch_loss/int(img_num*0.8/opt.batchsize)
    loss_plot['train'].append(epoch_loss)
H
hypox64 已提交
166

H
hypox64 已提交
167
    #val
H
hypox64 已提交
168 169
    epoch_loss_eval = 0
    with torch.no_grad():
H
hypox64 已提交
170 171 172 173 174 175 176 177 178
    # net.eval()
        for i in range(int(img_num*0.2/opt.batchsize)):
            img,mask = loadimage(imagepaths_eval[i*opt.batchsize:(i+1)*opt.batchsize], maskpaths_eval[i*opt.batchsize:(i+1)*opt.batchsize], opt,test_flag=True)
            if opt.model =='UNet':
                mask_pred = net(img)
            elif opt.model =='BiSeNet':
                mask_pred, _, _ = net(img)
            # mask_pred = net(img)
            loss= criterion(mask_pred, mask)
H
hypox64 已提交
179
            epoch_loss_eval += loss.item()
H
hypox64 已提交
180 181
    epoch_loss_eval = epoch_loss_eval/int(img_num*0.2/opt.batchsize)
    loss_plot['eval'].append(epoch_loss_eval)
H
hypox64 已提交
182 183
    # torch.cuda.empty_cache()

H
hypox64 已提交
184
    #savelog
H
hypox64 已提交
185
    endtime = datetime.datetime.now()
H
hypox64 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
    util.writelog(os.path.join(dir_checkpoint,'loss.txt'),
                '--- Epoch train_loss: {0:.6f} eval_loss: {1:.6f} Cost time: {2:} s'.format(
                    epoch_loss,
                    epoch_loss_eval,
                    (endtime - starttime).seconds),
                True)
    #plot
    plt.plot(np.linspace(opt.startepoch+1,epoch+1,epoch+1-opt.startepoch),loss_plot['train'],label='train')
    plt.plot(np.linspace(opt.startepoch+1,epoch+1,epoch+1-opt.startepoch),loss_plot['eval'],label='eval')
    plt.xlabel('Epoch')
    plt.ylabel('BCELoss')
    plt.legend(loc=1)
    plt.savefig(os.path.join(dir_checkpoint,'loss.jpg'))
    plt.close()
    #save network
    torch.save(net.cpu().state_dict(),os.path.join(dir_checkpoint,'last.pth'))
    f = open(os.path.join(dir_checkpoint,'epoch_log.txt'),'w+')
    f.write(str(epoch+1))
    f.close()
    if (epoch+1)%opt.savefreq == 0:
        torch.save(net.cpu().state_dict(),os.path.join(dir_checkpoint,'epoch'+str(epoch+1)+'.pth'))
H
hypox64 已提交
207
        print('network saved.')