-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
158 lines (147 loc) · 9.17 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import tensorflow as tf
from hparams import hyperparams as hp
from networks import lstm_3_layers
from utils import get_next_batch
import numpy as np
class Graph:
def __init__(self, mode):
self.mode = mode
if self.mode in ['train', 'eval']:
if self.mode == 'train' and len(hp.gpu_ids) > 1:
self.multi_train()
else:
self.single_train()
tf.summary.scalar('{}/loss'.format(self.mode), self.loss)
self.merged = tf.summary.merge_all()
self.t_vars = tf.trainable_variables()
self.num_paras = 0
for var in self.t_vars:
var_shape = var.get_shape().as_list()
self.num_paras += np.prod(var_shape)
print("Total number of parameters : %r"%(self.num_paras))
elif self.mode in ['test']:
self.test()
elif self.mode in ['infer']:
self.infer()
else:
raise Exception('no supported mode in model __init__ function, please check ...')
###################################################################################
# #
# multi gpu train #
# #
###################################################################################
def multi_train(self):
def _assign_to_device(device, ps_device='/cpu:0'):
PS_OPS = ['Variable', 'VariableV2', 'AutoReloadVariable']
def _assign(op):
node_def = op if isinstance(op, tf.NodeDef) else op.node_def
if node_def.op in PS_OPS:
return '/' + ps_device
else:
return device
return _assign
def _average_gradients(tower_grads):
average_grads = []
for grad_and_vars in zip(*tower_grads):
grads = []
for g, _ in grad_and_vars:
expanded_g = tf.expand_dims(g, 0)
grads.append(expanded_g)
grad = tf.concat(grads, 0)
grad = tf.reduce_mean(grad, 0)
v = grad_and_vars[0][1]
grad_and_var = (grad, v)
average_grads.append(grad_and_var)
return average_grads
with tf.device('/cpu:0'):
self.x, self.y, self.mask = get_next_batch(self.mode)
self.tower_grads = []
self.global_step = tf.get_variable('global_step', initializer=0, dtype=tf.int32, trainable=False)
self.lr = tf.train.exponential_decay(hp.lr, global_step=self.global_step,
decay_steps=hp.lr_decay_steps,
decay_rate=hp.lr_decay_rate)
self.optimizer = tf.train.AdamOptimizer(learning_rate=self.lr)
gpu_nums = len(hp.gpu_ids)
per_batch = hp.batch_size // gpu_nums
with tf.variable_scope('network'):
for i in range(gpu_nums):
with tf.device(_assign_to_device('/gpu:{}'.format(hp.gpu_ids[i]), ps_device='/cpu:0')):
self._x = self.x[i * per_batch: (i + 1) * per_batch]
self._y = self.y[i * per_batch: (i + 1) * per_batch]
self._mask = self.mask[i * per_batch: (i + 1) * per_batch]
self.outputs = lstm_3_layers(self._x, num_units=hp.lab_size, bidirection=False,
scope='lstm_3_layers', reuse=tf.AUTO_REUSE)
# sigmoid, fifo-queue
self.y_hat = tf.nn.sigmoid(self.outputs)
tf.get_variable_scope().reuse_variables()
# loss
self.res = tf.abs(self.y_hat - self.y) # [B, classes]
# self.loss = tf.reduce_mean(tf.multiply(self.res, self.mask))
self.loss = tf.reduce_sum(tf.multiply(self.res, self.mask), keep_dims=True) # [B, classes]
self.count_onenum = tf.count_nonzero(self.mask, axis=-1, keep_dims=True, dtype=tf.float32) # [B, classes]
self.loss = tf.reduce_mean(tf.multiply(self.loss, self.count_onenum)) # [B, ]
grad = self.optimizer.compute_gradients(self.loss)
self.tower_grads.append(grad)
self.tower_grads = _average_gradients(self.tower_grads)
clipped = []
for grad, var in self.tower_grads:
grad = tf.clip_by_norm(grad, 5.)
clipped.append((grad, var))
self.train_op = self.optimizer.apply_gradients(clipped, global_step=self.global_step)
###################################################################################
# #
# single gpu train and eval #
# #
###################################################################################
def single_train(self):
with tf.device('/gpu:{}'.format(hp.gpu_ids[0])):
self.x, self.y, self.mask = get_next_batch(self.mode)
self.global_step = tf.get_variable('global_step', initializer=0, dtype=tf.int32, trainable=False)
self.lr = tf.train.exponential_decay(learning_rate=hp.lr, global_step=self.global_step,
decay_steps=hp.lr_decay_steps,
decay_rate=hp.lr_decay_rate)
self.optimizer = tf.train.AdamOptimizer(self.lr)
with tf.variable_scope('network'):
self.outputs = lstm_3_layers(self.x, num_units=hp.lstm_size, bidirection=False,
scope='lstm_3_layers', reuse=tf.AUTO_REUSE)
self.outputs = tf.layers.dense(self.outputs, units=hp.lstm_size//2, activation=tf.nn.tanh, name='dense1')
self.y_hat = tf.layers.dense(self.outputs, units=hp.lab_size, activation=tf.nn.sigmoid, name='dense2')
# loss
self.res = tf.abs(self.y_hat - self.y) # [B, classes]
# self.loss = tf.reduce_mean(tf.multiply(self.res, self.mask))
self.loss = tf.reduce_sum(tf.multiply(self.res, self.mask), keep_dims=True) # [B, classes]
self.count_onenum = tf.count_nonzero(self.mask, axis=-1, keep_dims=True, dtype=tf.float32) # [B, classes]
self.loss = tf.reduce_mean(tf.multiply(self.loss, self.count_onenum)) # [B, ]
self.grads = self.optimizer.compute_gradients(self.loss)
clipped = []
for grad, var in self.grads:
grad = tf.clip_by_norm(grad, 5.)
clipped.append((grad, var))
self.train_op = self.optimizer.apply_gradients(clipped, global_step=self.global_step)
###################################################################################
# #
# test data in cpu #
# #
###################################################################################
def test(self):
with tf.device('/cpu:0'):
self.x, self.y, self.mask = get_next_batch(mode=self.mode)
with tf.variable_scope('network'):
self.outputs = lstm_3_layers(self.x, num_units=hp.lab_size, bidirection=False,
scope='lstm_3_layers', reuse=tf.AUTO_REUSE)
self.outputs = tf.layers.dense(self.outputs, units=hp.lstm_size//2, activation=tf.nn.tanh, name='dense1')
self.y_hat = tf.layers.dense(self.outputs, units=hp.lab_size, activation=tf.nn.sigmoid, name='dense2')
self.y_hat = tf.multiply(self.y_hat, self.mask)
###################################################################################
# #
# real data infer in cpu #
# #
###################################################################################
def infer(self):
with tf.device('/cpu:0'):
self.x = tf.placeholder(shape=[None, None, hp.f_size], dtype=tf.float32)
with tf.variable_scope('network'):
self.y_hat = lstm_3_layers(self.x, num_units=hp.lab_size, bidirection=False,
scope='lstm_3_layers', reuse=tf.AUTO_REUSE)
self.outputs = tf.layers.dense(self.outputs, units=hp.lstm_size//2, activation=tf.nn.tanh, name='dense1')
self.y_hat = tf.layers.dense(self.outputs, units=hp.lab_size, activation=tf.nn.sigmoid, name='dense2')