fork download
  1. import logging
  2. import os
  3.  
  4. import numpy as np
  5. import tensorflow
  6. import tensorflow.keras.backend as K
  7. from tensorflow.keras import layers
  8. from tensorflow.keras import regularizers
  9. from tensorflow.keras.layers import BatchNormalization
  10. from tensorflow.keras.layers import Conv2D
  11. from tensorflow.keras.layers import Dropout
  12. from tensorflow.keras.layers import Input
  13. from tensorflow.keras.layers import Lambda, Dense
  14. from tensorflow.keras.layers import Reshape
  15. from tensorflow.keras.models import Model
  16. from tensorflow.keras.optimizers import Adam
  17.  
  18. from constants import NUM_FBANKS, NUM_FRAMES
  19. from triplet_loss import deep_speaker_loss
  20.  
  21. logger = logging.getLogger(__name__)
  22.  
  23.  
  24.  
  25.  
  26. class DeepSpeakerModel:
  27.  
  28. os.environ['PYTHONHASHSEED']=str(7381)
  29. tensorflow.random.set_seed(7381)
  30. import random
  31. random.seed(7381)
  32. np.random.seed(7381)
  33.  
  34. print("called")
  35. # I thought it was 3 but maybe energy is added at a 4th dimension.
  36. # would be better to have 4 dimensions:
  37. # MFCC, DIFF(MFCC), DIFF(DIFF(MFCC)), ENERGIES (probably tiled across the frequency domain).
  38. # this seems to help match the parameter counts.
  39. def __init__(self, batch_input_shape=(None, NUM_FRAMES, NUM_FBANKS, 1), include_softmax=False,
  40. num_speakers_softmax=None):
  41. self.include_softmax = include_softmax
  42. if self.include_softmax:
  43. assert num_speakers_softmax > 0
  44. self.clipped_relu_count = 0
  45.  
  46. # http://c...content-available-to-author-only...b.io/convolutional-networks/
  47. # conv weights
  48. # #params = ks * ks * nb_filters * num_channels_input
  49.  
  50. # Conv128-s
  51. # 5*5*128*128/2+128
  52. # ks*ks*nb_filters*channels/strides+bias(=nb_filters)
  53.  
  54. # take 100 ms -> 4 frames.
  55. # if signal is 3 seconds, then take 100ms per 100ms and average out this network.
  56. # 8*8 = 64 features.
  57.  
  58. # used to share all the layers across the inputs
  59.  
  60. # num_frames = K.shape() - do it dynamically after.
  61. inputs = Input(batch_shape=batch_input_shape, name='input')
  62. x = self.cnn_component(inputs)
  63.  
  64. x = Reshape((-1, 2048))(x)
  65. # Temporal average layer. axis=1 is time.
  66. x = Lambda(lambda y: K.mean(y, axis=1), name='average')(x)
  67. if include_softmax:
  68. logger.info('Including a Dropout layer to reduce overfitting.')
  69. # used for softmax because the dataset we pre-train on might be too small. easy to overfit.
  70. x = Dropout(0.5,seed=7381)(x)
  71. x = Dense(512, name='affine')(x)
  72. if include_softmax:
  73. # Those weights are just when we train on softmax.
  74. x = Dense(num_speakers_softmax, activation='softmax')(x)
  75. else:
  76. # Does not contain any weights.
  77. x = Lambda(lambda y: K.l2_normalize(y, axis=1), name='ln')(x)
  78. self.m = Model(inputs, x, name='ResCNN')
  79.  
  80. def keras_model(self):
  81. return self.m
  82.  
  83. def get_weights(self):
  84. w = self.m.get_weights()
  85. if self.include_softmax:
  86. w.pop() # last 2 are the W_softmax and b_softmax.
  87. w.pop()
  88. return w
  89.  
  90. def clipped_relu(self, inputs):
  91. relu = Lambda(lambda y: K.minimum(K.maximum(y, 0), 20), name=f'clipped_relu_{self.clipped_relu_count}')(inputs)
  92. self.clipped_relu_count += 1
  93. return relu
  94.  
  95. def identity_block(self, input_tensor, kernel_size, filters, stage, block):
  96. conv_name_base = f'res{stage}_{block}_branch'
  97.  
  98. x = Conv2D(filters,
  99. kernel_size=kernel_size,
  100. strides=1,
  101. activation=None,
  102. padding='same',
  103. kernel_initializer='glorot_uniform',
  104. kernel_regularizer=regularizers.l2(l=0.0001),
  105. name=conv_name_base + '_2a')(input_tensor)
  106. x = BatchNormalization(name=conv_name_base + '_2a_bn')(x)
  107. x = self.clipped_relu(x)
  108.  
  109. x = Conv2D(filters,
  110. kernel_size=kernel_size,
  111. strides=1,
  112. activation=None,
  113. padding='same',
  114. kernel_initializer='glorot_uniform',
  115. kernel_regularizer=regularizers.l2(l=0.0001),
  116. name=conv_name_base + '_2b')(x)
  117. x = BatchNormalization(name=conv_name_base + '_2b_bn')(x)
  118.  
  119. x = self.clipped_relu(x)
  120.  
  121. x = layers.add([x, input_tensor])
  122. x = self.clipped_relu(x)
  123. return x
  124.  
  125. def conv_and_res_block(self, inp, filters, stage):
  126. conv_name = 'conv{}-s'.format(filters)
  127. # TODO: why kernel_regularizer?
  128. o = Conv2D(filters,
  129. kernel_size=5,
  130. strides=2,
  131. activation=None,
  132. padding='same',
  133. kernel_initializer='glorot_uniform',
  134. kernel_regularizer=regularizers.l2(l=0.0001), name=conv_name)(inp)
  135. o = BatchNormalization(name=conv_name + '_bn')(o)
  136. o = self.clipped_relu(o)
  137. for i in range(3):
  138. o = self.identity_block(o, kernel_size=3, filters=filters, stage=stage, block=i)
  139. return o
  140.  
  141. def cnn_component(self, inp):
  142. x = self.conv_and_res_block(inp, 64, stage=1)
  143. x = self.conv_and_res_block(x, 128, stage=2)
  144. x = self.conv_and_res_block(x, 256, stage=3)
  145. x = self.conv_and_res_block(x, 512, stage=4)
  146. return x
  147.  
  148. def set_weights(self, w):
  149. for layer, layer_w in zip(self.m.layers, w):
  150. layer.set_weights(layer_w)
  151. logger.info(f'Setting weights for [{layer.name}]...')
  152.  
  153.  
  154. def main():
  155. # Looks correct to me.
  156. # I have 37K but paper reports 41K. which is not too far.
  157. os.environ['PYTHONHASHSEED']=str(7381)
  158. tensorflow.random.set_seed(7381)
  159. random.seed(7381)
  160. np.random.seed(7381)
  161.  
  162. session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)
  163. sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
  164. K.set_session(sess)
  165.  
  166. dsm = DeepSpeakerModel()
  167. dsm.m.summary()
  168.  
  169.  
  170. # I suspect num frames to be 32.
  171. # Then fbank=64, then total would be 32*64 = 2048.
  172. # plot_model(dsm.m, to_file='model.png', dpi=300, show_shapes=True, expand_nested=True)
  173.  
  174.  
  175. def _train():
  176. # x = np.random.uniform(size=(6, 32, 64, 4)) # 6 is multiple of 3.
  177. # y_softmax = np.random.uniform(size=(6, 100))
  178. # dsm = DeepSpeakerModel(batch_input_shape=(None, 32, 64, 4), include_softmax=True, num_speakers_softmax=100)
  179. # dsm.m.compile(optimizer=Adam(lr=0.01), loss='categorical_crossentropy')
  180. # print(dsm.m.predict(x).shape)
  181. # print(dsm.m.evaluate(x, y_softmax))
  182. # w = dsm.get_weights()
  183. dsm = DeepSpeakerModel(batch_input_shape=(None, 32, 64, 4), include_softmax=False)
  184. # dsm.m.set_weights(w)
  185. dsm.m.compile(optimizer=Adam(lr=0.01), loss=deep_speaker_loss)
  186.  
  187. # it works!!!!!!!!!!!!!!!!!!!!
  188. # unit_batch_size = 20
  189. # anchor = np.ones(shape=(unit_batch_size, 32, 64, 4))
  190. # positive = np.array(anchor)
  191. # negative = np.ones(shape=(unit_batch_size, 32, 64, 4)) * (-1)
  192. # batch = np.vstack((anchor, positive, negative))
  193. # x = batch
  194. # y = np.zeros(shape=(len(batch), 512)) # not important.
  195. # print('Starting to fit...')
  196. # while True:
  197. # print(dsm.m.train_on_batch(x, y))
  198.  
  199. # should not work... and it does not work!
  200. unit_batch_size = 20
  201. negative = np.ones(shape=(unit_batch_size, 32, 64, 4)) * (-1)
  202. batch = np.vstack((negative, negative, negative))
  203. x = batch
  204. y = np.zeros(shape=(len(batch), 512)) # not important.
  205. print('Starting to fit...')
  206. while True:
  207. print(dsm.m.train_on_batch(x, y))
  208.  
  209.  
  210. def _test_checkpoint_compatibility():
  211. dsm = DeepSpeakerModel(batch_input_shape=(None, 32, 64, 4), include_softmax=True, num_speakers_softmax=10)
  212. dsm.m.save_weights('test.h5')
  213. dsm = DeepSpeakerModel(batch_input_shape=(None, 32, 64, 4), include_softmax=False)
  214. dsm.m.load_weights('test.h5', by_name=True)
  215. os.remove('test.h5')
  216.  
  217.  
  218. if __name__ == '__main__':
  219. _test_checkpoint_compatibility()
  220.  
Runtime error #stdin #stdout #stderr 1.56s 203460KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "./prog.py", line 18, in <module>
ModuleNotFoundError: No module named 'constants'