CRF
对于序列标注问题,通常会在LSTM的输出后接一个CRF层:将LSTM的输出通过线性变换得到维度为[batch_size, max_seq_len, num_tags]的张量,这个张量再作为一元势函数(Unary Potentials)输入到CRF层。
# 将两个LSTM的输出合并
output_fw, output_bw = outputs
output = tf.concat([output_fw, output_bw], axis=-1)
# 变换矩阵,可训练参数
W = tf.get_variable("W", [2 * num_units, num_tags])
# 线性变换
matricized_output = tf.reshape(output, [-1, 2 * num_units])
matricized_unary_scores = tf.matmul(matricized_output , W)
unary_scores = tf.reshape(matricized_unary_scores, [batch_size, max_seq_len, num_tags])
2.1.损失函数
# Loss函数
log_likelihood, transition_params =
tf.contrib.crf.crf_log_likelihood(unary_scores,tags,sequence_lengths)
loss = tf.reduce_mean(-log_likelihood)
其中
tags:维度为[batch_size, max_seq_len]的矩阵,也就是Golden标签,注意这里的标签都是以索引方式表示的。
sequence_lengths:维度为[batch_size]的向量,记录了每个序列的长度。
log_likelihood:维度为[batch_size]的向量,每个元素代表每个给定序列的Log-Likelihood。
transition_params :维度为[num_tags, num_tags]的转移矩阵。注意这里的转移矩阵不像传统的HMM概率转移矩阵那样要求每个元素非负且每一行的和为1,这里的每个元素取值范围是实数(正负都可以)。
2.2.解码
decode_tags, best_score =
tf.contrib.crf.crf_decode(unary_scores,transition_params,sequence_lengths)
其中
decode_tags:维度为[batch_size, max_seq_len]的矩阵,包含最高分的标签序列。
best_score :维度为[batch_size]的向量,包含最高分数。