Spaces:
Runtime error
Runtime error
Muhammad Rama Nurimani
commited on
Commit
·
7ec346b
1
Parent(s):
45f3c3c
test deploy
Browse files- template_model.py +99 -0
template_model.py
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Model class template
|
2 |
+
|
3 |
+
This module provides a template for users to implement custom models.
|
4 |
+
You can specify '--model template' to use this model.
|
5 |
+
The class name should be consistent with both the filename and its model option.
|
6 |
+
The filename should be <model>_dataset.py
|
7 |
+
The class name should be <Model>Dataset.py
|
8 |
+
It implements a simple image-to-image translation baseline based on regression loss.
|
9 |
+
Given input-output pairs (data_A, data_B), it learns a network netG that can minimize the following L1 loss:
|
10 |
+
min_<netG> ||netG(data_A) - data_B||_1
|
11 |
+
You need to implement the following functions:
|
12 |
+
<modify_commandline_options>: Add model-specific options and rewrite default values for existing options.
|
13 |
+
<__init__>: Initialize this model class.
|
14 |
+
<set_input>: Unpack input data and perform data pre-processing.
|
15 |
+
<forward>: Run forward pass. This will be called by both <optimize_parameters> and <test>.
|
16 |
+
<optimize_parameters>: Update network weights; it will be called in every training iteration.
|
17 |
+
"""
|
18 |
+
import torch
|
19 |
+
from base_model import BaseModel
|
20 |
+
import networks
|
21 |
+
|
22 |
+
|
23 |
+
class TemplateModel(BaseModel):
|
24 |
+
@staticmethod
|
25 |
+
def modify_commandline_options(parser, is_train=True):
|
26 |
+
"""Add new model-specific options and rewrite default values for existing options.
|
27 |
+
|
28 |
+
Parameters:
|
29 |
+
parser -- the option parser
|
30 |
+
is_train -- if it is training phase or test phase. You can use this flag to add training-specific or test-specific options.
|
31 |
+
|
32 |
+
Returns:
|
33 |
+
the modified parser.
|
34 |
+
"""
|
35 |
+
parser.set_defaults(dataset_mode='aligned') # You can rewrite default values for this model. For example, this model usually uses aligned dataset as its dataset.
|
36 |
+
if is_train:
|
37 |
+
parser.add_argument('--lambda_regression', type=float, default=1.0, help='weight for the regression loss') # You can define new arguments for this model.
|
38 |
+
|
39 |
+
return parser
|
40 |
+
|
41 |
+
def __init__(self, opt):
|
42 |
+
"""Initialize this model class.
|
43 |
+
|
44 |
+
Parameters:
|
45 |
+
opt -- training/test options
|
46 |
+
|
47 |
+
A few things can be done here.
|
48 |
+
- (required) call the initialization function of BaseModel
|
49 |
+
- define loss function, visualization images, model names, and optimizers
|
50 |
+
"""
|
51 |
+
BaseModel.__init__(self, opt) # call the initialization method of BaseModel
|
52 |
+
# specify the training losses you want to print out. The program will call base_model.get_current_losses to plot the losses to the console and save them to the disk.
|
53 |
+
self.loss_names = ['loss_G']
|
54 |
+
# specify the images you want to save and display. The program will call base_model.get_current_visuals to save and display these images.
|
55 |
+
self.visual_names = ['data_A', 'data_B', 'output']
|
56 |
+
# specify the models you want to save to the disk. The program will call base_model.save_networks and base_model.load_networks to save and load networks.
|
57 |
+
# you can use opt.isTrain to specify different behaviors for training and test. For example, some networks will not be used during test, and you don't need to load them.
|
58 |
+
self.model_names = ['G']
|
59 |
+
# define networks; you can use opt.isTrain to specify different behaviors for training and test.
|
60 |
+
self.netG = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, gpu_ids=self.gpu_ids)
|
61 |
+
if self.isTrain: # only defined during training time
|
62 |
+
# define your loss functions. You can use losses provided by torch.nn such as torch.nn.L1Loss.
|
63 |
+
# We also provide a GANLoss class "networks.GANLoss". self.criterionGAN = networks.GANLoss().to(self.device)
|
64 |
+
self.criterionLoss = torch.nn.L1Loss()
|
65 |
+
# define and initialize optimizers. You can define one optimizer for each network.
|
66 |
+
# If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an example.
|
67 |
+
self.optimizer = torch.optim.Adam(self.netG.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))
|
68 |
+
self.optimizers = [self.optimizer]
|
69 |
+
|
70 |
+
# Our program will automatically call <model.setup> to define schedulers, load networks, and print networks
|
71 |
+
|
72 |
+
def set_input(self, input):
|
73 |
+
"""Unpack input data from the dataloader and perform necessary pre-processing steps.
|
74 |
+
|
75 |
+
Parameters:
|
76 |
+
input: a dictionary that contains the data itself and its metadata information.
|
77 |
+
"""
|
78 |
+
AtoB = self.opt.direction == 'AtoB' # use <direction> to swap data_A and data_B
|
79 |
+
self.data_A = input['A' if AtoB else 'B'].to(self.device) # get image data A
|
80 |
+
self.data_B = input['B' if AtoB else 'A'].to(self.device) # get image data B
|
81 |
+
self.image_paths = input['A_paths' if AtoB else 'B_paths'] # get image paths
|
82 |
+
|
83 |
+
def forward(self):
|
84 |
+
"""Run forward pass. This will be called by both functions <optimize_parameters> and <test>."""
|
85 |
+
self.output = self.netG(self.data_A) # generate output image given the input data_A
|
86 |
+
|
87 |
+
def backward(self):
|
88 |
+
"""Calculate losses, gradients, and update network weights; called in every training iteration"""
|
89 |
+
# caculate the intermediate results if necessary; here self.output has been computed during function <forward>
|
90 |
+
# calculate loss given the input and intermediate results
|
91 |
+
self.loss_G = self.criterionLoss(self.output, self.data_B) * self.opt.lambda_regression
|
92 |
+
self.loss_G.backward() # calculate gradients of network G w.r.t. loss_G
|
93 |
+
|
94 |
+
def optimize_parameters(self):
|
95 |
+
"""Update network weights; it will be called in every training iteration."""
|
96 |
+
self.forward() # first call forward to calculate intermediate results
|
97 |
+
self.optimizer.zero_grad() # clear network G's existing gradients
|
98 |
+
self.backward() # calculate gradients for network G
|
99 |
+
self.optimizer.step() # update gradients for network G
|