Since we're analyzing a full sequence, it's legal for us to look into future data. A…
- User
Since we're analyzing a full sequence, it's legal for us to look into future data. A simple way to achieve that is to go both directions at once, making a bidirectional RNN. In Keras you can achieve that both manually (using two LSTMs and Concatenate) and by using keras.layers.Bidirectional. This one works just as TimeDistributed we saw before: you wrap it around a recurrent layer (SimpleRNN now and LSTM/GRU later) and it actually creates two layers under the hood. Your first task is to use such a layer our POS-tagger. #Эта часть в коде остаётся: model = keras.models.Sequential() model.add(L.InputLayer([None],dtype='int32')) model.add(L.Embedding(len(all_words),50)) #Затем добавляем обертку tf.keras.layers.Bidirectional: model.add(L.Bidirectional(L.SimpleRNN(64, return_sequences = True))) #И добавляем слой Dense с активацией softmax: model.add(L.Dense(len(all_tags),activation='softmax'))
model.compile('adam','categorical_crossentropy')
model.fit_generator(generate_batches(train_data),len(train_data)/BATCH_SIZE, callbacks=[EvaluateAccuracy()], epochs=5,)
Task I: Structured loss functions (more bonus points) Since we're tagging the whole sequence at once, we might as well train our network to do so. Remember linear CRF from the lecture? You can also use it as a loss function for your RNN • There's more than one way to do so, but we'd recommend starting with Conditional Random Fields • You can plug CRF as a loss function and still train by backprop. There's even some neat tensorflow implementation for you. • Alternatively, you can condition your model on previous tags (make it autoregressive) and perform beam search over that model.
- Assistant
To use a CRF as a loss function for the POS-tagger model, we can use the
tensorflow-addonspackage, which provides an implementation of CRF layer and loss function.First, we need to install the package:
!pip install tensorflow-addonsThen, we can modify the model and compile it with the CRF loss function:
import tensorflow_addons as tfa model = keras.models.Sequential() model.add(L.InputLayer([None],dtype='int32')) model.add(L.Embedding(len(all_words),50)) model.add(L.Bidirectional(L.SimpleRNN(64, return_sequences=True))) model.add(tfa.layers.CRF(len(all_tags)))We replace the Dense layer with the CRF layer provided by
tensorflow-addons. This layer will handle the CRF decoding and compute the CRF loss during training.Next, we need to compile the model with the
tf_addons.losses.CategoricalCrossentropy()loss function:model.compile('adam', loss=tfa.losses.CategoricalCrossentropy())With this setup, we can fit the model using the new loss function:
model.fit_generator(generate_batches(train_data),len(train_data)/BATCH_SIZE, callbacks=[EvaluateAccuracy()], epochs=5)