def evaluate(args): content_image = utils.tensor_load_rgbimage(args.content_image, size=args.content_size, keep_asp=True) content_image = content_image.unsqueeze(0) style = utils.tensor_load_rgbimage(args.style_image, size=args.style_size) style = style.unsqueeze(0) style = utils.preprocess_batch(style) vgg = Vgg16() utils.init_vgg16(args.vgg_model_dir) vgg.load_state_dict( torch.load(os.path.join(args.vgg_model_dir, "vgg16.weight"))) style_model = HangSNetV1() style_model.load_state_dict(torch.load(args.model)) if args.cuda: style_model.cuda() vgg.cuda() content_image = content_image.cuda() style = style.cuda() style_v = Variable(style, volatile=True) utils.subtract_imagenet_mean_batch(style_v) features_style = vgg(style_v) gram_style = [utils.gram_matrix(y) for y in features_style] content_image = Variable(utils.preprocess_batch(content_image)) target = Variable(gram_style[2].data, requires_grad=False) style_model.setTarget(target) output = style_model(content_image) utils.tensor_save_bgrimage(output.data[0], args.output_image, args.cuda)
def optimize(args): """ Gatys et al. CVPR 2017 ref: Image Style Transfer Using Convolutional Neural Networks """ # load the content and style target content_image = utils.tensor_load_rgbimage(args.content_image, size=args.content_size, keep_asp=True) content_image = content_image.unsqueeze(0) content_image = Variable(utils.preprocess_batch(content_image), requires_grad=False) content_image = utils.subtract_imagenet_mean_batch(content_image) style_image = utils.tensor_load_rgbimage(args.style_image, size=args.style_size) style_image = style_image.unsqueeze(0) style_image = Variable(utils.preprocess_batch(style_image), requires_grad=False) style_image = utils.subtract_imagenet_mean_batch(style_image) # load the pre-trained vgg-16 and extract features vgg = Vgg16() utils.init_vgg16(args.vgg_model_dir) vgg.load_state_dict( torch.load(os.path.join(args.vgg_model_dir, "vgg16.weight"))) if args.cuda: content_image = content_image.cuda() style_image = style_image.cuda() vgg.cuda() features_content = vgg(content_image) f_xc_c = Variable(features_content[1].data, requires_grad=False) features_style = vgg(style_image) gram_style = [utils.gram_matrix(y) for y in features_style] # init optimizer output = Variable(content_image.data, requires_grad=True) optimizer = Adam([output], lr=args.lr) mse_loss = torch.nn.MSELoss() # optimizing the images for e in range(args.iters): utils.imagenet_clamp_batch(output, 0, 255) optimizer.zero_grad() features_y = vgg(output) content_loss = args.content_weight * mse_loss(features_y[1], f_xc_c) style_loss = 0. for m in range(len(features_y)): gram_y = utils.gram_matrix(features_y[m]) gram_s = Variable(gram_style[m].data, requires_grad=False) style_loss += args.style_weight * mse_loss(gram_y, gram_s) total_loss = content_loss + style_loss if (e + 1) % args.log_interval == 0: print(total_loss.data.cpu().numpy()[0]) total_loss.backward() optimizer.step() # save the image output = utils.add_imagenet_mean_batch(output) utils.tensor_save_bgrimage(output.data[0], args.output_image, args.cuda)
def train(args): np.random.seed(args.seed) torch.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed) kwargs = {'num_workers': 0, 'pin_memory': False} else: kwargs = {} transform = transforms.Compose([ transforms.Scale(args.image_size), transforms.CenterCrop(args.image_size), transforms.ToTensor(), transforms.Lambda(lambda x: x.mul(255)) ]) train_dataset = datasets.ImageFolder(args.dataset, transform) train_loader = DataLoader(train_dataset, batch_size=args.batch_size, **kwargs) transformer = TransformerNet() optimizer = Adam(transformer.parameters(), args.lr) mse_loss = torch.nn.MSELoss() vgg = Vgg16() utils.init_vgg16(args.vgg_model_dir) vgg.load_state_dict( torch.load(os.path.join(args.vgg_model_dir, "vgg16.weight"))) if args.cuda: transformer.cuda() vgg.cuda() style = utils.tensor_load_rgbimage(args.style_image, size=args.style_size) style = style.repeat(args.batch_size, 1, 1, 1) style = utils.preprocess_batch(style) if args.cuda: style = style.cuda() style_v = Variable(style, volatile=True) utils.subtract_imagenet_mean_batch(style_v) features_style = vgg(style_v) gram_style = [utils.gram_matrix(y) for y in features_style] for e in range(args.epochs): transformer.train() agg_content_loss = 0. agg_style_loss = 0. count = 0 for batch_id, (x, _) in enumerate(train_loader): n_batch = len(x) count += n_batch optimizer.zero_grad() x = Variable(utils.preprocess_batch(x)) if args.cuda: x = x.cuda() y = transformer(x) xc = Variable(x.data.clone(), volatile=True) utils.subtract_imagenet_mean_batch(y) utils.subtract_imagenet_mean_batch(xc) features_y = vgg(y) features_xc = vgg(xc) f_xc_c = Variable(features_xc[1].data, requires_grad=False) content_loss = args.content_weight * mse_loss( features_y[1], f_xc_c) style_loss = 0. for m in range(len(features_y)): gram_s = Variable(gram_style[m].data, requires_grad=False) gram_y = utils.gram_matrix(features_y[m]) style_loss += args.style_weight * mse_loss( gram_y, gram_s[:n_batch, :, :]) total_loss = content_loss + style_loss total_loss.backward() optimizer.step() agg_content_loss += content_loss.data[0] agg_style_loss += style_loss.data[0] if (batch_id + 1) % args.log_interval == 0: mesg = "{}\tEpoch {}:\t[{}/{}]\tcontent: {:.6f}\tstyle: {:.6f}\ttotal: {:.6f}".format( time.ctime(), e + 1, count, len(train_dataset), agg_content_loss / (batch_id + 1), agg_style_loss / (batch_id + 1), (agg_content_loss + agg_style_loss) / (batch_id + 1)) print(mesg) # save model transformer.eval() transformer.cpu() save_model_filename = "epoch_" + str(args.epochs) + "_" + str( time.ctime()).replace(' ', '_') + "_" + str( args.content_weight) + "_" + str(args.style_weight) + ".model" save_model_path = os.path.join(args.save_model_dir, save_model_filename) torch.save(transformer.state_dict(), save_model_path) print("\nDone, trained model saved at", save_model_path)
transform = transforms.Compose([ transforms.Scale(args.image_size), #handle non-square img transforms.CenterCrop(args.image_size), transforms.ToTensor(), transforms.Lambda(lambda x: x.mul(255)) ]) train_img = datasets.ImageFolder(args.dataset, transform) train_loader = DataLoader(train_img, batch_size=args.batch_size, num_workers=4) n_iter = len(train_loader) print('=> %d Iter Step of 1 Epoch' % n_iter) # extract pretrained VGG weight print('=> Check and Extract pre-trained VGG16 weight') utils.init_vgg16() #init model print('=> Init Model') style_model = net.StylePart() #empyt model vgg_model = net.Vgg16Part() # fill pretrained vgg vgg_model.load_state_dict(torch.load('model/vgg16.weight')) # Load style_image print('=> Init Style Image') style = utils.img2X(args.style_image, args.style_size) style = style.repeat(args.batch_size, 1, 1, 1) style = utils.excg_rgb_bgr(style) # put on GPU if use_cuda:
def optimize(args): style_image = utils.tensor_load_rgbimage(args.style_image, size=args.style_size) style_image = style_image.unsqueeze(0) style_image = Variable(utils.preprocess_batch(style_image), requires_grad=False) # style_image = utils.subtract_imagenet_mean_batch(style_image) # generate the vector field that we want to stylize size = args.content_size vectors = np.zeros((size, size, 2), dtype=np.float32) eps = 1e-7 for y in range(size): for x in range(size): xx = float(x - size / 2) yy = float(y - size / 2) rsq = xx**2 + yy**2 if (rsq == 0): vectors[y, x, 0] = -1 vectors[y, x, 1] = 1 else: vectors[y, x, 0] = -yy / rsq if yy != 0 else eps vectors[y, x, 1] = xx / rsq if xx != 0 else eps # vectors[y, x, 0] = -1 # vectors[y, x, 1] = 1 # load the pre-trained vgg-16 and extract features vgg = Vgg16() utils.init_vgg16(args.vgg_model_dir) vgg.load_state_dict( torch.load(os.path.join(args.vgg_model_dir, 'vgg16.weight'))) if args.cuda: style_image = style_image.cuda() vgg.cuda() features_style = vgg(style_image) gram_style = [utils.gram_matrix(y) for y in features_style] # output_size = torch.Size([1, size, size]) # output = torch.randn(output_size) * 80 + 127 # if args.cuda: # output = output.cuda() # output = output.expand(3, size, size) # output = Variable(output, requires_grad=True) output_size = torch.Size([3, size, size]) output = Variable(torch.randn(output_size, device="cuda") * 80 + 127, requires_grad=True) optimizer = Adam([output], lr=args.lr) mse_loss = torch.nn.MSELoss() loss = [] tbar = trange(args.iters) for e in tbar: utils.clamp_batch(output, 0, 255) optimizer.zero_grad() lic_input = output kernellen = 15 kernel = np.sin(np.arange(kernellen) * np.pi / kernellen) kernel = kernel.astype(np.float32) loss.append(args.content_weight * lic.line_integral_convolution( vectors, lic_input, kernel, args.cuda)) # vgg_input = output.unsqueeze(0) # features_y = vgg(vgg_input) # style_loss = 0 # for m in range(len(features_y)): # gram_y = utils.gram_matrix(features_y[m]) # gram_s = Variable(gram_style[m].data, requires_grad=False) # style_loss += args.style_weight * mse_loss(gram_y, gram_s) # style_loss.backward() # loss[e] += style_loss loss[e].backward() optimizer.step() tbar.set_description(str(loss[e].data.cpu().numpy().item())) # save the image if ((e + 1) % args.log_interval == 0): # print("iter: %d content_loss: %f style_loss %f" % (e, loss[e].item(), style_loss.item())) utils.tensor_save_bgrimage(output.data, "output_iter_" + str(e + 1) + ".jpg", args.cuda)
def optimize(args): style_image = utils.tensor_load_rgbimage(args.style_image, size=args.style_size) style_image = style_image.unsqueeze(0) style_image = Variable(utils.preprocess_batch(style_image), requires_grad=False) style_image = utils.subtract_imagenet_mean_batch(style_image) # generate the vector field that we want to backward from size = args.content_size vectors = np.zeros((size, size, 2), dtype=np.float32) vortex_spacing = 0.5 extra_factor = 2. a = np.array([1, 0]) * vortex_spacing b = np.array([np.cos(np.pi / 3), np.sin(np.pi / 3)]) * vortex_spacing rnv = int(2 * extra_factor / vortex_spacing) vortices = [ n * a + m * b for n in range(-rnv, rnv) for m in range(-rnv, rnv) ] vortices = [(x, y) for (x, y) in vortices if -extra_factor < x < extra_factor and -extra_factor < y < extra_factor] xs = np.linspace(-1, 1, size).astype(np.float32)[None, :] ys = np.linspace(-1, 1, size).astype(np.float32)[:, None] for (x, y) in vortices: rsq = (xs - x)**2 + (ys - y)**2 vectors[..., 0] += (ys - y) / rsq vectors[..., 1] += -(xs - x) / rsq # for y in range(size): # for x in range(size): # xx = float(x - size / 2) # yy = float(y - size / 2) # rsq = xx ** 2 + yy ** 2 # if rsq == 0: # vectors[y, x, 0] = 1 # vectors[y, x, 1] = 1 # else: # vectors[y, x, 0] = -yy / rsq # vectors[y, x, 1] = xx / rsq # # vectors[y, x, 0] = 1 # # vectors[y, x, 1] = -1 vectors = utils.tensor_load_vector_field(vectors) # load the pre-trained vgg-16 and extract features vgg = Vgg16() utils.init_vgg16(args.vgg_model_dir) vgg.load_state_dict( torch.load(os.path.join(args.vgg_model_dir, 'vgg16.weight'))) if args.cuda: style_image = style_image.cuda() vgg.cuda() features_style = vgg(style_image) gram_style = [utils.gram_matrix(y) for y in features_style] # load the sobel network sobel = Sobel() if args.cuda: vectors = vectors.cuda() sobel.cuda() # init optimizer vectors_size = vectors.data.size() output_size = np.asarray(vectors_size) output_size[1] = 3 output_size = torch.Size(output_size) output = Variable(torch.randn(output_size, device="cuda") * 30, requires_grad=True) optimizer = Adam([output], lr=args.lr) cosine_loss = CosineLoss() mse_loss = torch.nn.MSELoss() #optimize the images tbar = trange(args.iters) for e in tbar: utils.imagenet_clamp_batch(output, 0, 255) optimizer.zero_grad() sobel_input = utils.gray_bgr_batch(output) sobel_y = sobel(sobel_input) content_loss = args.content_weight * cosine_loss(vectors, sobel_y) vgg_input = output features_y = vgg(vgg_input) style_loss = 0 for m in range(len(features_y)): gram_y = utils.gram_matrix(features_y[m]) gram_s = Variable(gram_style[m].data, requires_grad=False) style_loss += args.style_weight * mse_loss(gram_y, gram_s) total_loss = content_loss + style_loss total_loss.backward() optimizer.step() if ((e + 1) % args.log_interval == 0): print("iter: %d content_loss: %f style_loss %f" % (e, content_loss.item() / args.content_weight, style_loss.item() / args.style_weight)) tbar.set_description(str(total_loss.data.cpu().numpy().item())) # save the image output = utils.add_imagenet_mean_batch_device(output, args.cuda) utils.tensor_save_bgrimage(output.data[0], args.output_image, args.cuda)
def train(args): check_paths(args) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed) kwargs = {'num_workers': 0, 'pin_memory': False} else: kwargs = {} transform = transforms.Compose([ transforms.Scale(args.image_size), transforms.CenterCrop(args.image_size), transforms.ToTensor(), transforms.Lambda(lambda x: x.mul(255)) ]) train_dataset = datasets.ImageFolder(args.dataset, transform) train_loader = DataLoader(train_dataset, batch_size=args.batch_size, **kwargs) style_model = Net(ngf=args.ngf) if args.resume is not None: print('Resuming, initializing using weight from {}.'.format( args.resume)) style_model.load_state_dict(torch.load(args.resume)) print(style_model) optimizer = Adam(style_model.parameters(), args.lr) mse_loss = torch.nn.MSELoss() vgg = Vgg16() utils.init_vgg16(args.vgg_model_dir) vgg.load_state_dict( torch.load(os.path.join(args.vgg_model_dir, "vgg16.weight"))) if args.cuda: style_model.cuda() vgg.cuda() style_loader = utils.StyleLoader(args.style_folder, args.style_size) tbar = trange(args.epochs) for e in tbar: style_model.train() agg_content_loss = 0. agg_style_loss = 0. count = 0 for batch_id, (x, _) in enumerate(train_loader): n_batch = len(x) count += n_batch optimizer.zero_grad() x = Variable(utils.preprocess_batch(x)) if args.cuda: x = x.cuda() style_v = style_loader.get(batch_id) style_model.setTarget(style_v) style_v = utils.subtract_imagenet_mean_batch(style_v) features_style = vgg(style_v) gram_style = [utils.gram_matrix(y) for y in features_style] y = style_model(x) xc = Variable(x.data.clone()) y = utils.subtract_imagenet_mean_batch(y) xc = utils.subtract_imagenet_mean_batch(xc) features_y = vgg(y) features_xc = vgg(xc) f_xc_c = Variable(features_xc[1].data, requires_grad=False) content_loss = args.content_weight * mse_loss( features_y[1], f_xc_c) style_loss = 0. for m in range(len(features_y)): gram_y = utils.gram_matrix(features_y[m]) gram_s = Variable(gram_style[m].data, requires_grad=False).repeat( args.batch_size, 1, 1, 1) style_loss += args.style_weight * mse_loss( gram_y, gram_s[:n_batch, :, :]) total_loss = content_loss + style_loss total_loss.backward() optimizer.step() agg_content_loss += content_loss.data[0] agg_style_loss += style_loss.data[0] if (batch_id + 1) % args.log_interval == 0: mesg = "{}\tEpoch {}:\t[{}/{}]\tcontent: {:.6f}\tstyle: {:.6f}\ttotal: {:.6f}".format( time.ctime(), e + 1, count, len(train_dataset), agg_content_loss / (batch_id + 1), agg_style_loss / (batch_id + 1), (agg_content_loss + agg_style_loss) / (batch_id + 1)) tbar.set_description(mesg) if (batch_id + 1) % (4 * args.log_interval) == 0: # save model style_model.eval() style_model.cpu() save_model_filename = "Epoch_" + str(e) + "iters_" + str(count) + "_" + \ str(time.ctime()).replace(' ', '_') + "_" + str( args.content_weight) + "_" + str(args.style_weight) + ".model" save_model_path = os.path.join(args.save_model_dir, save_model_filename) torch.save(style_model.state_dict(), save_model_path) style_model.train() style_model.cuda() tbar.set_description("\nCheckpoint, trained model saved at", save_model_path) # save model style_model.eval() style_model.cpu() save_model_filename = "Final_epoch_" + str(args.epochs) + "_" + \ str(time.ctime()).replace(' ', '_') + "_" + str( args.content_weight) + "_" + str(args.style_weight) + ".model" save_model_path = os.path.join(args.save_model_dir, save_model_filename) torch.save(style_model.state_dict(), save_model_path) print("\nDone, trained model saved at", save_model_path)
def train(args): np.random.seed(args.seed) torch.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed) kwargs = {'num_workers': 0, 'pin_memory': False} else: kwargs = {} transform = transforms.Compose([transforms.Scale(args.image_size), transforms.CenterCrop(args.image_size), transforms.ToTensor(), transforms.Lambda(lambda x: x.mul(255))]) train_dataset = datasets.ImageFolder(args.dataset, transform) train_loader = DataLoader(train_dataset, batch_size=args.batch_size, **kwargs) transformer = TransformerNet() if (args.premodel != ""): transformer.load_state_dict(torch.load(args.premodel)) print("load pretrain model:"+args.premodel) optimizer = Adam(transformer.parameters(), args.lr) mse_loss = torch.nn.MSELoss() vgg = Vgg16() utils.init_vgg16(args.vgg_model_dir) vgg.load_state_dict(torch.load(os.path.join(args.vgg_model_dir, "vgg16.weight"))) if args.cuda: transformer.cuda() vgg.cuda() style = utils.tensor_load_rgbimage(args.style_image, size=args.style_size) style = style.repeat(args.batch_size, 1, 1, 1) style = utils.preprocess_batch(style) if args.cuda: style = style.cuda() style_v = Variable(style, volatile=True) style_v = utils.subtract_imagenet_mean_batch(style_v) features_style = vgg(style_v) gram_style = [utils.gram_matrix(y) for y in features_style] hori=0 writer = SummaryWriter(args.logdir,comment=args.logdir) for e in range(args.epochs): transformer.train() agg_content_loss = 0. agg_style_loss = 0. agg_cate_loss = 0. agg_cam_loss = 0. count = 0 for batch_id, (x, _) in enumerate(train_loader): n_batch = len(x) count += n_batch optimizer.zero_grad() x = Variable(utils.preprocess_batch(x)) if args.cuda: x = x.cuda() y = transformer(x) xc = Variable(x.data.clone(), volatile=True) #print(y.size()) #(4L, 3L, 224L, 224L) # Calculate focus loss and category loss y_cam = utils.depreprocess_batch(y) y_cam = utils.subtract_mean_std_batch(y_cam) xc_cam = utils.depreprocess_batch(xc) xc_cam = utils.subtract_mean_std_batch(xc_cam) del features_blobs[:] logit_x = net(xc_cam) logit_y = net(y_cam) label=[] cam_loss = 0 for i in range(len(xc_cam)): h_x = F.softmax(logit_x[i]) probs_x, idx_x = h_x.data.sort(0, True) label.append(idx_x[0]) h_y = F.softmax(logit_y[i]) probs_y, idx_y = h_y.data.sort(0, True) x_cam = returnCAM(features_blobs[0][i], weight_softmax, idx_x[0]) x_cam = Variable(x_cam.data,requires_grad = False) y_cam = returnCAM(features_blobs[1][i], weight_softmax, idx_y[0]) cam_loss += mse_loss(y_cam, x_cam) #the focus loss cam_loss *= 80 #the category loss label = Variable(torch.LongTensor(label),requires_grad = False).cuda() cate_loss = 10000 * torch.nn.CrossEntropyLoss()(logit_y,label) y = utils.subtract_imagenet_mean_batch(y) xc = utils.subtract_imagenet_mean_batch(xc) features_y = vgg(y) features_xc = vgg(xc) #f_xc_c = Variable(features_xc[1].data, requires_grad=False) #content_loss = args.content_weight * mse_loss(features_y[1], f_xc_c) f_xc_c = Variable(features_xc[2].data, requires_grad=False) content_loss = args.content_weight * mse_loss(features_y[2], f_xc_c) style_loss = 0. for m in range(len(features_y)): gram_s = Variable(gram_style[m].data, requires_grad=False) gram_y = utils.gram_matrix(features_y[m]) style_loss += args.style_weight * mse_loss(gram_y, gram_s[:n_batch, :, :]) #add the total four loss and backward total_loss = style_loss + content_loss + cam_loss + cate_loss total_loss.backward() optimizer.step() #something for display agg_content_loss += content_loss.data[0] agg_style_loss += style_loss.data[0] agg_cate_loss += cate_loss.data[0] agg_cam_loss += cam_loss.data[0] writer.add_scalar("Loss_Cont", agg_content_loss / (batch_id + 1), hori) writer.add_scalar("Loss_Style", agg_style_loss / (batch_id + 1), hori) writer.add_scalar("Loss_CAM", agg_cam_loss / (batch_id + 1), hori) writer.add_scalar("Loss_Cate", agg_cate_loss / (batch_id + 1), hori) hori += 1 if (batch_id + 1) % args.log_interval == 0: mesg = "{}Epoch{}:[{}/{}] content:{:.2f} style:{:.2f} cate:{:.2f} cam:{:.2f} total:{:.2f}".format( time.strftime("%a %H:%M:%S"),e + 1, count, len(train_dataset), agg_content_loss / (batch_id + 1), agg_style_loss / (batch_id + 1), agg_cate_loss / (batch_id + 1), agg_cam_loss / (batch_id + 1), (agg_content_loss + agg_style_loss + agg_cate_loss + agg_cam_loss ) / (batch_id + 1) ) print(mesg) if (batch_id + 1) % 2500 == 0: transformer.eval() transformer.cpu() save_model_filename = "epoch_" + str(e+1) + "_" + str(time.ctime()).replace(' ', '_') + "_" + str( args.content_weight) + "_" + str(args.style_weight) + ".model" save_model_path = os.path.join(args.save_model_dir, save_model_filename) torch.save(transformer.state_dict(), save_model_path) transformer.cuda() transformer.train() print("saved at ",count) # save model transformer.eval() transformer.cpu() save_model_filename = "epoch_" + str(args.epochs) + "_" + str(time.ctime()).replace(' ', '_') + "_" + str( args.content_weight) + "_" + str(args.style_weight) + ".model" save_model_path = os.path.join(args.save_model_dir, save_model_filename) torch.save(transformer.state_dict(), save_model_path) writer.close() print("\nDone, trained model saved at", save_model_path)
def train(): check_point_path = '' transform = transforms.Compose([transforms.Scale(IMAGE_SIZE), transforms.CenterCrop(IMAGE_SIZE), transforms.ToTensor(), transforms.Lambda(lambda x: x.mul(255))]) train_dataset = datasets.ImageFolder(DATASET_FOLDER, transform) train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE) style_model = Net(ngf=FILTER_CHANNEL, dv=device).to(device) if RESUME is not None: print('Resuming, initializing using weight from {}.'.format(RESUME)) style_model.load_state_dict(torch.load(RESUME)) print(style_model) optimizer = Adam(style_model.parameters(), LEARNING_RATE) mse_loss = torch.nn.MSELoss() vgg = Vgg16() utils.init_vgg16(VGG_DIR) vgg.load_state_dict(torch.load(os.path.join(VGG_DIR, "vgg16.weight"))) vgg.to(device) style_loader = utils.StyleLoader(STYLE_FOLDER, IMAGE_SIZE, device) tbar = tqdm(range(EPOCHS)) for e in tbar: style_model.train() agg_content_loss = 0. agg_style_loss = 0. count = 0 for batch_id, (x, _) in enumerate(train_loader): n_batch = len(x) count += n_batch optimizer.zero_grad() x = Variable(utils.preprocess_batch(x)).to(device) style_v = style_loader.get(batch_id) style_model.setTarget(style_v) style_v = utils.subtract_imagenet_mean_batch(style_v, device) features_style = vgg(style_v) gram_style = [utils.gram_matrix(y) for y in features_style] y = style_model(x) xc = Variable(x.data.clone()) y = utils.subtract_imagenet_mean_batch(y, device) xc = utils.subtract_imagenet_mean_batch(xc, device) features_y = vgg(y) features_xc = vgg(xc) f_xc_c = Variable(features_xc[1].data, requires_grad=False) content_loss = CONT_WEIGHT * mse_loss(features_y[1], f_xc_c) style_loss = 0. for m in range(len(features_y)): gram_y = utils.gram_matrix(features_y[m]) gram_s = Variable(gram_style[m].data, requires_grad=False).repeat(BATCH_SIZE, 1, 1, 1) style_loss += STYLE_WEIGHT * mse_loss(gram_y.unsqueeze_(1), gram_s[:n_batch, :, :]) total_loss = content_loss + style_loss total_loss.backward() optimizer.step() agg_content_loss += content_loss.data[0] agg_style_loss += style_loss.data[0] if (batch_id + 1) % 100 == 0: mesg = "{}\tEpoch {}:\t[{}/{}]\tcontent: {:.6f}\tstyle: {:.6f}\ttotal: {:.6f}".format( time.ctime(), e + 1, count, len(train_dataset), agg_content_loss / (batch_id + 1), agg_style_loss / (batch_id + 1), (agg_content_loss + agg_style_loss) / (batch_id + 1) ) tbar.set_description(mesg) if (batch_id + 1) % (4 * 100) == 0: # save model style_model.eval() style_model.cpu() save_model_filename = "Epoch_" + str(e) + "iters_" + str(count) + "_" + str(time.ctime()).replace(' ', '_') + "_" + str( CONT_WEIGHT) + "_" + str(STYLE_WEIGHT) + ".model" save_model_path = os.path.join(SAVE_MODEL_DIR, save_model_filename) torch.save(style_model.state_dict(), save_model_path) if check_point_path: os.remove(check_point_path) check_point_path = save_model_path style_model.train() style_model.cuda() tbar.set_description("\nCheckpoint, trained model saved at", save_model_path) # save model style_model.eval() style_model.cpu() save_model_filename = "Final_epoch_" + str(EPOCHS) + "_" + str(time.ctime()).replace(' ', '_') + "_" + str( CONT_WEIGHT) + "_" + str(STYLE_WEIGHT) + ".model" save_model_path = os.path.join(SAVE_MODEL_DIR, save_model_filename) torch.save(style_model.state_dict(), save_model_path) print("\nDone, trained model saved at", save_model_path)
0.02, gpu_id=device) net_r = define_G(opt.input_nc_r, opt.output_nc_r, opt.ngf, opt.netG, 'batch', False, 'normal', 0.02, gpu_id=device) # VGG for perceptual loss if opt.lamb_content > 0: vgg = Vgg16() init_vgg16(root_path) vgg.load_state_dict(torch.load(os.path.join(root_path, "vgg16.weight"))) vgg.to(device) # define loss criterionL1 = nn.L1Loss().to(device) criterionL2 = nn.MSELoss().to(device) criterionMSE = nn.MSELoss().to(device) criterionSSIM = SSIM(data_range=255, size_average=True, channel=3) criterionMSSSIM1 = MS_SSIM(data_range=255, size_average=True, channel=1) criterionMSSSIM3 = MS_SSIM(data_range=255, size_average=True, channel=3) # setup optimizer optimizer_i = optim.Adam(net_i.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))
def train(args): np.random.seed(args.seed) torch.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed) kwargs = {'num_workers': 0, 'pin_memory': False} else: kwargs = {} training_set = np.loadtxt(args.dataset, dtype=np.float32) training_set_size = training_set.shape[1] num_batch = int(training_set_size / args.batch_size) transformer = TransformerNet() optimizer = Adam(transformer.parameters(), args.lr) mse_loss = torch.nn.MSELoss() vgg = Vgg16() utils.init_vgg16(args.vgg_model_dir) vgg.load_state_dict( torch.load(os.path.join(args.vgg_model_dir, "vgg16.weight"))) if args.cuda: transformer.cuda() vgg.cuda() style = np.loadtxt(args.style_image, dtype=np.float32) style = style.reshape((1, 1, args.style_size_x, args.style_size_y)) style = torch.from_numpy(style) style = style.repeat(args.batch_size, 3, 1, 1) if args.cuda: style = style.cuda() style_v = Variable(style, volatile=True) style_v = utils.subtract_imagenet_mean_batch(style_v) features_style = vgg(style_v) gram_style = [utils.gram_matrix(y) for y in features_style] # Hard data if args.hard_data: hard_data = np.loadtxt(args.hard_data_file) # if not isinstance(hard_data[0], list): # hard_data = [hard_data] for e in range(args.epochs): transformer.train() agg_content_loss = 0. agg_style_loss = 0. count = 0 # for batch_id, (x, _) in enumerate(train_loader): for batch_id in range(num_batch): x = training_set[:, batch_id * args.batch_size:(batch_id + 1) * args.batch_size] n_batch = x.shape[1] count += n_batch x = x.transpose() x = x.reshape((n_batch, 1, args.image_size_x, args.image_size_y)) # plt.imshow(x[0,:,:,:].squeeze(0)) # plt.show() x = torch.from_numpy(x).float() optimizer.zero_grad() x = Variable(x) if args.cuda: x = x.cuda() y = transformer(x) if args.hard_data: hard_data_loss = 0 num_hard_data = 0 for hd in hard_data: hard_data_loss += args.hard_data_weight * ( y[:, 0, hd[1], hd[0]] - hd[2] * 255.0).norm()**2 / n_batch num_hard_data += 1 hard_data_loss /= num_hard_data y = y.repeat(1, 3, 1, 1) # x = Variable(utils.preprocess_batch(x)) # xc = x.data.clone() # xc = xc.repeat(1, 3, 1, 1) # xc = Variable(xc, volatile=True) y = utils.subtract_imagenet_mean_batch(y) # xc = utils.subtract_imagenet_mean_batch(xc) features_y = vgg(y) # features_xc = vgg(xc) # f_xc_c = Variable(features_xc[1].data, requires_grad=False) # content_loss = args.content_weight * mse_loss(features_y[1], f_xc_c) style_loss = 0. for m in range(len(features_y)): gram_s = Variable(gram_style[m].data, requires_grad=False) gram_y = utils.gram_matrix(features_y[m]) style_loss += args.style_weight * mse_loss( gram_y, gram_s[:n_batch, :, :]) # total_loss = content_loss + style_loss total_loss = style_loss if args.hard_data: total_loss += hard_data_loss total_loss.backward() optimizer.step() # agg_content_loss += content_loss.data[0] agg_style_loss += style_loss.data[0] if (batch_id + 1) % args.log_interval == 0: if args.hard_data: mesg = "{}\tEpoch {}:\t[{}/{}]\tcontent: {:.6f}\tstyle: {:.6f}\thard_data: {:.6f}\ttotal: {:.6f}".format( time.ctime(), e + 1, count, num_batch, agg_content_loss / (batch_id + 1), agg_style_loss / (batch_id + 1), hard_data_loss.data[0], (agg_content_loss + agg_style_loss) / (batch_id + 1)) else: mesg = "{}\tEpoch {}:\t[{}/{}]\tcontent: {:.6f}\tstyle: {:.6f}\ttotal: {:.6f}".format( time.ctime(), e + 1, count, num_batch, agg_content_loss / (batch_id + 1), agg_style_loss / (batch_id + 1), (agg_content_loss + agg_style_loss) / (batch_id + 1)) print(mesg) # save model transformer.eval() transformer.cpu() save_model_filename = "epoch_" + str(args.epochs) + "_" + str( time.ctime()).replace(' ', '_') + "_" + str( args.content_weight) + "_" + str(args.style_weight) + ".model" save_model_path = os.path.join(args.save_model_dir, save_model_filename) torch.save(transformer.state_dict(), save_model_path) print("\nDone, trained model saved at", save_model_path)
def train(args): serialNumFile = "serialNum.txt" serial = 0 if os.path.isfile(serialNumFile): with open(serialNumFile, "r") as t: serial = int(t.read()) serial += 1 with open(serialNumFile, "w") as t: t.write(str(serial)) if args.mysql: cnx = mysql.connector.connect(user='******', database='midburn', password='******') cursor = cnx.cursor() location = args.dataset.split("/") if location[-1] == "": location = location[-2] else: location = location[-1] save_model_filename = str(serial) + "_" + extractName( args.style_image) + "_" + str(args.epochs) + "_" + str( int(args.content_weight)) + "_" + str(int( args.style_weight)) + "_size_" + str( args.image_size) + "_dataset_" + str(location) + ".model" print(save_model_filename) np.random.seed(args.seed) torch.manual_seed(args.seed) m_epoch = 0 if args.cuda: torch.cuda.manual_seed(args.seed) #kwargs = {'num_workers': 0, 'pin_memory': False} kwargs = {'num_workers': 4, 'pin_memory': True} else: kwargs = {} transform = transforms.Compose([ transforms.Scale(args.image_size), transforms.CenterCrop(args.image_size), transforms.ToTensor(), transforms.Lambda(lambda x: x.mul(255)) ]) train_dataset = datasets.ImageFolder(args.dataset, transform) train_loader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, **kwargs) transformer = TransformerNet() #transformer = ResNeXtNet() transformer_type = transformer.__class__.__name__ optimizer = Adam(transformer.parameters(), args.lr) if args.l1: loss_criterion = torch.nn.L1Loss() else: loss_criterion = torch.nn.MSELoss() loss_type = loss_criterion.__class__.__name__ if args.visdom: vis = VisdomLinePlotter("Style Transfer: " + transformer_type) else: vis = None vgg = Vgg16() utils.init_vgg16(args.vgg_model_dir) vgg.load_state_dict( torch.load(os.path.join(args.vgg_model_dir, "vgg16.weight"))) if args.cuda: transformer.cuda() vgg.cuda() if args.model is not None: transformer.load_state_dict(torch.load(args.model)) save_model_filename = save_model_filename + "@@@@@@" + str( int(getEpoch(args.model)) + int(args.epochs)) m_epoch += int(getEpoch(args.model)) print("loaded model\n") for param in vgg.parameters(): param.requires_grad = False with torch.no_grad(): style = utils.tensor_load_rgbimage(args.style_image, size=args.style_size) style = style.repeat(args.batch_size, 1, 1, 1) style = utils.preprocess_batch(style) if args.cuda: style = style.cuda() style = utils.subtract_imagenet_mean_batch(style) features_style = vgg(style) gram_style = [utils.gram_matrix(y) for y in features_style] del features_style del style # TODO: scheduler and style-loss criterion unused at the moment scheduler = StepLR(optimizer, step_size=15000 // args.batch_size) style_loss_criterion = torch.nn.CosineSimilarity() total_count = 0 if args.mysql: q1 = ("REPLACE INTO `images`(`name`) VALUES ('" + args.style_image + "')") cursor.execute(q1) cnx.commit() imgId = cursor.lastrowid for e in range(args.epochs): transformer.train() agg_content_loss = 0. agg_style_loss = 0. count = 0 for batch_id, (x, _) in enumerate(train_loader): n_batch = len(x) count += n_batch total_count += n_batch optimizer.zero_grad() x = utils.preprocess_batch(x) if args.cuda: x = x.cuda() y = transformer(x) y = utils.subtract_imagenet_mean_batch(y) xc = utils.subtract_imagenet_mean_batch(x) features_y = vgg(y) f_xc_c = vgg.content_features(xc) content_loss = args.content_weight * loss_criterion( features_y[1], f_xc_c) style_loss = 0. for m in range(len(features_y)): gram_s = gram_style[m] gram_y = utils.gram_matrix(features_y[m]) style_loss += loss_criterion(gram_y, gram_s[:n_batch, :, :]) #style_loss -= style_loss_criterion(gram_y, gram_s[:n_batch, :, :]) style_loss *= args.style_weight total_loss = content_loss + style_loss total_loss.backward() optimizer.step() # TODO: enable #scheduler.step() agg_content_loss += content_loss.item() agg_style_loss += style_loss.item() if (batch_id + 1) % args.log_interval == 0: if args.mysql: q1 = ( "REPLACE INTO `statistics`(`imgId`,`epoch`, `iteration_id`, `content_loss`, `style_loss`, `loss`) VALUES (" + str(imgId) + "," + str(int(e) + m_epoch) + "," + str(batch_id) + "," + str(agg_content_loss / (batch_id + 1)) + "," + str(agg_style_loss / (batch_id + 1)) + "," + str( (agg_content_loss + agg_style_loss) / (batch_id + 1)) + ")") cursor.execute(q1) cnx.commit() mesg = "{}\tEpoch {}:\t[{}/{}]\tcontent: {:.6f}\tstyle: {:.6f}\ttotal: {:.6f}\n".format( time.ctime(), e + 1, count, len(train_dataset), agg_content_loss / (batch_id + 1), agg_style_loss / (batch_id + 1), (agg_content_loss + agg_style_loss) / (batch_id + 1)) sys.stdout.flush() print(mesg) if vis is not None: vis.plot(loss_type, "Content Loss", total_count, content_loss.item()) vis.plot(loss_type, "Style Loss", total_count, style_loss.item()) vis.plot(loss_type, "Total Loss", total_count, total_loss.item()) # save model transformer.eval() transformer.cpu() save_model_path = os.path.join(args.save_model_dir, save_model_filename) torch.save(transformer.state_dict(), save_model_path) print("\nDone, trained model saved at", save_model_path)