-
Notifications
You must be signed in to change notification settings - Fork 55
/
model.py
executable file
·212 lines (157 loc) · 11.1 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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import os
import tensorflow as tf
from module import discriminator, generator_gatedcnn, domain_classifier
from datetime import datetime
import numpy as np
from preprocess import *
class StarGANVC(object):
def __init__(self,
num_features,
frames=FRAMES,
batchsize=8,
discriminator=discriminator,
generator=generator_gatedcnn,
classifier=domain_classifier,
mode='train',
log_dir='./log'):
self.num_features = num_features
self.batchsize = batchsize
self.input_shape = [None, num_features, frames, 1]
self.label_shape = [None, SPEAKERS_NUM]
self.mode = mode
self.log_dir = log_dir
self.discriminator = discriminator
self.generator = generator_gatedcnn
self.classifier = classifier
self.build_model()
self.saver = tf.train.Saver()
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
self.sess.run(tf.global_variables_initializer())
if self.mode == 'train':
self.train_step = 0
now = datetime.now()
self.log_dir = os.path.join(log_dir, now.strftime('%Y%m%d-%H%M%S'))
self.writer = tf.summary.FileWriter(self.log_dir, tf.get_default_graph())
self.generator_summaries, self.discriminator_summaries, self.domain_classifier_summaries = self.summary()
def build_model(self):
# Placeholders for real training samples
self.input_real = tf.placeholder(tf.float32, self.input_shape, name='input_real')
self.target_real = tf.placeholder(tf.float32, self.input_shape, name='target_real')
self.source_label = tf.placeholder(tf.float32, self.label_shape, name='source_label')
self.target_label = tf.placeholder(tf.float32, self.label_shape, name='target_label')
self.target_label_reshaped = tf.placeholder(tf.float32, [None, 1, 1, SPEAKERS_NUM], name='reshaped_label_for_classifier')
self.generated_forward = self.generator(self.input_real, self.target_label, reuse=False, scope_name='generator')
self.generated_back = self.generator(self.generated_forward, self.source_label, reuse=True, scope_name='generator')
#============================Domain classify loss=============================
self.domain_out_real = self.classifier(self.target_real, reuse=False, scope_name='classifier')
self.domain_real_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.target_label_reshaped, logits=self.domain_out_real))
# ============================Generator loss================================
#Cycle loss
self.cycle_loss = tf.reduce_mean(tf.abs(self.input_real - self.generated_back))
#Identity loss
self.identity_map = self.generator(self.input_real, self.source_label, reuse=True, scope_name='generator')
self.identity_loss = tf.reduce_mean(tf.abs(self.input_real - self.identity_map))
self.discrimination_real = self.discriminator(self.target_real, self.target_label, reuse=False, scope_name='discriminator')
#combine discriminator and generator
self.discirmination = self.discriminator(self.generated_forward, self.target_label, reuse=True, scope_name='discriminator')
self.generator_loss = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(self.discirmination), logits=self.discirmination))
# Place holder for lambda_cycle and lambda_identity
self.lambda_cycle = tf.placeholder(tf.float32, None, name='lambda_cycle')
self.lambda_identity = tf.placeholder(tf.float32, None, name='lambda_identity')
self.lambda_classifier = tf.placeholder(tf.float32, None, name='lambda_classifier')
self.generator_loss_all = self.generator_loss + self.lambda_cycle * self.cycle_loss + \
self.lambda_identity * self.identity_loss +\
self.lambda_classifier * self.domain_real_loss
# =========================Discriminator loss========================
self.discirmination_fake = self.discriminator(self.generated_forward, self.target_label, reuse=True, scope_name='discriminator')
self.discrimination_real_loss = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(self.discrimination_real), logits=self.discrimination_real))
self.discrimination_fake_loss = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros_like(self.discirmination_fake), logits=self.discirmination_fake))
# calculate `x_hat`
epsilon = tf.random_uniform((self.batchsize, 1, 1, 1), 0.0, 1.0)
x_hat = epsilon * self.generated_forward + (1.0 - epsilon) * self.input_real
# gradient penalty
gradients = tf.gradients(self.discriminator(x_hat, self.target_label, reuse=True, scope_name='discriminator'), [x_hat])
_gradient_penalty = 10.0 * tf.square(tf.norm(gradients[0], ord=2) - 1.0)
self.domain_out_fake = self.classifier(self.generated_forward, reuse=True, scope_name='classifier')
self.domain_fake_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.target_label_reshaped, logits=self.domain_out_fake))
self.discrimator_loss = self.discrimination_fake_loss + self.discrimination_real_loss + _gradient_penalty + self.domain_fake_loss
#================================================================================
# Categorize variables because we have to optimize the three sets of the variables separately
trainable_variables = tf.trainable_variables()
self.discriminator_vars = [var for var in trainable_variables if 'discriminator' in var.name]
self.generator_vars = [var for var in trainable_variables if 'generator' in var.name]
self.classifier_vars = [var for var in trainable_variables if 'classifier' in var.name]
#optimizer
self.generator_learning_rate = tf.placeholder(tf.float32, None, name='generator_learning_rate')
self.discriminator_learning_rate = tf.placeholder(tf.float32, None, name='discriminator_learning_rate')
self.classifier_learning_rate = tf.placeholder(tf.float32, None, name="domain_classifier_learning_rate")
self.discriminator_optimizer = tf.train.AdamOptimizer(
learning_rate=self.discriminator_learning_rate, beta1=0.5).minimize(
self.discrimator_loss, var_list=self.discriminator_vars)
self.generator_optimizer = tf.train.AdamOptimizer(
learning_rate=self.generator_learning_rate, beta1=0.5).minimize(
self.generator_loss_all, var_list=self.generator_vars)
self.classifier_optimizer = tf.train.AdamOptimizer(learning_rate=self.classifier_learning_rate).minimize(
self.domain_real_loss, var_list=self.classifier_vars)
# test
self.input_test = tf.placeholder(tf.float32, self.input_shape, name='input_test')
self.target_label_test = tf.placeholder(tf.float32, self.label_shape, name='target_label_test')
self.generation_test = self.generator(self.input_test, self.target_label_test, reuse=True, scope_name='generator')
def train(self, input_source, input_target, source_label, target_label, lambda_cycle=1.0, \
lambda_identity=1.0, lambda_classifier=1.0, \
generator_learning_rate=0.0001, \
discriminator_learning_rate=0.0001, \
classifier_learning_rate=0.0001):
target_label = np.array(target_label, dtype=np.float32)
target_label_reshaped = np.reshape(target_label, [target_label.shape[0], 1, 1, SPEAKERS_NUM])
domain_classifier_real_loss, _, domain_classifier_summaries = self.sess.run(\
[self.domain_real_loss, self.classifier_optimizer, self.domain_classifier_summaries],\
feed_dict={self.input_real: input_source, self.target_label:target_label, self.target_real:input_target, \
self.target_label_reshaped:target_label_reshaped, \
self.classifier_learning_rate:classifier_learning_rate}
)
self.writer.add_summary(domain_classifier_summaries, self.train_step)
generation_f, _, generator_loss, _, generator_summaries = self.sess.run(
[self.generated_forward, self.generated_back, self.generator_loss, self.generator_optimizer, self.generator_summaries], \
feed_dict = {self.lambda_cycle: lambda_cycle, self.lambda_identity: lambda_identity, self.lambda_classifier:lambda_classifier ,\
self.input_real: input_source, self.target_real: input_target,\
self.source_label:source_label, self.target_label:target_label, \
self.target_label_reshaped:target_label_reshaped, \
self.generator_learning_rate: generator_learning_rate})
self.writer.add_summary(generator_summaries, self.train_step)
discriminator_loss, _, discriminator_summaries = self.sess.run(\
[self.discrimator_loss, self.discriminator_optimizer, self.discriminator_summaries], \
feed_dict = {self.input_real: input_source, self.target_real: input_target , self.target_label:target_label,\
self.target_label_reshaped:target_label_reshaped, \
self.discriminator_learning_rate: discriminator_learning_rate})
self.writer.add_summary(discriminator_summaries, self.train_step)
self.train_step += 1
return generator_loss, discriminator_loss, domain_classifier_real_loss
def summary(self):
with tf.name_scope('generator_summaries'):
cycle_loss_summary = tf.summary.scalar('cycle_loss', self.cycle_loss)
identity_loss_summary = tf.summary.scalar('identity_loss', self.identity_loss)
generator_loss_summary = tf.summary.scalar('generator_loss', self.generator_loss)
generator_summaries = tf.summary.merge([cycle_loss_summary, identity_loss_summary, generator_loss_summary])
with tf.name_scope('discriminator_summaries'):
discriminator_loss_summary = tf.summary.scalar('discriminator_loss', self.discrimator_loss)
discriminator_summaries = tf.summary.merge([discriminator_loss_summary])
with tf.name_scope('domain_classifier_summaries'):
domain_real_loss = tf.summary.scalar('domain_real_loss', self.domain_real_loss)
domain_classifer_summaries = tf.summary.merge([domain_real_loss])
return generator_summaries, discriminator_summaries, domain_classifer_summaries
def test(self, inputs, label):
generation = self.sess.run(self.generation_test, feed_dict={self.input_test: inputs, self.target_label_test: label})
return generation
def save(self, directory, filename):
if not os.path.exists(directory):
os.makedirs(directory)
self.saver.save(self.sess, os.path.join(directory, filename))
return os.path.join(directory, filename)
def load(self, filepath):
self.saver.restore(self.sess, filepath)
if __name__ == '__main__':
starganvc = StarGANVC(36)