models.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. '''
  2. Created on 2019年4月22日
  3. @author: User
  4. '''
  5. from keras import models,layers,losses,optimizers
  6. from keras.callbacks import ModelCheckpoint
  7. import numpy as np
  8. from BiddingKG.dl.common.Utils import *
  9. import keras.backend as K
  10. import tensorflow as tf
  11. import math
  12. import six
  13. layers.Dense
  14. def getTextCNNModel(input_shape,vocab,embedding_weights,classes):
  15. def resize(x):
  16. _shape = shape_list(x)
  17. print("#$",_shape)
  18. x1 = tf.reshape(x,[_shape[0],2,_shape[1]//2,_shape[2]]) # type: object
  19. print("--")
  20. x2 = tf.transpose(x1,[1,0,2,3])
  21. x_l,x_r = tf.split(x2,[1,1],axis=0)
  22. return [tf.squeeze(x_l,axis=0),tf.squeeze(x_r,axis=0)]
  23. def resize_input(x):
  24. _shape = shape_list(x)
  25. x1 = tf.reshape(x,[_shape[0],3,_shape[1]//3]) # type: object
  26. x2 = tf.transpose(x1,[1,0,2])
  27. x_l,x_c,x_r = tf.split(x2,[1,1,1],axis=0)
  28. return [tf.squeeze(x_l,axis=0),tf.squeeze(x_c,axis=0),tf.squeeze(x_r,axis=0)]
  29. # assert len(input_shape)==3
  30. list_input = []
  31. for i in range(input_shape[0]):
  32. list_input.append(layers.Input(shape=(input_shape[1],),dtype=tf.int32,name="input%d"%(i)))
  33. print("list_input",list_input)
  34. list_embedding = []
  35. # if len(list_input)==1:
  36. # list_resizeinput = layers.Lambda(resize_input)(list_input[0])
  37. # else:
  38. concat_input = layers.Lambda(lambda x:tf.concat(x,axis=-1))(list_input)
  39. embedding_input = [concat_input]
  40. # embedding_input = list_input
  41. embedding = layers.Embedding(len(vocab),input_shape[2],weights=[embedding_weights] if embedding_weights is not None else None,trainable=True,name="char_embeding")
  42. for i in range(len(embedding_input)):
  43. print(i)
  44. list_embedding.append(embedding(embedding_input[i]))
  45. print(list_embedding)
  46. #
  47. set_variables = set()
  48. for v in tf.trainable_variables():
  49. set_variables.add(v.name)
  50. list_bert = []
  51. for i in range(len(list_embedding)):
  52. for v in tf.trainable_variables():
  53. set_variables.add(v.name)
  54. bert_layer = layers.Lambda(lambda x:transformer_model(input_tensor=x,name="bert%d"%(i)),trainable=True,name="bert%d"%(i))
  55. list_bert.append(bert_layer(list_embedding[i]))
  56. #set bert_weights to trainable
  57. bert_weights = []
  58. for v in tf.trainable_variables():
  59. if v.name not in set_variables:
  60. print("++++",v.name)
  61. bert_weights.append(v)
  62. bert_layer._trainable_weights = bert_weights
  63. _resize = layers.Lambda(lambda x:resize(x))(list_bert[0])
  64. list_w2v = _resize
  65. list_conv = []
  66. list_kernel = [2,5,8]
  67. for i in range(len(list_w2v)):
  68. list_temp = []
  69. for kernel in list_kernel:
  70. list_temp.append(layers.Conv1D(10,kernel,strides=1,padding="same",activation="relu")(list_w2v[i]))
  71. list_conv.append(layers.merge(list_temp,mode="concat"))
  72. layers.Conv2D
  73. list_matrix = []
  74. for i in range(len(list_conv)):
  75. list_matrix.append(layers.Dense(12,activation="relu")(list_conv[i]))
  76. if len(list_matrix)>1:
  77. ave = layers.merge(list_matrix,mode="concat")
  78. dropout = layers.Dropout(0.3)(ave)
  79. else:
  80. dropout = layers.Dropout(0.3)(list_matrix[0])
  81. flatten = layers.Flatten()(dropout)
  82. matrix = layers.Dense(classes*10,activation="relu")(flatten)
  83. out = layers.Dense(classes,activation="softmax")(matrix)
  84. model = models.Model(list_input,out)
  85. model.compile(optimizer=optimizers.Adadelta(),loss=losses.categorical_crossentropy,metrics=[precision,recall,f1_score])
  86. model.summary()
  87. return model
  88. class Attention(layers.Layer):
  89. def __init__(self, **kwargs):
  90. super(Attention, self).__init__(**kwargs)
  91. def build(self, input_shape):
  92. # W: (EMBED_SIZE, 1)
  93. # b: (MAX_TIMESTEPS, 1)
  94. # u: (MAX_TIMESTEPS, MAX_TIMESTEPS)
  95. self.W = self.add_weight(name="W_{:s}".format(self.name),
  96. shape=(input_shape[-1], 1),
  97. initializer="normal")
  98. self.b = self.add_weight(name="b_{:s}".format(self.name),
  99. shape=(input_shape[1], 1),
  100. initializer="zeros")
  101. self.u = self.add_weight(name="u_{:s}".format(self.name),
  102. shape=(input_shape[1], input_shape[1]),
  103. initializer="normal")
  104. super(Attention, self).build(input_shape)
  105. def call(self, x, mask=None):
  106. # input: (BATCH_SIZE, MAX_TIMESTEPS, EMBED_SIZE)
  107. # et: (BATCH_SIZE, MAX_TIMESTEPS)
  108. et = K.squeeze(K.tanh(K.dot(x, self.W) + self.b), axis=-1)
  109. # at: (BATCH_SIZE, MAX_TIMESTEPS)
  110. at = K.dot(et, self.u)
  111. at = K.exp(at)
  112. if mask is not None:
  113. at *= K.cast(mask, K.floatx())
  114. # ot: (BATCH_SIZE, MAX_TIMESTEPS, EMBED_SIZE)
  115. at /= K.cast(K.sum(at, axis=1, keepdims=True) + K.epsilon(), K.floatx())
  116. atx = K.expand_dims(at, axis=-1)
  117. ot = atx * x
  118. # output: (BATCH_SIZE, EMBED_SIZE)
  119. return K.sum(ot, axis=1)
  120. def compute_mask(self, input, input_mask=None):
  121. # do not pass the mask to the next layers
  122. return None
  123. def compute_output_shape(self, input_shape):
  124. # output shape: (BATCH_SIZE, EMBED_SIZE)
  125. return (input_shape[0], input_shape[-1])
  126. def get_config(self):
  127. return super(Attention, self).get_config()
  128. def gelu(x):
  129. """Gaussian Error Linear Unit.
  130. This is a smoother version of the RELU.
  131. Original paper: https://arxiv.org/abs/1606.08415
  132. Args:
  133. x: float Tensor to perform activation.
  134. Returns:
  135. `x` with the GELU activation applied.
  136. """
  137. cdf = 0.5 * (1.0 + tf.tanh(
  138. (np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))))
  139. return x * cdf
  140. def shape_list(x):
  141. """Return list of dims, statically where possible."""
  142. x = tf.convert_to_tensor(x)
  143. # If unknown rank, return dynamic shape
  144. if x.get_shape().dims is None:
  145. return tf.shape(x)
  146. static = x.get_shape().as_list()
  147. shape = tf.shape(x)
  148. ret = []
  149. for i in range(len(static)):
  150. dim = static[i]
  151. if dim is None:
  152. dim = shape[i]
  153. ret.append(dim)
  154. return ret
  155. def get_timing_signal_1d(length,
  156. channels,
  157. min_timescale=1.0,
  158. max_timescale=1.0e4,
  159. start_index=0):
  160. """Gets a bunch of sinusoids of different frequencies.
  161. Each channel of the input Tensor is incremented by a sinusoid of a different
  162. frequency and phase.
  163. This allows attention to learn to use absolute and relative positions.
  164. Timing signals should be added to some precursors of both the query and the
  165. memory inputs to attention.
  166. The use of relative position is possible because sin(x+y) and cos(x+y) can be
  167. expressed in terms of y, sin(x) and cos(x).
  168. In particular, we use a geometric sequence of timescales starting with
  169. min_timescale and ending with max_timescale. The number of different
  170. timescales is equal to channels / 2. For each timescale, we
  171. generate the two sinusoidal signals sin(timestep/timescale) and
  172. cos(timestep/timescale). All of these sinusoids are concatenated in
  173. the channels dimension.
  174. Args:
  175. length: scalar, length of timing signal sequence.
  176. channels: scalar, size of timing embeddings to create. The number of
  177. different timescales is equal to channels / 2.
  178. min_timescale: a float
  179. max_timescale: a float
  180. start_index: index of first position
  181. Returns:
  182. a Tensor of timing signals [1, length, channels]
  183. """
  184. position = tf.to_float(tf.range(length) + start_index)
  185. num_timescales = channels // 2
  186. log_timescale_increment = (
  187. math.log(float(max_timescale) / float(min_timescale)) /
  188. (tf.to_float(num_timescales) - 1))
  189. inv_timescales = min_timescale * tf.exp(
  190. tf.to_float(tf.range(num_timescales)) * -log_timescale_increment)
  191. scaled_time = tf.expand_dims(position, 1) * tf.expand_dims(inv_timescales, 0)
  192. signal = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=1)
  193. signal = tf.pad(signal, [[0, 0], [0, tf.mod(channels, 2)]])
  194. signal = tf.reshape(signal, [1, length, channels])
  195. return signal
  196. def add_timing_signal_1d(x,
  197. min_timescale=1.0,
  198. max_timescale=1.0e4,
  199. start_index=0):
  200. """Adds a bunch of sinusoids of different frequencies to a Tensor.
  201. Each channel of the input Tensor is incremented by a sinusoid of a different
  202. frequency and phase.
  203. This allows attention to learn to use absolute and relative positions.
  204. Timing signals should be added to some precursors of both the query and the
  205. memory inputs to attention.
  206. The use of relative position is possible because sin(x+y) and cos(x+y) can be
  207. experessed in terms of y, sin(x) and cos(x).
  208. In particular, we use a geometric sequence of timescales starting with
  209. min_timescale and ending with max_timescale. The number of different
  210. timescales is equal to channels / 2. For each timescale, we
  211. generate the two sinusoidal signals sin(timestep/timescale) and
  212. cos(timestep/timescale). All of these sinusoids are concatenated in
  213. the channels dimension.
  214. Args:
  215. x: a Tensor with shape [batch, length, channels]
  216. min_timescale: a float
  217. max_timescale: a float
  218. start_index: index of first position
  219. Returns:
  220. a Tensor the same shape as x.
  221. """
  222. batchs = shape_list(x)[0]
  223. length = shape_list(x)[1]
  224. channels = shape_list(x)[2]
  225. signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale,
  226. start_index)
  227. _signal = tf.tile(signal,[batchs,1,1])
  228. _concat = tf.concat([x,_signal],axis=2)
  229. # _concat = tf.quantized_concat(2,[x,signal],input_mins=[-10,-10],input_maxes=[10,10])[0]
  230. print("##",_concat)
  231. return _concat
  232. def get_activation(activation_string):
  233. """Maps a string to a Python function, e.g., "relu" => `tf.nn.relu`.
  234. Args:
  235. activation_string: String name of the activation function.
  236. Returns:
  237. A Python function corresponding to the activation function. If
  238. `activation_string` is None, empty, or "linear", this will return None.
  239. If `activation_string` is not a string, it will return `activation_string`.
  240. Raises:
  241. ValueError: The `activation_string` does not correspond to a known
  242. activation.
  243. """
  244. # We assume that anything that"s not a string is already an activation
  245. # function, so we just return it.
  246. if not isinstance(activation_string, six.string_types):
  247. return activation_string
  248. if not activation_string:
  249. return None
  250. act = activation_string.lower()
  251. if act == "linear":
  252. return None
  253. elif act == "relu":
  254. return tf.nn.relu
  255. elif act == "gelu":
  256. return gelu
  257. elif act == "tanh":
  258. return tf.tanh
  259. else:
  260. raise ValueError("Unsupported activation: %s" % act)
  261. def dropout(input_tensor, dropout_prob):
  262. """Perform dropout.
  263. Args:
  264. input_tensor: float Tensor.
  265. dropout_prob: Python float. The probability of dropping out a value (NOT of
  266. *keeping* a dimension as in `tf.nn.dropout`).
  267. Returns:
  268. A version of `input_tensor` with dropout applied.
  269. """
  270. if dropout_prob is None or dropout_prob == 0.0:
  271. return input_tensor
  272. output = tf.nn.dropout(input_tensor, 1.0 - dropout_prob)
  273. return output
  274. def layer_norm(input_tensor, name=None):
  275. """Run layer normalization on the last dimension of the tensor."""
  276. return tf.contrib.layers.layer_norm(
  277. inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
  278. def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
  279. """Runs layer normalization followed by dropout."""
  280. output_tensor = layer_norm(input_tensor, name)
  281. output_tensor = dropout(output_tensor, dropout_prob)
  282. return output_tensor
  283. def create_initializer(initializer_range=0.02):
  284. """Creates a `truncated_normal_initializer` with the given range."""
  285. return tf.truncated_normal_initializer(stddev=initializer_range)
  286. def reshape_to_matrix(input_tensor):
  287. """Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix)."""
  288. ndims = input_tensor.shape.ndims
  289. if ndims < 2:
  290. raise ValueError("Input tensor must have at least rank 2. Shape = %s" %
  291. (input_tensor.shape))
  292. if ndims == 2:
  293. return input_tensor
  294. width = input_tensor.shape[-1]
  295. output_tensor = tf.reshape(input_tensor, [-1, width])
  296. return output_tensor
  297. def reshape_from_matrix(output_tensor, orig_shape_list):
  298. """Reshapes a rank 2 tensor back to its original rank >= 2 tensor."""
  299. if len(orig_shape_list) == 2:
  300. return output_tensor
  301. output_shape = shape_list(output_tensor)
  302. orig_dims = orig_shape_list[0:-1]
  303. width = output_shape[-1]
  304. return tf.reshape(output_tensor, orig_dims + [width])
  305. def assert_rank(tensor, expected_rank, name=None):
  306. """Raises an exception if the tensor rank is not of the expected rank.
  307. Args:
  308. tensor: A tf.Tensor to check the rank of.
  309. expected_rank: Python integer or list of integers, expected rank.
  310. name: Optional name of the tensor for the error message.
  311. Raises:
  312. ValueError: If the expected shape doesn't match the actual shape.
  313. """
  314. if name is None:
  315. name = tensor.name
  316. expected_rank_dict = {}
  317. if isinstance(expected_rank, six.integer_types):
  318. expected_rank_dict[expected_rank] = True
  319. else:
  320. for x in expected_rank:
  321. expected_rank_dict[x] = True
  322. actual_rank = tensor.shape.ndims
  323. if actual_rank not in expected_rank_dict:
  324. scope_name = tf.get_variable_scope().name
  325. raise ValueError(
  326. "For the tensor `%s` in scope `%s`, the actual rank "
  327. "`%d` (shape = %s) is not equal to the expected rank `%s`" %
  328. (name, scope_name, actual_rank, str(tensor.shape), str(expected_rank)))
  329. def get_shape_list(tensor, expected_rank=None, name=None):
  330. """Returns a list of the shape of tensor, preferring static dimensions.
  331. Args:
  332. tensor: A tf.Tensor object to find the shape of.
  333. expected_rank: (optional) int. The expected rank of `tensor`. If this is
  334. specified and the `tensor` has a different rank, and exception will be
  335. thrown.
  336. name: Optional name of the tensor for the error message.
  337. Returns:
  338. A list of dimensions of the shape of tensor. All static dimensions will
  339. be returned as python integers, and dynamic dimensions will be returned
  340. as tf.Tensor scalars.
  341. """
  342. if name is None:
  343. name = tensor.name
  344. if expected_rank is not None:
  345. assert_rank(tensor, expected_rank, name)
  346. shape = tensor.shape.as_list()
  347. non_static_indexes = []
  348. for (index, dim) in enumerate(shape):
  349. if dim is None:
  350. non_static_indexes.append(index)
  351. if not non_static_indexes:
  352. return shape
  353. dyn_shape = tf.shape(tensor)
  354. for index in non_static_indexes:
  355. shape[index] = dyn_shape[index]
  356. return shape
  357. def attention_layer(from_tensor,
  358. to_tensor,
  359. attention_mask=None,
  360. num_attention_heads=1,
  361. size_per_head=10,
  362. query_act=None,
  363. key_act=None,
  364. value_act=None,
  365. attention_probs_dropout_prob=0.0,
  366. initializer_range=0.02,
  367. do_return_2d_tensor=False,
  368. batch_size=None,
  369. from_seq_length=None,
  370. to_seq_length=None):
  371. """Performs multi-headed attention from `from_tensor` to `to_tensor`.
  372. This is an implementation of multi-headed attention based on "Attention
  373. is all you Need". If `from_tensor` and `to_tensor` are the same, then
  374. this is self-attention. Each timestep in `from_tensor` attends to the
  375. corresponding sequence in `to_tensor`, and returns a fixed-with vector.
  376. This function first projects `from_tensor` into a "query" tensor and
  377. `to_tensor` into "key" and "value" tensors. These are (effectively) a list
  378. of tensors of length `num_attention_heads`, where each tensor is of shape
  379. [batch_size, seq_length, size_per_head].
  380. Then, the query and key tensors are dot-producted and scaled. These are
  381. softmaxed to obtain attention probabilities. The value tensors are then
  382. interpolated by these probabilities, then concatenated back to a single
  383. tensor and returned.
  384. In practice, the multi-headed attention are done with transposes and
  385. reshapes rather than actual separate tensors.
  386. Args:
  387. from_tensor: float Tensor of shape [batch_size, from_seq_length,
  388. from_width].
  389. to_tensor: float Tensor of shape [batch_size, to_seq_length, to_width].
  390. attention_mask: (optional) int32 Tensor of shape [batch_size,
  391. from_seq_length, to_seq_length]. The values should be 1 or 0. The
  392. attention scores will effectively be set to -infinity for any positions in
  393. the mask that are 0, and will be unchanged for positions that are 1.
  394. num_attention_heads: int. Number of attention heads.
  395. size_per_head: int. Size of each attention head.
  396. query_act: (optional) Activation function for the query transform.
  397. key_act: (optional) Activation function for the key transform.
  398. value_act: (optional) Activation function for the value transform.
  399. attention_probs_dropout_prob: (optional) float. Dropout probability of the
  400. attention probabilities.
  401. initializer_range: float. Range of the weight initializer.
  402. do_return_2d_tensor: bool. If True, the output will be of shape [batch_size
  403. * from_seq_length, num_attention_heads * size_per_head]. If False, the
  404. output will be of shape [batch_size, from_seq_length, num_attention_heads
  405. * size_per_head].
  406. batch_size: (Optional) int. If the input is 2D, this might be the batch size
  407. of the 3D version of the `from_tensor` and `to_tensor`.
  408. from_seq_length: (Optional) If the input is 2D, this might be the seq length
  409. of the 3D version of the `from_tensor`.
  410. to_seq_length: (Optional) If the input is 2D, this might be the seq length
  411. of the 3D version of the `to_tensor`.
  412. Returns:
  413. float Tensor of shape [batch_size, from_seq_length,
  414. num_attention_heads * size_per_head]. (If `do_return_2d_tensor` is
  415. true, this will be of shape [batch_size * from_seq_length,
  416. num_attention_heads * size_per_head]).
  417. Raises:
  418. ValueError: Any of the arguments or tensor shapes are invalid.
  419. """
  420. def transpose_for_scores(input_tensor, batch_size, num_attention_heads,
  421. seq_length, width):
  422. output_tensor = tf.reshape(
  423. input_tensor, [batch_size, seq_length, num_attention_heads, width])
  424. output_tensor = tf.transpose(output_tensor, [0, 2, 1, 3])
  425. return output_tensor
  426. from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])
  427. to_shape = get_shape_list(to_tensor, expected_rank=[2, 3])
  428. if len(from_shape) != len(to_shape):
  429. raise ValueError(
  430. "The rank of `from_tensor` must match the rank of `to_tensor`.")
  431. if len(from_shape) == 3:
  432. batch_size = from_shape[0]
  433. from_seq_length = from_shape[1]
  434. to_seq_length = to_shape[1]
  435. elif len(from_shape) == 2:
  436. if (batch_size is None or from_seq_length is None or to_seq_length is None):
  437. raise ValueError(
  438. "When passing in rank 2 tensors to attention_layer, the values "
  439. "for `batch_size`, `from_seq_length`, and `to_seq_length` "
  440. "must all be specified.")
  441. # Scalar dimensions referenced here:
  442. # B = batch size (number of sequences)
  443. # F = `from_tensor` sequence length
  444. # T = `to_tensor` sequence length
  445. # N = `num_attention_heads`
  446. # H = `size_per_head`
  447. from_tensor_2d = reshape_to_matrix(from_tensor)
  448. to_tensor_2d = reshape_to_matrix(to_tensor)
  449. # `query_layer` = [B*F, N*H]
  450. '''
  451. 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))
  452. query_layer = tf.matmul(from_tensor_2d,query_matrix)
  453. if query_act is not None:
  454. query_layer = query_act(query_layer)
  455. 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))
  456. key_layer = tf.matmul(from_tensor_2d,key_matrix)
  457. if key_act is not None:
  458. key_layer =key_act(key_layer)
  459. 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))
  460. value_layer = tf.matmul(from_tensor_2d,value_matrix)
  461. if value_act is not None:
  462. value_layer = value_act(value_layer)
  463. '''
  464. query_layer = tf.layers.dense(
  465. from_tensor_2d,
  466. num_attention_heads * size_per_head,
  467. activation=query_act,
  468. name="query",
  469. kernel_initializer=create_initializer(initializer_range))
  470. # `key_layer` = [B*T, N*H]
  471. key_layer = tf.layers.dense(
  472. to_tensor_2d,
  473. num_attention_heads * size_per_head,
  474. activation=key_act,
  475. name="key",
  476. kernel_initializer=create_initializer(initializer_range))
  477. # `value_layer` = [B*T, N*H]
  478. value_layer = tf.layers.dense(
  479. to_tensor_2d,
  480. num_attention_heads * size_per_head,
  481. activation=value_act,
  482. name="value",
  483. kernel_initializer=create_initializer(initializer_range))
  484. # `query_layer` = [B, N, F, H]
  485. query_layer = transpose_for_scores(query_layer, batch_size,
  486. num_attention_heads, from_seq_length,
  487. size_per_head)
  488. # `key_layer` = [B, N, T, H]
  489. key_layer = transpose_for_scores(key_layer, batch_size, num_attention_heads,
  490. to_seq_length, size_per_head)
  491. # Take the dot product between "query" and "key" to get the raw
  492. # attention scores.
  493. # `attention_scores` = [B, N, F, T]
  494. attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
  495. attention_scores = tf.multiply(attention_scores,
  496. 1.0 / math.sqrt(float(size_per_head)))
  497. print(attention_scores)
  498. if attention_mask is not None:
  499. # `attention_mask` = [B, 1, F, T]
  500. attention_mask = tf.expand_dims(attention_mask, axis=[1])
  501. # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
  502. # masked positions, this operation will create a tensor which is 0.0 for
  503. # positions we want to attend and -10000.0 for masked positions.
  504. adder = (1.0 - tf.cast(attention_mask, tf.float32)) * -10000.0
  505. # Since we are adding it to the raw scores before the softmax, this is
  506. # effectively the same as removing these entirely.
  507. attention_scores += adder
  508. # Normalize the attention scores to probabilities.
  509. # `attention_probs` = [B, N, F, T]
  510. # B = batch size (number of sequences)
  511. # F = `from_tensor` sequence length
  512. # T = `to_tensor` sequence length
  513. # N = `num_attention_heads`
  514. # H = `size_per_head`
  515. #attention_scores = tf.reshape(attention_scores,[batch_size,num_attention_heads,from_seq_length,to_seq_length])
  516. attention_probs = tf.nn.softmax(attention_scores)
  517. # This is actually dropping out entire tokens to attend to, which might
  518. # seem a bit unusual, but is taken from the original Transformer paper.
  519. attention_probs = dropout(attention_probs, attention_probs_dropout_prob)
  520. # `value_layer` = [B, T, N, H]
  521. value_layer = tf.reshape(
  522. value_layer,
  523. [batch_size, to_seq_length, num_attention_heads, size_per_head])
  524. # `value_layer` = [B, N, T, H]
  525. value_layer = tf.transpose(value_layer, [0, 2, 1, 3])
  526. # `context_layer` = [B, N, F, H]
  527. context_layer = tf.matmul(attention_probs, value_layer)
  528. # `context_layer` = [B, F, N, H]
  529. context_layer = tf.transpose(context_layer, [0, 2, 1, 3])
  530. if do_return_2d_tensor:
  531. # `context_layer` = [B*F, N*H]
  532. context_layer = tf.reshape(
  533. context_layer,
  534. [batch_size * from_seq_length, num_attention_heads * size_per_head])
  535. else:
  536. # `context_layer` = [B, F, N*H]
  537. context_layer = tf.reshape(
  538. context_layer,
  539. [batch_size, from_seq_length, num_attention_heads * size_per_head])
  540. return context_layer
  541. def transformer_model(input_tensor,
  542. attention_mask=None,
  543. hidden_size=120,
  544. num_hidden_layers=1,
  545. num_attention_heads=6,
  546. intermediate_size=256,
  547. intermediate_act_fn=gelu,
  548. hidden_dropout_prob=0.1,
  549. attention_probs_dropout_prob=0.1,
  550. initializer_range=0.02,
  551. do_return_all_layers=False,
  552. name=None):
  553. input_tensor = add_timing_signal_1d(input_tensor,max_timescale=1000)
  554. if hidden_size % num_attention_heads != 0:
  555. raise ValueError(
  556. "The hidden size (%d) is not a multiple of the number of attention "
  557. "heads (%d)" % (hidden_size, num_attention_heads))
  558. attention_head_size = int(hidden_size / num_attention_heads)
  559. input_shape = get_shape_list(input_tensor, expected_rank=3)
  560. batch_size = input_shape[0]
  561. seq_length = input_shape[1]
  562. input_width = input_shape[2]
  563. # The Transformer performs sum residuals on all layers so the input needs
  564. # to be the same as the hidden size.
  565. if input_width != hidden_size:
  566. raise ValueError("The width of the input tensor (%d) != hidden size (%d)" %
  567. (input_width, hidden_size))
  568. # We keep the representation as a 2D tensor to avoid re-shaping it back and
  569. # forth from a 3D tensor to a 2D tensor. Re-shapes are normally free on
  570. # the GPU/CPU but may not be free on the TPU, so we want to minimize them to
  571. # help the optimizer.
  572. prev_output = reshape_to_matrix(input_tensor)
  573. all_layer_outputs = []
  574. if name is not None:
  575. _name = str(name)+"encoder"
  576. else:
  577. _name = "encoder"
  578. with tf.variable_scope(_name,reuse=tf.AUTO_REUSE):
  579. for layer_idx in range(num_hidden_layers):
  580. with tf.variable_scope("layer_%d" % layer_idx,reuse=tf.AUTO_REUSE):
  581. layer_input = prev_output
  582. with tf.variable_scope("attention",reuse=tf.AUTO_REUSE):
  583. attention_heads = []
  584. with tf.variable_scope("self",reuse=tf.AUTO_REUSE):
  585. attention_head = attention_layer(
  586. from_tensor=layer_input,
  587. to_tensor=layer_input,
  588. attention_mask=attention_mask,
  589. num_attention_heads=num_attention_heads,
  590. size_per_head=attention_head_size,
  591. attention_probs_dropout_prob=attention_probs_dropout_prob,
  592. initializer_range=initializer_range,
  593. do_return_2d_tensor=True,
  594. batch_size=batch_size,
  595. from_seq_length=seq_length,
  596. to_seq_length=seq_length)
  597. attention_heads.append(attention_head)
  598. attention_output = None
  599. if len(attention_heads) == 1:
  600. attention_output = attention_heads[0]
  601. else:
  602. # In the case where we have other sequences, we just concatenate
  603. # them to the self-attention head before the projection.
  604. attention_output = tf.concat(attention_heads, axis=-1)
  605. # Run a linear projection of `hidden_size` then add a residual
  606. # with `layer_input`.
  607. with tf.variable_scope("output",reuse=tf.AUTO_REUSE):
  608. attention_output = tf.layers.dense(
  609. attention_output,
  610. hidden_size,
  611. kernel_initializer=create_initializer(initializer_range))
  612. attention_output = dropout(attention_output, hidden_dropout_prob)
  613. attention_output = layer_norm(attention_output + layer_input)
  614. # The activation is only applied to the "intermediate" hidden layer.
  615. with tf.variable_scope("intermediate",reuse=tf.AUTO_REUSE):
  616. intermediate_output = tf.layers.dense(
  617. attention_output,
  618. intermediate_size,
  619. activation=intermediate_act_fn,
  620. kernel_initializer=create_initializer(initializer_range))
  621. # Down-project back to `hidden_size` then add the residual.
  622. with tf.variable_scope("output",reuse=tf.AUTO_REUSE):
  623. layer_output = tf.layers.dense(
  624. intermediate_output,
  625. hidden_size,
  626. kernel_initializer=create_initializer(initializer_range))
  627. layer_output = dropout(layer_output, hidden_dropout_prob)
  628. layer_output = layer_norm(layer_output + attention_output)
  629. prev_output = layer_output
  630. all_layer_outputs.append(layer_output)
  631. if do_return_all_layers:
  632. final_outputs = []
  633. for layer_output in all_layer_outputs:
  634. final_output = reshape_from_matrix(layer_output, input_shape)
  635. final_outputs.append(final_output)
  636. return final_outputs
  637. else:
  638. final_output = reshape_from_matrix(prev_output, input_shape)
  639. return final_output
  640. # def getBiLSTMModel(input_shape,vocab,embedding_weights,classes,use_am=False):
  641. #
  642. # assert len(input_shape)==3
  643. # list_input = []
  644. # for i in range(input_shape[0]):
  645. # list_input.append(layers.Input(shape=(input_shape[1],),dtype=tf.int32))
  646. # print(list_input)
  647. # list_embedding = []
  648. #
  649. # embedding = layers.Embedding(len(vocab),input_shape[2],weights=[embedding_weights] if embedding_weights is not None else None,trainable=True,name="char_embeding")
  650. # for i in range(len(list_input)):
  651. # list_embedding.append(embedding(list_input[i]))
  652. # #
  653. # bert_layer = layers.Lambda(transformer_model,trainable=True,name="bert")
  654. # set_variables = set()
  655. # for v in tf.trainable_variables():
  656. # set_variables.add(v.name)
  657. # list_bert = []
  658. # for i in range(len(list_embedding)):
  659. # list_bert.append(bert_layer(list_embedding[i]))
  660. # #set bert_weights to trainable
  661. # bert_weights = []
  662. # for v in tf.trainable_variables():
  663. # if v.name not in set_variables:
  664. # bert_weights.append(v)
  665. # bert_layer._trainable_weights = bert_weights
  666. #
  667. # list_w2v = list_bert
  668. # list_lstm = []
  669. #
  670. # if use_am:
  671. # for i in range(len(list_w2v)):
  672. # list_lstm.append(Attention()(layers.Bidirectional(layers.LSTM(120,activation="relu",return_sequences=True))(list_w2v[i])))
  673. # else:
  674. # for i in range(len(list_w2v)):
  675. # list_lstm.append(layers.Bidirectional(layers.LSTM(24,activation="relu"))(list_w2v[i]))
  676. #
  677. #
  678. # list_matrix = []
  679. # for i in range(len(list_lstm)):
  680. # list_matrix.append(layers.Dense(classes*2,activation="relu")(list_lstm[i]))
  681. #
  682. # if len(list_matrix)>1:
  683. # ave = layers.merge(list_matrix,mode="concat")
  684. #
  685. # dropout = layers.Dropout(0.4)(ave)
  686. # else:
  687. # dropout = layers.Dropout(0.4)(list_matrix[0])
  688. #
  689. #
  690. # matrix = layers.Dense(classes*10,activation="sigmoid")(dropout)
  691. #
  692. # out = layers.Dense(classes,activation="softmax")(matrix)
  693. #
  694. # model = models.Model(list_input,out)
  695. #
  696. # model.compile(optimizer=optimizers.Adam(lr=0.00002),loss=losses.categorical_crossentropy,metrics=[precision,recall,f1_score])
  697. #
  698. # model.summary()
  699. #
  700. # return model
  701. def getBiLSTMModel(input_shape,vocab,embedding_weights,classes,use_am=False):
  702. def resize(x):
  703. _shape = shape_list(x)
  704. print("#$",_shape)
  705. x1 = tf.reshape(x,[_shape[0],3,_shape[1]//3,_shape[2]]) # type: object
  706. print("--")
  707. x2 = tf.transpose(x1,[1,0,2,3])
  708. x_l,x_c,x_r = tf.split(x2,[1,1,1],axis=0)
  709. return [tf.squeeze(x_l,axis=0),tf.squeeze(x_c,axis=0),tf.squeeze(x_r,axis=0)]
  710. def resize_input(x):
  711. _shape = shape_list(x)
  712. x1 = tf.reshape(x,[_shape[0],3,_shape[1]//3]) # type: object
  713. x2 = tf.transpose(x1,[1,0,2])
  714. x_l,x_c,x_r = tf.split(x2,[1,1,1],axis=0)
  715. return [tf.squeeze(x_l,axis=0),tf.squeeze(x_c,axis=0),tf.squeeze(x_r,axis=0)]
  716. # assert len(input_shape)==3
  717. list_input = []
  718. for i in range(input_shape[0]):
  719. list_input.append(layers.Input(shape=(input_shape[1],),dtype=tf.int32,name="input%d"%(i)))
  720. print("list_input",list_input)
  721. list_embedding = []
  722. # if len(list_input)==1:
  723. # list_resizeinput = layers.Lambda(resize_input)(list_input[0])
  724. # else:
  725. # concat_input = layers.Lambda(lambda x:tf.concat(x,axis=-1))(list_input)
  726. # embedding_input = [concat_input]
  727. embedding_input = list_input
  728. embedding = layers.Embedding(len(vocab),input_shape[2],weights=[embedding_weights] if embedding_weights is not None else None,trainable=True,name="char_embeding")
  729. for i in range(len(embedding_input)):
  730. print(i)
  731. list_embedding.append(embedding(embedding_input[i]))
  732. print(list_embedding)
  733. #
  734. set_variables = set()
  735. for v in tf.trainable_variables():
  736. set_variables.add(v.name)
  737. # list_bert = []
  738. # for i in range(len(list_embedding)):
  739. # for v in tf.trainable_variables():
  740. # set_variables.add(v.name)
  741. # bert_layer = layers.Lambda(lambda x:transformer_model(input_tensor=x,name="bert%d"%(i)),trainable=True,name="bert%d"%(i))
  742. # list_bert.append(bert_layer(list_embedding[i]))
  743. # #set bert_weights to trainable
  744. # bert_weights = []
  745. # for v in tf.trainable_variables():
  746. # if v.name not in set_variables:
  747. # print("++++",v.name)
  748. # bert_weights.append(v)
  749. # bert_layer._trainable_weights = bert_weights
  750. bert_layer = layers.Lambda(lambda x:transformer_model(input_tensor=x,name="bert%d"%(i)),trainable=True,name="bert%d"%(0))
  751. list_bert = []
  752. for i in range(len(list_embedding)):
  753. list_bert.append(bert_layer(list_embedding[i]))
  754. #set bert_weights to trainable
  755. bert_weights = []
  756. for v in tf.trainable_variables():
  757. if v.name not in set_variables:
  758. print("++++",v.name)
  759. bert_weights.append(v)
  760. bert_layer._trainable_weights = bert_weights
  761. print("##",list_bert)
  762. # context_embedding = []
  763. # list_kernel = [5,8]
  764. # for i in range(len(list_bert)):
  765. # list_temp = []
  766. # for kernel in list_kernel:
  767. # list_temp.append(layers.Conv1D(3,kernel,strides=1,padding="same",activation="relu")(list_bert[i]))
  768. # context_embedding.append(layers.Dense(12,activation="relu")(layers.Flatten()(layers.merge(list_temp,mode="concat"))))
  769. # context_embedding = [layers.GlobalMaxPool1D()(item) for item in list_bert]
  770. # _resize = layers.Lambda(lambda x:resize(x))(list_bert[0])
  771. list_w2v = list_bert
  772. list_lstm = []
  773. if use_am:
  774. for i in range(len(list_w2v)):
  775. list_lstm.append(Attention()(layers.Bidirectional(layers.LSTM(120,activation="relu",return_sequences=True))(list_w2v[i])))
  776. else:
  777. for i in range(len(list_w2v)):
  778. list_lstm.append(layers.Bidirectional(layers.LSTM(24,activation="relu"))(list_w2v[i]))
  779. # list_avg = []
  780. # for i in range(len(list_lstm)):
  781. # list_avg.append(layers.GlobalAveragePooling1D()(list_lstm[i]))
  782. list_matrix = []
  783. for i in range(len(list_lstm)):
  784. list_matrix.append(layers.Dense(12,activation="relu")(list_lstm[i]))
  785. # list_matrix.extend(context_embedding)
  786. if len(list_matrix)>1:
  787. ave = layers.merge(list_matrix,mode="concat")
  788. dropout = layers.Dropout(0.2)(ave)
  789. else:
  790. dropout = layers.Dropout(0.2)(list_matrix[0])
  791. matrix = layers.Dense(48,activation="tanh")(dropout)
  792. out = layers.Dense(classes,activation="softmax")(matrix)
  793. # out = layers.Dense(classes,activation="sigmoid")(dropout)
  794. # out = layers.Lambda(lambda x:layers.activations.softmax(x))(out)
  795. model = models.Model(list_input,out)
  796. model.compile(optimizer=optimizers.Adam(lr=0.01),loss=losses.categorical_crossentropy,metrics=[precision,recall,f1_score])
  797. model.summary()
  798. return model
  799. def getBiLSTMModel_entity(input_shape,vocab,embedding_weights,classes):
  800. list_input = []
  801. for i in range(input_shape[0]):
  802. list_input.append(layers.Input(shape=(input_shape[1],),dtype=tf.int32,name="input%d"%(i)))
  803. print("list_input",list_input)
  804. list_embedding = []
  805. embedding_input = list_input
  806. embedding = layers.Embedding(len(vocab),input_shape[2],weights=[embedding_weights] if embedding_weights is not None else None,trainable=True,name="char_embeding")
  807. for i in range(len(embedding_input)):
  808. print(i)
  809. list_embedding.append(embedding(embedding_input[i]))
  810. print(list_embedding)
  811. list_w2v = list_embedding
  812. list_lstm = []
  813. for i in range(len(list_w2v)):
  814. list_lstm.append(layers.Bidirectional(layers.LSTM(24,activation="relu"))(list_w2v[i]))
  815. # list_avg = []
  816. # for i in range(len(list_lstm)):
  817. # list_avg.append(layers.GlobalAveragePooling1D()(list_lstm[i]))
  818. list_matrix = []
  819. for i in range(len(list_lstm)):
  820. list_matrix.append(layers.Dense(12,activation="relu")(list_lstm[i]))
  821. if len(list_matrix)>1:
  822. ave = layers.merge(list_matrix,mode="concat")
  823. dropout = layers.Dropout(0.2)(ave)
  824. else:
  825. dropout = layers.Dropout(0.2)(list_matrix[0])
  826. matrix = layers.Dense(classes*10,activation="relu")(dropout)
  827. out = layers.Dense(classes,activation="softmax")(matrix)
  828. # out = layers.Dense(classes,activation="sigmoid")(dropout)
  829. # out = layers.Lambda(lambda x:layers.activations.softmax(x))(out)
  830. model = models.Model(list_input,out)
  831. model.compile(optimizer=optimizers.Adam(lr=0.00001),loss=losses.categorical_crossentropy,metrics=[precision,recall,f1_score])
  832. model.summary()
  833. return model
  834. if __name__=="__main__":
  835. #getTextCNNModel((3,100,60),[1,2,3,4,5],None,2)
  836. model = getBiLSTMModel((3,100,256),fool_char_to_id.keys(),None,3,use_am=False)
  837. #getBiLSTMModel_entity((20,20,3,100,60),[1,2,3,4,5],None,6)