首页 技术 正文
技术 2022年11月19日
0 收藏 854 点赞 2,446 浏览 23501 个字

http://blog.csdn.net/scotfield_msn/article/details/60339415

在TensorFlow (RNN)深度学习下 双向LSTM(BiLSTM)+CRF 实现 sequence labeling 

双向LSTM+CRF跑序列标注问题

源码下载

去年底样子一直在做NLP相关task,是个关于序列标注问题。这 sequence labeling属于NLP的经典问题了,开始尝试用HMM,哦不,用CRF做baseline,by the way, 用的CRF++。

关于CRF的理论就不再啰嗦了,街货。顺便提下,CRF比HMM在理论上以及实际效果上都要好不少。但我要说的是CRF跑我这task还是不太乐观。P值0.6样子,R低的离谱,所以F1很不乐观。mentor告诉我说是特征不足,师兄说是这个task本身就比较难做,F1低算是正常了。

CRF做完baseline后,一直在着手用BiLSTM+CRF跑 sequence labeling,奈何项目繁多,没有多余的精力去按照正常的计划做出来。后来还是一点一点的,按照大牛们的步骤以及参考现有的代码,把 BiLSTM+CRF的实现拿下了。后来发现,跑出来的效果也不太理想……可能是这个task确实变态……抑或模型还要加强吧~

这里对比下CRF与LSTM的cell,先说RNN吧,RNN其实是比CNN更适合做序列问题的模型,RNN隐层当前时刻的输入有一部分是前一时刻的隐层输出,这使得他能通过循环反馈连接看到前面的信息,将一段序列的前面的context capture 过来参与此刻的计算,并且还具备非线性的拟合能力,这都是CRF无法超越的地方。而LSTM的cell很好的将RNN的梯度弥散问题优化解决了,他对门卫gate说:老兄,有的不太重要的信息,你该忘掉就忘掉吧,免得占用现在的资源。而双向LSTM就更厉害了,不仅看得到过去,还能将未来的序列考虑进来,使得上下文信息充分被利用。而CRF,他不像LSTM能够考虑长远的上下文信息,它更多地考虑整个句子的局部特征的线性加权组合(通过特征模板扫描整个句子),特别的一点,他计算的是联合概率,优化了整个序列,而不是拼接每个时刻的最优值。那么,将BILSTM与CRF一起就构成了还比较不错的组合,这目前也是学术界的流行做法~

另外针对目前的跑通结果提几个改进点:

1.+CNN,通过CNN的卷积操作去提取英文单词的字母细节。

2.+char representation,作用与上相似,提取更细粒度的细节。

3.考虑将特定的人工提取的规则融入到NN模型中去。

好了,叨了不少。codes time:

完整代码以及相关预处理的数据请移步github: scofiled’s github/bilstm+crf

注明:codes参考的是chilynn

requirements:

ubuntu14

python2.7

tensorflow 0.8

numpy

pandas0.15

BILSTM_CRF.py

  1. import math
  2. import helper
  3. import numpy as np
  4. import tensorflow as tf
  5. from tensorflow.models.rnn import rnn, rnn_cell
  6. class BILSTM_CRF(object):
  7. def __init__(self, num_chars, num_classes, num_steps=200, num_epochs=100, embedding_matrix=None, is_training=True, is_crf=True, weight=False):
  8. # Parameter
  9. self.max_f1 = 0
  10. self.learning_rate = 0.002
  11. self.dropout_rate = 0.5
  12. self.batch_size = 128
  13. self.num_layers = 1
  14. self.emb_dim = 100
  15. self.hidden_dim = 100
  16. self.num_epochs = num_epochs
  17. self.num_steps = num_steps
  18. self.num_chars = num_chars
  19. self.num_classes = num_classes
  20. # placeholder of x, y and weight
  21. self.inputs = tf.placeholder(tf.int32, [None, self.num_steps])
  22. self.targets = tf.placeholder(tf.int32, [None, self.num_steps])
  23. self.targets_weight = tf.placeholder(tf.float32, [None, self.num_steps])
  24. self.targets_transition = tf.placeholder(tf.int32, [None])
  25. # char embedding
  26. if embedding_matrix != None:
  27. self.embedding = tf.Variable(embedding_matrix, trainable=False, name=”emb”, dtype=tf.float32)
  28. else:
  29. self.embedding = tf.get_variable(“emb”, [self.num_chars, self.emb_dim])
  30. self.inputs_emb = tf.nn.embedding_lookup(self.embedding, self.inputs)
  31. self.inputs_emb = tf.transpose(self.inputs_emb, [1, 0, 2])
  32. self.inputs_emb = tf.reshape(self.inputs_emb, [-1, self.emb_dim])
  33. self.inputs_emb = tf.split(0, self.num_steps, self.inputs_emb)
  34. # lstm cell
  35. lstm_cell_fw = tf.nn.rnn_cell.BasicLSTMCell(self.hidden_dim)
  36. lstm_cell_bw = tf.nn.rnn_cell.BasicLSTMCell(self.hidden_dim)
  37. # dropout
  38. if is_training:
  39. lstm_cell_fw = tf.nn.rnn_cell.DropoutWrapper(lstm_cell_fw, output_keep_prob=(1 – self.dropout_rate))
  40. lstm_cell_bw = tf.nn.rnn_cell.DropoutWrapper(lstm_cell_bw, output_keep_prob=(1 – self.dropout_rate))
  41. lstm_cell_fw = tf.nn.rnn_cell.MultiRNNCell([lstm_cell_fw] * self.num_layers)
  42. lstm_cell_bw = tf.nn.rnn_cell.MultiRNNCell([lstm_cell_bw] * self.num_layers)
  43. # get the length of each sample
  44. self.length = tf.reduce_sum(tf.sign(self.inputs), reduction_indices=1)
  45. self.length = tf.cast(self.length, tf.int32)
  46. # forward and backward
  47. self.outputs, _, _ = rnn.bidirectional_rnn(
  48. lstm_cell_fw,
  49. lstm_cell_bw,
  50. self.inputs_emb,
  51. dtype=tf.float32,
  52. sequence_length=self.length
  53. )
  54. # softmax
  55. self.outputs = tf.reshape(tf.concat(1, self.outputs), [-1, self.hidden_dim * 2])
  56. self.softmax_w = tf.get_variable(“softmax_w”, [self.hidden_dim * 2, self.num_classes])
  57. self.softmax_b = tf.get_variable(“softmax_b”, [self.num_classes])
  58. self.logits = tf.matmul(self.outputs, self.softmax_w) + self.softmax_b
  59. if not is_crf:
  60. pass
  61. else:
  62. self.tags_scores = tf.reshape(self.logits, [self.batch_size, self.num_steps, self.num_classes])
  63. self.transitions = tf.get_variable(“transitions”, [self.num_classes + 1, self.num_classes + 1])
  64. dummy_val = -1000
  65. class_pad = tf.Variable(dummy_val * np.ones((self.batch_size, self.num_steps, 1)), dtype=tf.float32)
  66. self.observations = tf.concat(2, [self.tags_scores, class_pad])
  67. begin_vec = tf.Variable(np.array([[dummy_val] * self.num_classes + [0] for _ in range(self.batch_size)]), trainable=False, dtype=tf.float32)
  68. end_vec = tf.Variable(np.array([[0] + [dummy_val] * self.num_classes for _ in range(self.batch_size)]), trainable=False, dtype=tf.float32)
  69. begin_vec = tf.reshape(begin_vec, [self.batch_size, 1, self.num_classes + 1])
  70. end_vec = tf.reshape(end_vec, [self.batch_size, 1, self.num_classes + 1])
  71. self.observations = tf.concat(1, [begin_vec, self.observations, end_vec])
  72. self.mask = tf.cast(tf.reshape(tf.sign(self.targets),[self.batch_size * self.num_steps]), tf.float32)
  73. # point score
  74. self.point_score = tf.gather(tf.reshape(self.tags_scores, [-1]), tf.range(0, self.batch_size * self.num_steps) * self.num_classes + tf.reshape(self.targets,[self.batch_size * self.num_steps]))
  75. self.point_score *= self.mask
  76. # transition score
  77. self.trans_score = tf.gather(tf.reshape(self.transitions, [-1]), self.targets_transition)
  78. # real score
  79. self.target_path_score = tf.reduce_sum(self.point_score) + tf.reduce_sum(self.trans_score)
  80. # all path score
  81. self.total_path_score, self.max_scores, self.max_scores_pre  = self.forward(self.observations, self.transitions, self.length)
  82. # loss
  83. self.loss = – (self.target_path_score – self.total_path_score)
  84. # summary
  85. self.train_summary = tf.scalar_summary(“loss”, self.loss)
  86. self.val_summary = tf.scalar_summary(“loss”, self.loss)
  87. self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.loss)
  88. def logsumexp(self, x, axis=None):
  89. x_max = tf.reduce_max(x, reduction_indices=axis, keep_dims=True)
  90. x_max_ = tf.reduce_max(x, reduction_indices=axis)
  91. return x_max_ + tf.log(tf.reduce_sum(tf.exp(x – x_max), reduction_indices=axis))
  92. def forward(self, observations, transitions, length, is_viterbi=True, return_best_seq=True):
  93. length = tf.reshape(length, [self.batch_size])
  94. transitions = tf.reshape(tf.concat(0, [transitions] * self.batch_size), [self.batch_size, 6, 6])
  95. observations = tf.reshape(observations, [self.batch_size, self.num_steps + 2, 6, 1])
  96. observations = tf.transpose(observations, [1, 0, 2, 3])
  97. previous = observations[0, :, :, :]
  98. max_scores = []
  99. max_scores_pre = []
  100. alphas = [previous]
  101. for t in range(1, self.num_steps + 2):
  102. previous = tf.reshape(previous, [self.batch_size, 6, 1])
  103. current = tf.reshape(observations[t, :, :, :], [self.batch_size, 1, 6])
  104. alpha_t = previous + current + transitions
  105. if is_viterbi:
  106. max_scores.append(tf.reduce_max(alpha_t, reduction_indices=1))
  107. max_scores_pre.append(tf.argmax(alpha_t, dimension=1))
  108. alpha_t = tf.reshape(self.logsumexp(alpha_t, axis=1), [self.batch_size, 6, 1])
  109. alphas.append(alpha_t)
  110. previous = alpha_t
  111. alphas = tf.reshape(tf.concat(0, alphas), [self.num_steps + 2, self.batch_size, 6, 1])
  112. alphas = tf.transpose(alphas, [1, 0, 2, 3])
  113. alphas = tf.reshape(alphas, [self.batch_size * (self.num_steps + 2), 6, 1])
  114. last_alphas = tf.gather(alphas, tf.range(0, self.batch_size) * (self.num_steps + 2) + length)
  115. last_alphas = tf.reshape(last_alphas, [self.batch_size, 6, 1])
  116. max_scores = tf.reshape(tf.concat(0, max_scores), (self.num_steps + 1, self.batch_size, 6))
  117. max_scores_pre = tf.reshape(tf.concat(0, max_scores_pre), (self.num_steps + 1, self.batch_size, 6))
  118. max_scores = tf.transpose(max_scores, [1, 0, 2])
  119. max_scores_pre = tf.transpose(max_scores_pre, [1, 0, 2])
  120. return tf.reduce_sum(self.logsumexp(last_alphas, axis=1)), max_scores, max_scores_pre
  121. def train(self, sess, save_file, X_train, y_train, X_val, y_val):
  122. saver = tf.train.Saver()
  123. char2id, id2char = helper.loadMap(“char2id”)
  124. label2id, id2label = helper.loadMap(“label2id”)
  125. merged = tf.merge_all_summaries()
  126. summary_writer_train = tf.train.SummaryWriter(‘loss_log/train_loss’, sess.graph)
  127. summary_writer_val = tf.train.SummaryWriter(‘loss_log/val_loss’, sess.graph)
  128. num_iterations = int(math.ceil(1.0 * len(X_train) / self.batch_size))
  129. cnt = 0
  130. for epoch in range(self.num_epochs):
  131. # shuffle train in each epoch
  132. sh_index = np.arange(len(X_train))
  133. np.random.shuffle(sh_index)
  134. X_train = X_train[sh_index]
  135. y_train = y_train[sh_index]
  136. print “current epoch: %d” % (epoch)
  137. for iteration in range(num_iterations):
  138. # train
  139. X_train_batch, y_train_batch = helper.nextBatch(X_train, y_train, start_index=iteration * self.batch_size, batch_size=self.batch_size)
  140. y_train_weight_batch = 1 + np.array((y_train_batch == label2id[‘B’]) | (y_train_batch == label2id[‘E’]), float)
  141. transition_batch = helper.getTransition(y_train_batch)
  142. _, loss_train, max_scores, max_scores_pre, length, train_summary =\
  143. sess.run([
  144. self.optimizer,
  145. self.loss,
  146. self.max_scores,
  147. self.max_scores_pre,
  148. self.length,
  149. self.train_summary
  150. ],
  151. feed_dict={
  152. self.targets_transition:transition_batch,
  153. self.inputs:X_train_batch,
  154. self.targets:y_train_batch,
  155. self.targets_weight:y_train_weight_batch
  156. })
  157. predicts_train = self.viterbi(max_scores, max_scores_pre, length, predict_size=self.batch_size)
  158. if iteration % 10 == 0:
  159. cnt += 1
  160. precision_train, recall_train, f1_train = self.evaluate(X_train_batch, y_train_batch, predicts_train, id2char, id2label)
  161. summary_writer_train.add_summary(train_summary, cnt)
  162. print “iteration: %5d, train loss: %5d, train precision: %.5f, train recall: %.5f, train f1: %.5f” % (iteration, loss_train, precision_train, recall_train, f1_train)
  163. # validation
  164. if iteration % 100 == 0:
  165. X_val_batch, y_val_batch = helper.nextRandomBatch(X_val, y_val, batch_size=self.batch_size)
  166. y_val_weight_batch = 1 + np.array((y_val_batch == label2id[‘B’]) | (y_val_batch == label2id[‘E’]), float)
  167. transition_batch = helper.getTransition(y_val_batch)
  168. loss_val, max_scores, max_scores_pre, length, val_summary =\
  169. sess.run([
  170. self.loss,
  171. self.max_scores,
  172. self.max_scores_pre,
  173. self.length,
  174. self.val_summary
  175. ],
  176. feed_dict={
  177. self.targets_transition:transition_batch,
  178. self.inputs:X_val_batch,
  179. self.targets:y_val_batch,
  180. self.targets_weight:y_val_weight_batch
  181. })
  182. predicts_val = self.viterbi(max_scores, max_scores_pre, length, predict_size=self.batch_size)
  183. precision_val, recall_val, f1_val = self.evaluate(X_val_batch, y_val_batch, predicts_val, id2char, id2label)
  184. summary_writer_val.add_summary(val_summary, cnt)
  185. print “iteration: %5d, valid loss: %5d, valid precision: %.5f, valid recall: %.5f, valid f1: %.5f” % (iteration, loss_val, precision_val, recall_val, f1_val)
  186. if f1_val > self.max_f1:
  187. self.max_f1 = f1_val
  188. save_path = saver.save(sess, save_file)
  189. print “saved the best model with f1: %.5f” % (self.max_f1)
  190. def test(self, sess, X_test, X_test_str, output_path):
  191. char2id, id2char = helper.loadMap(“char2id”)
  192. label2id, id2label = helper.loadMap(“label2id”)
  193. num_iterations = int(math.ceil(1.0 * len(X_test) / self.batch_size))
  194. print “number of iteration: ” + str(num_iterations)
  195. with open(output_path, “wb”) as outfile:
  196. for i in range(num_iterations):
  197. print “iteration: ” + str(i + 1)
  198. results = []
  199. X_test_batch = X_test[i * self.batch_size : (i + 1) * self.batch_size]
  200. X_test_str_batch = X_test_str[i * self.batch_size : (i + 1) * self.batch_size]
  201. if i == num_iterations – 1 and len(X_test_batch) < self.batch_size:
  202. X_test_batch = list(X_test_batch)
  203. X_test_str_batch = list(X_test_str_batch)
  204. last_size = len(X_test_batch)
  205. X_test_batch += [[0 for j in range(self.num_steps)] for i in range(self.batch_size – last_size)]
  206. X_test_str_batch += [[‘x’ for j in range(self.num_steps)] for i in range(self.batch_size – last_size)]
  207. X_test_batch = np.array(X_test_batch)
  208. X_test_str_batch = np.array(X_test_str_batch)
  209. results = self.predictBatch(sess, X_test_batch, X_test_str_batch, id2label)
  210. results = results[:last_size]
  211. else:
  212. X_test_batch = np.array(X_test_batch)
  213. results = self.predictBatch(sess, X_test_batch, X_test_str_batch, id2label)
  214. for i in range(len(results)):
  215. doc = ”.join(X_test_str_batch[i])
  216. outfile.write(doc + “<@>” +” “.join(results[i]).encode(“utf-8”) + “\n”)
  217. def viterbi(self, max_scores, max_scores_pre, length, predict_size=128):
  218. best_paths = []
  219. for m in range(predict_size):
  220. path = []
  221. last_max_node = np.argmax(max_scores[m][length[m]])
  222. # last_max_node = 0
  223. for t in range(1, length[m] + 1)[::-1]:
  224. last_max_node = max_scores_pre[m][t][last_max_node]
  225. path.append(last_max_node)
  226. path = path[::-1]
  227. best_paths.append(path)
  228. return best_paths
  229. def predictBatch(self, sess, X, X_str, id2label):
  230. results = []
  231. length, max_scores, max_scores_pre = sess.run([self.length, self.max_scores, self.max_scores_pre], feed_dict={self.inputs:X})
  232. predicts = self.viterbi(max_scores, max_scores_pre, length, self.batch_size)
  233. for i in range(len(predicts)):
  234. x = ”.join(X_str[i]).decode(“utf-8”)
  235. y_pred = ”.join([id2label[val] for val in predicts[i] if val != 5 and val != 0])
  236. entitys = helper.extractEntity(x, y_pred)
  237. results.append(entitys)
  238. return results
  239. def evaluate(self, X, y_true, y_pred, id2char, id2label):
  240. precision = -1.0
  241. recall = -1.0
  242. f1 = -1.0
  243. hit_num = 0
  244. pred_num = 0
  245. true_num = 0
  246. for i in range(len(y_true)):
  247. x = ”.join([str(id2char[val].encode(“utf-8”)) for val in X[i]])
  248. y = ”.join([str(id2label[val].encode(“utf-8”)) for val in y_true[i]])
  249. y_hat = ”.join([id2label[val] for val in y_pred[i]  if val != 5])
  250. true_labels = helper.extractEntity(x, y)
  251. pred_labels = helper.extractEntity(x, y_hat)
  252. hit_num += len(set(true_labels) & set(pred_labels))
  253. pred_num += len(set(pred_labels))
  254. true_num += len(set(true_labels))
  255. if pred_num != 0:
  256. precision = 1.0 * hit_num / pred_num
  257. if true_num != 0:
  258. recall = 1.0 * hit_num / true_num
  259. if precision > 0 and recall > 0:
  260. f1 = 2.0 * (precision * recall) / (precision + recall)
  261. return precision, recall, f1

util.py

  1. #encoding:utf-8
  2. import re
  3. import os
  4. import csv
  5. import time
  6. import pickle
  7. import numpy as np
  8. import pandas as pd
  9. def getEmbedding(infile_path=”embedding”):
  10. char2id, id_char = loadMap(“char2id”)
  11. row_index = 0
  12. with open(infile_path, “rb”) as infile:
  13. for row in infile:
  14. row = row.strip()
  15. row_index += 1
  16. if row_index == 1:
  17. num_chars = int(row.split()[0])
  18. emb_dim = int(row.split()[1])
  19. emb_matrix = np.zeros((len(char2id.keys()), emb_dim))
  20. continue
  21. items = row.split()
  22. char = items[0]
  23. emb_vec = [float(val) for val in items[1:]]
  24. if char in char2id:
  25. emb_matrix[char2id[char]] = emb_vec
  26. return emb_matrix
  27. def nextBatch(X, y, start_index, batch_size=128):
  28. last_index = start_index + batch_size
  29. X_batch = list(X[start_index:min(last_index, len(X))])
  30. y_batch = list(y[start_index:min(last_index, len(X))])
  31. if last_index > len(X):
  32. left_size = last_index – (len(X))
  33. for i in range(left_size):
  34. index = np.random.randint(len(X))
  35. X_batch.append(X[index])
  36. y_batch.append(y[index])
  37. X_batch = np.array(X_batch)
  38. y_batch = np.array(y_batch)
  39. return X_batch, y_batch
  40. def nextRandomBatch(X, y, batch_size=128):
  41. X_batch = []
  42. y_batch = []
  43. for i in range(batch_size):
  44. index = np.random.randint(len(X))
  45. X_batch.append(X[index])
  46. y_batch.append(y[index])
  47. X_batch = np.array(X_batch)
  48. y_batch = np.array(y_batch)
  49. return X_batch, y_batch
  50. # use “0” to padding the sentence
  51. def padding(sample, seq_max_len):
  52. for i in range(len(sample)):
  53. if len(sample[i]) < seq_max_len:
  54. sample[i] += [0 for _ in range(seq_max_len – len(sample[i]))]
  55. return sample
  56. def prepare(chars, labels, seq_max_len, is_padding=True):
  57. X = []
  58. y = []
  59. tmp_x = []
  60. tmp_y = []
  61. for record in zip(chars, labels):
  62. c = record[0]
  63. l = record[1]
  64. # empty line
  65. if c == -1:
  66. if len(tmp_x) <= seq_max_len:
  67. X.append(tmp_x)
  68. y.append(tmp_y)
  69. tmp_x = []
  70. tmp_y = []
  71. else:
  72. tmp_x.append(c)
  73. tmp_y.append(l)
  74. if is_padding:
  75. X = np.array(padding(X, seq_max_len))
  76. else:
  77. X = np.array(X)
  78. y = np.array(padding(y, seq_max_len))
  79. return X, y
  80. def extractEntity(sentence, labels):
  81. entitys = []
  82. re_entity = re.compile(r’BM*E’)
  83. m = re_entity.search(labels)
  84. while m:
  85. entity_labels = m.group()
  86. start_index = labels.find(entity_labels)
  87. entity = sentence[start_index:start_index + len(entity_labels)]
  88. labels = list(labels)
  89. # replace the “BM*E” with “OO*O”
  90. labels[start_index: start_index + len(entity_labels)] = [‘O’ for i in range(len(entity_labels))]
  91. entitys.append(entity)
  92. labels = ”.join(labels)
  93. m = re_entity.search(labels)
  94. return entitys
  95. def loadMap(token2id_filepath):
  96. if not os.path.isfile(token2id_filepath):
  97. print “file not exist, building map”
  98. buildMap()
  99. token2id = {}
  100. id2token = {}
  101. with open(token2id_filepath) as infile:
  102. for row in infile:
  103. row = row.rstrip().decode(“utf-8”)
  104. token = row.split(‘\t’)[0]
  105. token_id = int(row.split(‘\t’)[1])
  106. token2id[token] = token_id
  107. id2token[token_id] = token
  108. return token2id, id2token
  109. def saveMap(id2char, id2label):
  110. with open(“char2id”, “wb”) as outfile:
  111. for idx in id2char:
  112. outfile.write(id2char[idx] + “\t” + str(idx)  + “\r\n”)
  113. with open(“label2id”, “wb”) as outfile:
  114. for idx in id2label:
  115. outfile.write(id2label[idx] + “\t” + str(idx) + “\r\n”)
  116. print “saved map between token and id”
  117. def buildMap(train_path=”train.in”):
  118. df_train = pd.read_csv(train_path, delimiter=’\t’, quoting=csv.QUOTE_NONE, skip_blank_lines=False, header=None, names=[“char”, “label”])
  119. chars = list(set(df_train[“char”][df_train[“char”].notnull()]))
  120. labels = list(set(df_train[“label”][df_train[“label”].notnull()]))
  121. char2id = dict(zip(chars, range(1, len(chars) + 1)))
  122. label2id = dict(zip(labels, range(1, len(labels) + 1)))
  123. id2char = dict(zip(range(1, len(chars) + 1), chars))
  124. id2label =  dict(zip(range(1, len(labels) + 1), labels))
  125. id2char[0] = “<PAD>”
  126. id2label[0] = “<PAD>”
  127. char2id[“<PAD>”] = 0
  128. label2id[“<PAD>”] = 0
  129. id2char[len(chars) + 1] = “<NEW>”
  130. char2id[“<NEW>”] = len(chars) + 1
  131. saveMap(id2char, id2label)
  132. return char2id, id2char, label2id, id2label
  133. def getTrain(train_path, val_path, train_val_ratio=0.99, use_custom_val=False, seq_max_len=200):
  134. char2id, id2char, label2id, id2label = buildMap(train_path)
  135. df_train = pd.read_csv(train_path, delimiter=’\t’, quoting=csv.QUOTE_NONE, skip_blank_lines=False, header=None, names=[“char”, “label”])
  136. # map the char and label into id
  137. df_train[“char_id”] = df_train.char.map(lambda x : -1 if str(x) == str(np.nan) else char2id[x])
  138. df_train[“label_id”] = df_train.label.map(lambda x : -1 if str(x) == str(np.nan) else label2id[x])
  139. # convert the data in maxtrix
  140. X, y = prepare(df_train[“char_id”], df_train[“label_id”], seq_max_len)
  141. # shuffle the samples
  142. num_samples = len(X)
  143. indexs = np.arange(num_samples)
  144. np.random.shuffle(indexs)
  145. X = X[indexs]
  146. y = y[indexs]
  147. if val_path != None:
  148. X_train = X
  149. y_train = y
  150. X_val, y_val = getTest(val_path, is_validation=True, seq_max_len=seq_max_len)
  151. else:
  152. # split the data into train and validation set
  153. X_train = X[:int(num_samples * train_val_ratio)]
  154. y_train = y[:int(num_samples * train_val_ratio)]
  155. X_val = X[int(num_samples * train_val_ratio):]
  156. y_val = y[int(num_samples * train_val_ratio):]
  157. print “train size: %d, validation size: %d” %(len(X_train), len(y_val))
  158. return X_train, y_train, X_val, y_val
  159. def getTest(test_path=”test.in”, is_validation=False, seq_max_len=200):
  160. char2id, id2char = loadMap(“char2id”)
  161. label2id, id2label = loadMap(“label2id”)
  162. df_test = pd.read_csv(test_path, delimiter=’\t’, quoting=csv.QUOTE_NONE, skip_blank_lines=False, header=None, names=[“char”, “label”])
  163. def mapFunc(x, char2id):
  164. if str(x) == str(np.nan):
  165. return -1
  166. elif x.decode(“utf-8”) not in char2id:
  167. return char2id[“<NEW>”]
  168. else:
  169. return char2id[x.decode(“utf-8”)]
  170. df_test[“char_id”] = df_test.char.map(lambda x:mapFunc(x, char2id))
  171. df_test[“label_id”] = df_test.label.map(lambda x : -1 if str(x) == str(np.nan) else label2id[x])
  172. if is_validation:
  173. X_test, y_test = prepare(df_test[“char_id”], df_test[“label_id”], seq_max_len)
  174. return X_test, y_test
  175. else:
  176. df_test[“char”] = df_test.char.map(lambda x : -1 if str(x) == str(np.nan) else x)
  177. X_test, _ = prepare(df_test[“char_id”], df_test[“char_id”], seq_max_len)
  178. X_test_str, _ = prepare(df_test[“char”], df_test[“char_id”], seq_max_len, is_padding=False)
  179. print “test size: %d” %(len(X_test))
  180. return X_test, X_test_str
  181. def getTransition(y_train_batch):
  182. transition_batch = []
  183. for m in range(len(y_train_batch)):
  184. y = [5] + list(y_train_batch[m]) + [0]
  185. for t in range(len(y)):
  186. if t + 1 == len(y):
  187. continue
  188. i = y[t]
  189. j = y[t + 1]
  190. if i == 0:
  191. break
  192. transition_batch.append(i * 6 + j)
  193. transition_batch = np.array(transition_batch)
  194. return transition_batch

train.py

  1. import time
  2. import helper
  3. import argparse
  4. import numpy as np
  5. import pandas as pd
  6. import tensorflow as tf
  7. from BILSTM_CRF import BILSTM_CRF
  8. # python train.py train.in model -v validation.in -c char_emb -e 10 -g 2
  9. parser = argparse.ArgumentParser()
  10. parser.add_argument(“train_path”, help=”the path of the train file”)
  11. parser.add_argument(“save_path”, help=”the path of the saved model”)
  12. parser.add_argument(“-v”,”–val_path”, help=”the path of the validation file”, default=None)
  13. parser.add_argument(“-e”,”–epoch”, help=”the number of epoch”, default=100, type=int)
  14. parser.add_argument(“-c”,”–char_emb”, help=”the char embedding file”, default=None)
  15. parser.add_argument(“-g”,”–gpu”, help=”the id of gpu, the default is 0″, default=0, type=int)
  16. args = parser.parse_args()
  17. train_path = args.train_path
  18. save_path = args.save_path
  19. val_path = args.val_path
  20. num_epochs = args.epoch
  21. emb_path = args.char_emb
  22. gpu_config = “/cpu:0”
  23. #gpu_config = “/gpu:”+str(args.gpu)
  24. num_steps = 200 # it must consist with the test
  25. start_time = time.time()
  26. print “preparing train and validation data”
  27. X_train, y_train, X_val, y_val = helper.getTrain(train_path=train_path, val_path=val_path, seq_max_len=num_steps)
  28. char2id, id2char = helper.loadMap(“char2id”)
  29. label2id, id2label = helper.loadMap(“label2id”)
  30. num_chars = len(id2char.keys())
  31. num_classes = len(id2label.keys())
  32. if emb_path != None:
  33. embedding_matrix = helper.getEmbedding(emb_path)
  34. else:
  35. embedding_matrix = None
  36. print “building model”
  37. config = tf.ConfigProto(allow_soft_placement=True)
  38. with tf.Session(config=config) as sess:
  39. with tf.device(gpu_config):
  40. initializer = tf.random_uniform_initializer(-0.1, 0.1)
  41. with tf.variable_scope(“model”, reuse=None, initializer=initializer):
  42. model = BILSTM_CRF(num_chars=num_chars, num_classes=num_classes, num_steps=num_steps, num_epochs=num_epochs, embedding_matrix=embedding_matrix, is_training=True)
  43. print “training model”
  44. tf.initialize_all_variables().run()
  45. model.train(sess, save_path, X_train, y_train, X_val, y_val)
  46. print “final best f1 is: %f” % (model.max_f1)
  47. end_time = time.time()
  48. print “time used %f(hour)” % ((end_time – start_time) / 3600)

test.py

  1. import time
  2. import helper
  3. import argparse
  4. import numpy as np
  5. import pandas as pd
  6. import tensorflow as tf
  7. from BILSTM_CRF import BILSTM_CRF
  8. # python test.py model test.in test.out -c char_emb -g 2
  9. parser = argparse.ArgumentParser()
  10. parser.add_argument(“model_path”, help=”the path of model file”)
  11. parser.add_argument(“test_path”, help=”the path of test file”)
  12. parser.add_argument(“output_path”, help=”the path of output file”)
  13. parser.add_argument(“-c”,”–char_emb”, help=”the char embedding file”, default=None)
  14. parser.add_argument(“-g”,”–gpu”, help=”the id of gpu, the default is 0″, default=0, type=int)
  15. args = parser.parse_args()
  16. model_path = args.model_path
  17. test_path = args.test_path
  18. output_path = args.output_path
  19. gpu_config = “/cpu:0”
  20. emb_path = args.char_emb
  21. num_steps = 200 # it must consist with the train
  22. start_time = time.time()
  23. print “preparing test data”
  24. X_test, X_test_str = helper.getTest(test_path=test_path, seq_max_len=num_steps)
  25. char2id, id2char = helper.loadMap(“char2id”)
  26. label2id, id2label = helper.loadMap(“label2id”)
  27. num_chars = len(id2char.keys())
  28. num_classes = len(id2label.keys())
  29. if emb_path != None:
  30. embedding_matrix = helper.getEmbedding(emb_path)
  31. else:
  32. embedding_matrix = None
  33. print “building model”
  34. config = tf.ConfigProto(allow_soft_placement=True)
  35. with tf.Session(config=config) as sess:
  36. with tf.device(gpu_config):
  37. initializer = tf.random_uniform_initializer(-0.1, 0.1)
  38. with tf.variable_scope(“model”, reuse=None, initializer=initializer):
  39. model = BILSTM_CRF(num_chars=num_chars, num_classes=num_classes, num_steps=num_steps, embedding_matrix=embedding_matrix, is_training=False)
  40. print “loading model parameter”
  41. saver = tf.train.Saver()
  42. saver.restore(sess, model_path)
  43. print “testing”
  44. model.test(sess, X_test, X_test_str, output_path)
  45. end_time = time.time()
  46. print “time used %f(hour)” % ((end_time – start_time) / 3600)

TensorFlow (RNN)深度学习 双向LSTM(BiLSTM)+CRF 实现 sequence labeling 序列标注问题 源码下载

相关预处理的数据请参考github: scofiled’s github/bilstm+crf

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,023
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,513
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,360
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,143
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,774
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,853