model.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. '''
  2. Created on 2019年2月25日
  3. @author: User
  4. '''
  5. from keras import models
  6. from keras import layers
  7. from keras import optimizers, losses, metrics
  8. from keras.callbacks import ModelCheckpoint
  9. from module.Utils import *
  10. import keras.backend as K
  11. import tensorflow as tf
  12. import six
  13. import math
  14. def gelu(x):
  15. """Gaussian Error Linear Unit.
  16. This is a smoother version of the RELU.
  17. Original paper: https://arxiv.org/abs/1606.08415
  18. Args:
  19. x: float Tensor to perform activation.
  20. Returns:
  21. `x` with the GELU activation applied.
  22. """
  23. cdf = 0.5 * (1.0 + tf.tanh(
  24. (np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))))
  25. return x * cdf
  26. def shape_list(x):
  27. """Return list of dims, statically where possible."""
  28. x = tf.convert_to_tensor(x)
  29. # If unknown rank, return dynamic shape
  30. if x.get_shape().dims is None:
  31. return tf.shape(x)
  32. static = x.get_shape().as_list()
  33. shape = tf.shape(x)
  34. ret = []
  35. for i in range(len(static)):
  36. dim = static[i]
  37. if dim is None:
  38. dim = shape[i]
  39. ret.append(dim)
  40. return ret
  41. def get_timing_signal_1d(length,
  42. channels,
  43. min_timescale=1.0,
  44. max_timescale=1.0e4,
  45. start_index=0):
  46. """Gets a bunch of sinusoids of different frequencies.
  47. Each channel of the input Tensor is incremented by a sinusoid of a different
  48. frequency and phase.
  49. This allows attention to learn to use absolute and relative positions.
  50. Timing signals should be added to some precursors of both the query and the
  51. memory inputs to attention.
  52. The use of relative position is possible because sin(x+y) and cos(x+y) can be
  53. expressed in terms of y, sin(x) and cos(x).
  54. In particular, we use a geometric sequence of timescales starting with
  55. min_timescale and ending with max_timescale. The number of different
  56. timescales is equal to channels / 2. For each timescale, we
  57. generate the two sinusoidal signals sin(timestep/timescale) and
  58. cos(timestep/timescale). All of these sinusoids are concatenated in
  59. the channels dimension.
  60. Args:
  61. length: scalar, length of timing signal sequence.
  62. channels: scalar, size of timing embeddings to create. The number of
  63. different timescales is equal to channels / 2.
  64. min_timescale: a float
  65. max_timescale: a float
  66. start_index: index of first position
  67. Returns:
  68. a Tensor of timing signals [1, length, channels]
  69. """
  70. position = tf.to_float(tf.range(length) + start_index)
  71. num_timescales = channels // 2
  72. log_timescale_increment = (
  73. math.log(float(max_timescale) / float(min_timescale)) /
  74. (tf.to_float(num_timescales) - 1))
  75. inv_timescales = min_timescale * tf.exp(
  76. tf.to_float(tf.range(num_timescales)) * -log_timescale_increment)
  77. scaled_time = tf.expand_dims(position, 1) * tf.expand_dims(inv_timescales, 0)
  78. signal = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=1)
  79. signal = tf.pad(signal, [[0, 0], [0, tf.mod(channels, 2)]])
  80. signal = tf.reshape(signal, [1, length, channels])
  81. return signal
  82. def add_timing_signal_1d(x,
  83. min_timescale=1.0,
  84. max_timescale=1.0e4,
  85. start_index=0):
  86. """Adds a bunch of sinusoids of different frequencies to a Tensor.
  87. Each channel of the input Tensor is incremented by a sinusoid of a different
  88. frequency and phase.
  89. This allows attention to learn to use absolute and relative positions.
  90. Timing signals should be added to some precursors of both the query and the
  91. memory inputs to attention.
  92. The use of relative position is possible because sin(x+y) and cos(x+y) can be
  93. experessed in terms of y, sin(x) and cos(x).
  94. In particular, we use a geometric sequence of timescales starting with
  95. min_timescale and ending with max_timescale. The number of different
  96. timescales is equal to channels / 2. For each timescale, we
  97. generate the two sinusoidal signals sin(timestep/timescale) and
  98. cos(timestep/timescale). All of these sinusoids are concatenated in
  99. the channels dimension.
  100. Args:
  101. x: a Tensor with shape [batch, length, channels]
  102. min_timescale: a float
  103. max_timescale: a float
  104. start_index: index of first position
  105. Returns:
  106. a Tensor the same shape as x.
  107. """
  108. length = shape_list(x)[1]
  109. channels = shape_list(x)[2]
  110. signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale,
  111. start_index)
  112. return x + signal
  113. def get_activation(activation_string):
  114. """Maps a string to a Python function, e.g., "relu" => `tf.nn.relu`.
  115. Args:
  116. activation_string: String name of the activation function.
  117. Returns:
  118. A Python function corresponding to the activation function. If
  119. `activation_string` is None, empty, or "linear", this will return None.
  120. If `activation_string` is not a string, it will return `activation_string`.
  121. Raises:
  122. ValueError: The `activation_string` does not correspond to a known
  123. activation.
  124. """
  125. # We assume that anything that"s not a string is already an activation
  126. # function, so we just return it.
  127. if not isinstance(activation_string, six.string_types):
  128. return activation_string
  129. if not activation_string:
  130. return None
  131. act = activation_string.lower()
  132. if act == "linear":
  133. return None
  134. elif act == "relu":
  135. return tf.nn.relu
  136. elif act == "gelu":
  137. return gelu
  138. elif act == "tanh":
  139. return tf.tanh
  140. else:
  141. raise ValueError("Unsupported activation: %s" % act)
  142. def dropout(input_tensor, dropout_prob):
  143. """Perform dropout.
  144. Args:
  145. input_tensor: float Tensor.
  146. dropout_prob: Python float. The probability of dropping out a value (NOT of
  147. *keeping* a dimension as in `tf.nn.dropout`).
  148. Returns:
  149. A version of `input_tensor` with dropout applied.
  150. """
  151. if dropout_prob is None or dropout_prob == 0.0:
  152. return input_tensor
  153. output = tf.nn.dropout(input_tensor, 1.0 - dropout_prob)
  154. return output
  155. def layer_norm(input_tensor, name=None):
  156. """Run layer normalization on the last dimension of the tensor."""
  157. return tf.contrib.layers.layer_norm(
  158. inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
  159. def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
  160. """Runs layer normalization followed by dropout."""
  161. output_tensor = layer_norm(input_tensor, name)
  162. output_tensor = dropout(output_tensor, dropout_prob)
  163. return output_tensor
  164. def create_initializer(initializer_range=0.02):
  165. """Creates a `truncated_normal_initializer` with the given range."""
  166. return tf.truncated_normal_initializer(stddev=initializer_range)
  167. def reshape_to_matrix(input_tensor):
  168. """Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix)."""
  169. ndims = input_tensor.shape.ndims
  170. if ndims < 2:
  171. raise ValueError("Input tensor must have at least rank 2. Shape = %s" %
  172. (input_tensor.shape))
  173. if ndims == 2:
  174. return input_tensor
  175. width = input_tensor.shape[-1]
  176. output_tensor = tf.reshape(input_tensor, [-1, width])
  177. return output_tensor
  178. def reshape_from_matrix(output_tensor, orig_shape_list):
  179. """Reshapes a rank 2 tensor back to its original rank >= 2 tensor."""
  180. if len(orig_shape_list) == 2:
  181. return output_tensor
  182. output_shape = shape_list(output_tensor)
  183. orig_dims = orig_shape_list[0:-1]
  184. width = output_shape[-1]
  185. return tf.reshape(output_tensor, orig_dims + [width])
  186. def assert_rank(tensor, expected_rank, name=None):
  187. """Raises an exception if the tensor rank is not of the expected rank.
  188. Args:
  189. tensor: A tf.Tensor to check the rank of.
  190. expected_rank: Python integer or list of integers, expected rank.
  191. name: Optional name of the tensor for the error message.
  192. Raises:
  193. ValueError: If the expected shape doesn't match the actual shape.
  194. """
  195. if name is None:
  196. name = tensor.name
  197. expected_rank_dict = {}
  198. if isinstance(expected_rank, six.integer_types):
  199. expected_rank_dict[expected_rank] = True
  200. else:
  201. for x in expected_rank:
  202. expected_rank_dict[x] = True
  203. actual_rank = tensor.shape.ndims
  204. if actual_rank not in expected_rank_dict:
  205. scope_name = tf.get_variable_scope().name
  206. raise ValueError(
  207. "For the tensor `%s` in scope `%s`, the actual rank "
  208. "`%d` (shape = %s) is not equal to the expected rank `%s`" %
  209. (name, scope_name, actual_rank, str(tensor.shape), str(expected_rank)))
  210. def get_shape_list(tensor, expected_rank=None, name=None):
  211. """Returns a list of the shape of tensor, preferring static dimensions.
  212. Args:
  213. tensor: A tf.Tensor object to find the shape of.
  214. expected_rank: (optional) int. The expected rank of `tensor`. If this is
  215. specified and the `tensor` has a different rank, and exception will be
  216. thrown.
  217. name: Optional name of the tensor for the error message.
  218. Returns:
  219. A list of dimensions of the shape of tensor. All static dimensions will
  220. be returned as python integers, and dynamic dimensions will be returned
  221. as tf.Tensor scalars.
  222. """
  223. if name is None:
  224. name = tensor.name
  225. if expected_rank is not None:
  226. assert_rank(tensor, expected_rank, name)
  227. shape = tensor.shape.as_list()
  228. non_static_indexes = []
  229. for (index, dim) in enumerate(shape):
  230. if dim is None:
  231. non_static_indexes.append(index)
  232. if not non_static_indexes:
  233. return shape
  234. dyn_shape = tf.shape(tensor)
  235. for index in non_static_indexes:
  236. shape[index] = dyn_shape[index]
  237. return shape
  238. def attention_layer(from_tensor,
  239. to_tensor,
  240. attention_mask=None,
  241. num_attention_heads=1,
  242. size_per_head=10,
  243. query_act=None,
  244. key_act=None,
  245. value_act=None,
  246. attention_probs_dropout_prob=0.0,
  247. initializer_range=0.02,
  248. do_return_2d_tensor=False,
  249. batch_size=None,
  250. from_seq_length=None,
  251. to_seq_length=None):
  252. """Performs multi-headed attention from `from_tensor` to `to_tensor`.
  253. This is an implementation of multi-headed attention based on "Attention
  254. is all you Need". If `from_tensor` and `to_tensor` are the same, then
  255. this is self-attention. Each timestep in `from_tensor` attends to the
  256. corresponding sequence in `to_tensor`, and returns a fixed-with vector.
  257. This function first projects `from_tensor` into a "query" tensor and
  258. `to_tensor` into "key" and "value" tensors. These are (effectively) a list
  259. of tensors of length `num_attention_heads`, where each tensor is of shape
  260. [batch_size, seq_length, size_per_head].
  261. Then, the query and key tensors are dot-producted and scaled. These are
  262. softmaxed to obtain attention probabilities. The value tensors are then
  263. interpolated by these probabilities, then concatenated back to a single
  264. tensor and returned.
  265. In practice, the multi-headed attention are done with transposes and
  266. reshapes rather than actual separate tensors.
  267. Args:
  268. from_tensor: float Tensor of shape [batch_size, from_seq_length,
  269. from_width].
  270. to_tensor: float Tensor of shape [batch_size, to_seq_length, to_width].
  271. attention_mask: (optional) int32 Tensor of shape [batch_size,
  272. from_seq_length, to_seq_length]. The values should be 1 or 0. The
  273. attention scores will effectively be set to -infinity for any positions in
  274. the mask that are 0, and will be unchanged for positions that are 1.
  275. num_attention_heads: int. Number of attention heads.
  276. size_per_head: int. Size of each attention head.
  277. query_act: (optional) Activation function for the query transform.
  278. key_act: (optional) Activation function for the key transform.
  279. value_act: (optional) Activation function for the value transform.
  280. attention_probs_dropout_prob: (optional) float. Dropout probability of the
  281. attention probabilities.
  282. initializer_range: float. Range of the weight initializer.
  283. do_return_2d_tensor: bool. If True, the output will be of shape [batch_size
  284. * from_seq_length, num_attention_heads * size_per_head]. If False, the
  285. output will be of shape [batch_size, from_seq_length, num_attention_heads
  286. * size_per_head].
  287. batch_size: (Optional) int. If the input is 2D, this might be the batch size
  288. of the 3D version of the `from_tensor` and `to_tensor`.
  289. from_seq_length: (Optional) If the input is 2D, this might be the seq length
  290. of the 3D version of the `from_tensor`.
  291. to_seq_length: (Optional) If the input is 2D, this might be the seq length
  292. of the 3D version of the `to_tensor`.
  293. Returns:
  294. float Tensor of shape [batch_size, from_seq_length,
  295. num_attention_heads * size_per_head]. (If `do_return_2d_tensor` is
  296. true, this will be of shape [batch_size * from_seq_length,
  297. num_attention_heads * size_per_head]).
  298. Raises:
  299. ValueError: Any of the arguments or tensor shapes are invalid.
  300. """
  301. def transpose_for_scores(input_tensor, batch_size, num_attention_heads,
  302. seq_length, width):
  303. output_tensor = tf.reshape(
  304. input_tensor, [batch_size, seq_length, num_attention_heads, width])
  305. output_tensor = tf.transpose(output_tensor, [0, 2, 1, 3])
  306. return output_tensor
  307. from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])
  308. to_shape = get_shape_list(to_tensor, expected_rank=[2, 3])
  309. if len(from_shape) != len(to_shape):
  310. raise ValueError(
  311. "The rank of `from_tensor` must match the rank of `to_tensor`.")
  312. if len(from_shape) == 3:
  313. batch_size = from_shape[0]
  314. from_seq_length = from_shape[1]
  315. to_seq_length = to_shape[1]
  316. elif len(from_shape) == 2:
  317. if (batch_size is None or from_seq_length is None or to_seq_length is None):
  318. raise ValueError(
  319. "When passing in rank 2 tensors to attention_layer, the values "
  320. "for `batch_size`, `from_seq_length`, and `to_seq_length` "
  321. "must all be specified.")
  322. # Scalar dimensions referenced here:
  323. # B = batch size (number of sequences)
  324. # F = `from_tensor` sequence length
  325. # T = `to_tensor` sequence length
  326. # N = `num_attention_heads`
  327. # H = `size_per_head`
  328. from_tensor_2d = reshape_to_matrix(from_tensor)
  329. to_tensor_2d = reshape_to_matrix(to_tensor)
  330. # `query_layer` = [B*F, N*H]
  331. '''
  332. query_matrix = tf.get_variable(name="query",shape=(shape_list(from_tensor_2d)[-1],num_attention_heads * size_per_head),initializer=create_initializer(initializer_range))
  333. query_layer = tf.matmul(from_tensor_2d,query_matrix)
  334. if query_act is not None:
  335. query_layer = query_act(query_layer)
  336. key_matrix = tf.get_variable(name="key",shape=(shape_list(from_tensor_2d)[-1],num_attention_heads * size_per_head),initializer=create_initializer(initializer_range))
  337. key_layer = tf.matmul(from_tensor_2d,key_matrix)
  338. if key_act is not None:
  339. key_layer =key_act(key_layer)
  340. value_matrix = tf.get_variable(name="value",shape=(shape_list(from_tensor_2d)[-1],num_attention_heads * size_per_head),initializer=create_initializer(initializer_range))
  341. value_layer = tf.matmul(from_tensor_2d,value_matrix)
  342. if value_act is not None:
  343. value_layer = value_act(value_layer)
  344. '''
  345. query_layer = tf.layers.dense(
  346. from_tensor_2d,
  347. num_attention_heads * size_per_head,
  348. activation=query_act,
  349. name="query",
  350. kernel_initializer=create_initializer(initializer_range))
  351. # `key_layer` = [B*T, N*H]
  352. key_layer = tf.layers.dense(
  353. to_tensor_2d,
  354. num_attention_heads * size_per_head,
  355. activation=key_act,
  356. name="key",
  357. kernel_initializer=create_initializer(initializer_range))
  358. # `value_layer` = [B*T, N*H]
  359. value_layer = tf.layers.dense(
  360. to_tensor_2d,
  361. num_attention_heads * size_per_head,
  362. activation=value_act,
  363. name="value",
  364. kernel_initializer=create_initializer(initializer_range))
  365. # `query_layer` = [B, N, F, H]
  366. query_layer = transpose_for_scores(query_layer, batch_size,
  367. num_attention_heads, from_seq_length,
  368. size_per_head)
  369. # `key_layer` = [B, N, T, H]
  370. key_layer = transpose_for_scores(key_layer, batch_size, num_attention_heads,
  371. to_seq_length, size_per_head)
  372. # Take the dot product between "query" and "key" to get the raw
  373. # attention scores.
  374. # `attention_scores` = [B, N, F, T]
  375. attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
  376. attention_scores = tf.multiply(attention_scores,
  377. 1.0 / math.sqrt(float(size_per_head)))
  378. print(attention_scores)
  379. if attention_mask is not None:
  380. # `attention_mask` = [B, 1, F, T]
  381. attention_mask = tf.expand_dims(attention_mask, axis=[1])
  382. # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
  383. # masked positions, this operation will create a tensor which is 0.0 for
  384. # positions we want to attend and -10000.0 for masked positions.
  385. adder = (1.0 - tf.cast(attention_mask, tf.float32)) * -10000.0
  386. # Since we are adding it to the raw scores before the softmax, this is
  387. # effectively the same as removing these entirely.
  388. attention_scores += adder
  389. # Normalize the attention scores to probabilities.
  390. # `attention_probs` = [B, N, F, T]
  391. # B = batch size (number of sequences)
  392. # F = `from_tensor` sequence length
  393. # T = `to_tensor` sequence length
  394. # N = `num_attention_heads`
  395. # H = `size_per_head`
  396. # attention_scores = tf.reshape(attention_scores,[batch_size,num_attention_heads,from_seq_length,to_seq_length])
  397. attention_probs = tf.nn.softmax(attention_scores)
  398. # This is actually dropping out entire tokens to attend to, which might
  399. # seem a bit unusual, but is taken from the original Transformer paper.
  400. attention_probs = dropout(attention_probs, attention_probs_dropout_prob)
  401. # `value_layer` = [B, T, N, H]
  402. value_layer = tf.reshape(
  403. value_layer,
  404. [batch_size, to_seq_length, num_attention_heads, size_per_head])
  405. # `value_layer` = [B, N, T, H]
  406. value_layer = tf.transpose(value_layer, [0, 2, 1, 3])
  407. # `context_layer` = [B, N, F, H]
  408. context_layer = tf.matmul(attention_probs, value_layer)
  409. # `context_layer` = [B, F, N, H]
  410. context_layer = tf.transpose(context_layer, [0, 2, 1, 3])
  411. if do_return_2d_tensor:
  412. # `context_layer` = [B*F, N*H]
  413. context_layer = tf.reshape(
  414. context_layer,
  415. [batch_size * from_seq_length, num_attention_heads * size_per_head])
  416. else:
  417. # `context_layer` = [B, F, N*H]
  418. context_layer = tf.reshape(
  419. context_layer,
  420. [batch_size, from_seq_length, num_attention_heads * size_per_head])
  421. return context_layer
  422. def transformer_model(input_tensor,
  423. attention_mask=None,
  424. hidden_size=128,
  425. num_hidden_layers=4,
  426. num_attention_heads=1,
  427. intermediate_size=256,
  428. intermediate_act_fn=gelu,
  429. hidden_dropout_prob=0.1,
  430. attention_probs_dropout_prob=0.1,
  431. initializer_range=0.02,
  432. do_return_all_layers=False):
  433. # input_tensor = add_timing_signal_1d(input_tensor)
  434. if hidden_size % num_attention_heads != 0:
  435. raise ValueError(
  436. "The hidden size (%d) is not a multiple of the number of attention "
  437. "heads (%d)" % (hidden_size, num_attention_heads))
  438. attention_head_size = int(hidden_size / num_attention_heads)
  439. input_shape = get_shape_list(input_tensor, expected_rank=3)
  440. batch_size = input_shape[0]
  441. seq_length = input_shape[1]
  442. input_width = input_shape[2]
  443. # The Transformer performs sum residuals on all layers so the input needs
  444. # to be the same as the hidden size.
  445. if input_width != hidden_size:
  446. raise ValueError("The width of the input tensor (%d) != hidden size (%d)" %
  447. (input_width, hidden_size))
  448. # We keep the representation as a 2D tensor to avoid re-shaping it back and
  449. # forth from a 3D tensor to a 2D tensor. Re-shapes are normally free on
  450. # the GPU/CPU but may not be free on the TPU, so we want to minimize them to
  451. # help the optimizer.
  452. prev_output = reshape_to_matrix(input_tensor)
  453. all_layer_outputs = []
  454. with tf.variable_scope("encoder", reuse=tf.AUTO_REUSE):
  455. for layer_idx in range(num_hidden_layers):
  456. with tf.variable_scope("layer_%d" % layer_idx, reuse=tf.AUTO_REUSE):
  457. layer_input = prev_output
  458. with tf.variable_scope("attention", reuse=tf.AUTO_REUSE):
  459. attention_heads = []
  460. with tf.variable_scope("self", reuse=tf.AUTO_REUSE):
  461. attention_head = attention_layer(
  462. from_tensor=layer_input,
  463. to_tensor=layer_input,
  464. attention_mask=attention_mask,
  465. num_attention_heads=num_attention_heads,
  466. size_per_head=attention_head_size,
  467. attention_probs_dropout_prob=attention_probs_dropout_prob,
  468. initializer_range=initializer_range,
  469. do_return_2d_tensor=True,
  470. batch_size=batch_size,
  471. from_seq_length=seq_length,
  472. to_seq_length=seq_length)
  473. attention_heads.append(attention_head)
  474. attention_output = None
  475. if len(attention_heads) == 1:
  476. attention_output = attention_heads[0]
  477. else:
  478. # In the case where we have other sequences, we just concatenate
  479. # them to the self-attention head before the projection.
  480. attention_output = tf.concat(attention_heads, axis=-1)
  481. # Run a linear projection of `hidden_size` then add a residual
  482. # with `layer_input`.
  483. with tf.variable_scope("output", reuse=tf.AUTO_REUSE):
  484. attention_output = tf.layers.dense(
  485. attention_output,
  486. hidden_size,
  487. kernel_initializer=create_initializer(initializer_range))
  488. attention_output = dropout(attention_output, hidden_dropout_prob)
  489. attention_output = layer_norm(attention_output + layer_input)
  490. # The activation is only applied to the "intermediate" hidden layer.
  491. with tf.variable_scope("intermediate", reuse=tf.AUTO_REUSE):
  492. intermediate_output = tf.layers.dense(
  493. attention_output,
  494. intermediate_size,
  495. activation=intermediate_act_fn,
  496. kernel_initializer=create_initializer(initializer_range))
  497. # Down-project back to `hidden_size` then add the residual.
  498. with tf.variable_scope("output", reuse=tf.AUTO_REUSE):
  499. layer_output = tf.layers.dense(
  500. intermediate_output,
  501. hidden_size,
  502. kernel_initializer=create_initializer(initializer_range))
  503. layer_output = dropout(layer_output, hidden_dropout_prob)
  504. layer_output = layer_norm(layer_output + attention_output)
  505. prev_output = layer_output
  506. all_layer_outputs.append(layer_output)
  507. if do_return_all_layers:
  508. final_outputs = []
  509. for layer_output in all_layer_outputs:
  510. final_output = reshape_from_matrix(layer_output, input_shape)
  511. final_outputs.append(final_output)
  512. return final_outputs
  513. else:
  514. final_output = reshape_from_matrix(prev_output, input_shape)
  515. return final_output
  516. class Attention(layers.Layer):
  517. def __init__(self, **kwargs):
  518. super(Attention, self).__init__(**kwargs)
  519. def build(self, input_shape):
  520. # W: (EMBED_SIZE, 1)
  521. # b: (MAX_TIMESTEPS, 1)
  522. # u: (MAX_TIMESTEPS, MAX_TIMESTEPS)
  523. print(input_shape)
  524. self.W = self.add_weight(name="W_{:s}".format(self.name),
  525. shape=(input_shape[-1], 1),
  526. initializer="uniform")
  527. self.b = self.add_weight(name="b_{:s}".format(self.name),
  528. shape=(input_shape[1], 1),
  529. initializer="uniform")
  530. super(Attention, self).build(input_shape)
  531. def call(self, x, mask=None):
  532. # input: (BATCH_SIZE, MAX_TIMESTEPS, EMBED_SIZE)
  533. # et: (BATCH_SIZE, MAX_TIMESTEPS)
  534. et = K.squeeze(K.tanh(K.dot(x, self.W) + self.b), axis=-1)
  535. # at: (BATCH_SIZE, MAX_TIMESTEPS)
  536. print("et", np.shape(et))
  537. # at = K.dot(et, self.u)
  538. # if mask is not None:
  539. # at *= K.cast(mask, K.floatx())
  540. # ot: (BATCH_SIZE, MAX_TIMESTEPS, EMBED_SIZE)
  541. et /= K.cast(K.sum(et, axis=1, keepdims=True) + K.epsilon(), K.floatx())
  542. print(np.shape(et))
  543. # atx = K.expand_dims(at, axis=-1)
  544. # atx1 = K.argmax(at,axis=-1)
  545. # et1 = K.one_hot(atx1,100)
  546. # at1 = (at * (et1 - 1)) * -1
  547. # atx2 = K.argmax(at1,axis=-1)
  548. # et2 = K.one_hot(atx2,100)
  549. # at2 = (at1 * (et2 - 1)) * -1
  550. # atx3 = K.argmax(at2,axis=-1)
  551. # et3 = K.one_hot(atx3,100)
  552. # at3 = (at2 * (et3 - 1)) * -1
  553. # atx4 = K.argmax(at3,axis=-1)
  554. # et4 = K.one_hot(atx4,100)
  555. # at4 = (at3 * (et4 - 1)) * -1
  556. # atx5 = K.argmax(at4,axis=-1)
  557. # et5 = K.one_hot(atx5,100)
  558. # at5 = (at4 * (et5 - 1)) * -1
  559. # atx6 = K.argmax(at5,axis=-1)
  560. # et6 = K.one_hot(atx6,100)
  561. # et = et1 + et2 + et3 + et4 + et5 + et6
  562. # at = at * et
  563. # for i in range(at.shape[0]):
  564. # at[i][atx1[i]] = 0
  565. # atx2 = K.argmax(at,axis=-1)
  566. # for i in range(at.shape[0]):
  567. # at[i][atx2[i]] = 0
  568. # atx3 = K.argmax(at,axis=-1)
  569. # ad = K.zeros([at.shape[0],at.shape[1]])
  570. # at = at * ad
  571. # atx = K.expand_dims(at, axis=-1)
  572. return et
  573. def compute_mask(self, input, input_mask=None):
  574. # do not pass the mask to the next layers
  575. return None
  576. def compute_output_shape(self, input_shape):
  577. # output shape: (BATCH_SIZE, EMBED_SIZE)
  578. return (input_shape[0], input_shape[1])
  579. def get_config(self):
  580. return super(Attention, self).get_config()
  581. def getBiRNNModel(input_shape=[None, 36], out_len=2, TRANSFORMER=False):
  582. '''
  583. @summary:获取模型
  584. '''
  585. input = layers.Input(shape=input_shape, dtype="float32")
  586. # mask = layers.Masking(mask_value=0)(input)
  587. mask = input
  588. '''
  589. whole_lstm = layers.Bidirectional(layers.LSTM(12,return_sequences=False))(mask)
  590. repeat = layers.RepeatVector(input_shape[0])(whole_lstm)
  591. #lstm_0 = layers.Bidirectional(layers.LSTM(12,return_sequences=True))(mask)
  592. #lstm_1 = layers.Bidirectional(layers.LSTM(48,return_sequences=True))(lstm_0)
  593. matrix = layers.Dense(24,activation="relu")(mask)
  594. concat = layers.merge([repeat,matrix],mode="concat")
  595. matrix = layers.Dense(48,activation="relu")(concat)
  596. matrix = layers.Dense(24,activation="relu")(matrix)
  597. #output = layers.Dense(out_len,activation="softmax")(matrix)
  598. output = Attention()(concat)
  599. print("out",np.shape(output))
  600. #layers.RepeatVector(np.shape(matrix)[-2])(whole_lstm)
  601. '''
  602. ''''''
  603. if TRANSFORMER:
  604. set_v_before = set([v.name for v in tf.trainable_variables()])
  605. transformer_layer = layers.Lambda(
  606. lambda x: transformer_model(x, hidden_size=get_shape_list(mask)[-1], do_return_all_layers=False),
  607. trainable=True)
  608. globalLocalFeature = transformer_layer(mask)
  609. transformer_weights = []
  610. for v in tf.trainable_variables():
  611. if v.name not in set_v_before:
  612. transformer_weights.append(v)
  613. transformer_layer._trainable_weights = transformer_weights
  614. else:
  615. lstm_0 = layers.Bidirectional(layers.LSTM(32, return_sequences=True))(mask)
  616. # matrix = layers.Dense(24,activation="relu")(lstm_0)
  617. lstm_1 = layers.Bidirectional(layers.LSTM(12, return_sequences=True))(lstm_0)
  618. globalLocalFeature = lstm_1
  619. # output = layers.Lambda(lambda x:)
  620. output = layers.Dense(2, activation="softmax")(globalLocalFeature)
  621. # output = layers.Lambda(lambda x:K.clip(K.softmax(K.squeeze(x,2)),1e-12,1))(output)
  622. model = models.Model(inputs=[input], outputs=output)
  623. model.compile(optimizer=optimizers.Adam(lr=0.001), loss=my_loss, metrics=[precision, recall, f1_score])
  624. model.summary()
  625. return model
  626. if __name__ == "__main__":
  627. getBiRNNModel(TRANSFORMER=False)