models.py 31 KB

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