TensorFlow-Bi-LSTM+CRFによるシーケンス表示(コードの概要)

2931 ワード

Bi-LSTMは、TensorFlowを使用してBi-LSTMを構築する場合、次のコードがよく使用されます.
cell_fw = tf.contrib.rnn.LSTMCell(num_units=100)
cell_bw = tf.contrib.rnn.LSTMCell(num_units=100)

(outputs, output_states) = tf.nn.bidirectional_dynamic_rnn(cell_fw, cell_bw, inputs, 
sequence_length=300)

まず次は私が描いたBi-LSTMの概略図です.
実はLSTMは、一列のベクトルを入力し、一列のベクトルを出力するのが簡単です.構築時に2つのスーパーパラメータを設定するだけ:num_unitsとsequence_length.
LSTMCell
tf.contrib.rnn.LSTMCell(
    num_units,
    use_peepholes=False,
    cell_clip=None,
    initializer=None,
    num_proj=None,
    proj_clip=None,
    num_unit_shards=None,
    num_proj_shards=None,
    forget_bias=1.0,
    state_is_tuple=True,
    activation=None,
    reuse=None
)

上のLSTM Cellは1つのスーパーパラメータだけを設定する必要がありますnum_units、すなわち出力ベクトルの次元.
bidirectional_dynamic_rnn()
(outputs, output_states) = tf.nn.bidirectional_dynamic_rnn(
    cell_fw,
    cell_bw,
    inputs,
    sequence_length=None,
    initial_state_fw=None,
    initial_state_bw=None,
    dtype=None,
    parallel_iterations=None,
    swap_memory=False,
    time_major=False,
    scope=None
)

この関数で唯一設定する必要があるスーパーパラメータはシーケンス長sequence_です.length.
入力:  inputsのshapeは、通常、[batch_size,sequence_length,dim_embedding]である.
出力:  outputは(output_fw,output_bw)メタグループ、output_fwとoutput_bwのshapeはすべて[batch_size,sequence_length,num_units]
output_statesは(output_state_fw,output_state_bw)メタグループであり、それぞれ順方向と後方向の最後のセルのOutput,output_state_fwとoutput_state_bwのタイプはいずれもLSTMStateTupleであり、このクラスには2つの属性cとhがあり、それぞれMemory CellとHidden Stateを表し、以下の図に示す. 
CRFはシーケンス寸法の問題に対して、通常LSTMの出力の後に1つのCRF層をつなぐ:LSTMの出力を線形変換によって次元が[batch_size,max_seq_len,num_tags]のテンソルを得て、このテンソルは更に1元ポテンシャル関数(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])


# 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であることが要求されず、ここでの各要素の値範囲は実数である(正負であってもよい).
デコード
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]のベクトルで、最高スコアが含まれます.