Loading the lesson...
In the print dialog, choose "Save as PDF" as the destination.
Arabic NLP - Lesson 6
Why order matters, sequence problem types, and RNN, GRU, LSTM architectures
RNNs) feed input sequentially through time| Type | Examples |
|---|---|
| One to Many | song generator, text generator |
| Many to One | sentiment analysis, voice verification |
| Many to Many (aligned) | named entity recognition, part-of-speech tagging |
| Many to Many (encoder-decoder) | machine translation, question answering |
RNN cell computes a hidden state h_t from the current input and the previous hidden statea_tInput
xₜ
RNN cell
combines input with previous hidden state
Hidden state
hₜ
Output
aₜ, optional
the product was very good with few problems needs 8 stepsa good product (3 steps) gets padded with PAD tokens to match the longest sequence lengthWord2Vec, GloVe, AraVecLayer 1
builds a representation from the raw input
Layer 2
builds a richer representation on top of layer 1's output
IMDB sentiment classification (binary), from tf.keras.datasets.imdb100 tokens before trainingmodel = tf.keras.models.Sequential([
tf.keras.layers.Embedding(input_dim=VOCAB_SIZE+1, output_dim=100),
tf.keras.layers.SimpleRNN(64),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])5 epochs - a plain SimpleRNN struggles on this taskBidirectional lets the model see both past and future contextmodel_bi = tf.keras.models.Sequential([
tf.keras.layers.Embedding(VOCAB_SIZE, 64),
tf.keras.layers.Bidirectional(tf.keras.layers.SimpleRNN(64)),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])gru_bi = tf.keras.models.Sequential([
tf.keras.layers.Embedding(VOCAB_SIZE, 64),
tf.keras.layers.Bidirectional(tf.keras.layers.GRU(64, return_sequences=True)),
tf.keras.layers.Bidirectional(tf.keras.layers.GRU(64)),
tf.keras.layers.Dense(1, activation='sigmoid')
])GRU swaps in for SimpleRNN inside the same Bidirectional wrapper.LSTM retain information from far earlier in the sequence, solving the vanishing-gradient problemRNN/GRU - just swap in an LSTM celllstm_bi = tf.keras.models.Sequential([
tf.keras.layers.Embedding(VOCAB_SIZE, 64),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])def predict(text, clf, word2idx, padding_size):
padded_text = np.zeros((padding_size))
padded_text[:len(text.split())] = [word2idx.get(w, 0) for w in text.split()]
return clf.predict(tf.expand_dims(padded_text, 0))
predict("the movie was super awesome!", lstm_bi, word2idx, lstm_padding)RNNs process sequences step by step, so, unlike feed-forward networks, word order changes the outputSimpleRNN suffers from vanishing gradients and forgets early context on long sequencesGRU (update gate) and LSTM (update/forget/output gates) fix this, with LSTM adding an explicit long-term memoryMahmoud Abas|Types of sequence problems