Certainly! Here's an example of how you can create a simple RNN-based language model using TensorFlow 2:
python
import tensorflow as tf
from tensorflow.keras.layers import Embedding, GRU, Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
# Sample text data
text_data = [
"The quick brown fox jumps over the lazy dog.",
"The lazy dog sleeps all day.",
"The quick brown fox is very quick.",
"The dog is lazy but the fox is quick."
]
# Tokenize the text data
tokenizer = Tokenizer()
tokenizer.fit_on_texts(text_data)
vocab_size = len(tokenizer.word_index) + 1
# Convert text to sequences
sequences = tokenizer.texts_to_sequences(text_data)
# Prepare input and output sequences
max_length = max(len(seq) for seq in sequences)
padded_sequences = pad_sequences(sequences, maxlen=max_length, padding='pre')
# Create input and output sequences
input_sequences = padded_sequences[:, :-1]
output_sequences = padded_sequences[:, 1:]
# Define the model architecture
model = Sequential([
Embedding(vocab_size, 100, input_length=max_length-1),
GRU(128),
Dense(vocab_size, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
# Train the model
model.fit(input_sequences, output_sequences, epochs=50)
# Generate text
seed_text = "The quick"
next_words = 5
for _ in range(next_words):
token_list = tokenizer.texts_to_sequences([seed_text])[0]
token_list = pad_sequences([token_list], maxlen=max_length-1, padding='pre')
predicted = model.predict(token_list, verbose=0)
output_word = ""
for word, index in tokenizer.word_index.items():
if index == tf.argmax(predicted[0]).numpy():
output_word = word
break
seed_text += " " + output_word
print(seed_text)
In this example:
We start with a sample text dataset (text_data) containing a few sentences.
We tokenize the text data using the Tokenizer from Keras. This converts the text into sequences of integers representing the words.
We prepare the input and output sequences by padding the sequences to a fixed length (max_length) using pad_sequences. The input sequences are the original sequences without the last word, and the output sequences are the original sequences without the first word.
We define the model architecture using the Sequential model from Keras. It consists of an Embedding layer to convert the input sequences into dense vectors, a GRU layer for processing the sequences, and a Dense layer with softmax activation to predict the next word.
We compile the model with the Adam optimizer and sparse categorical cross-entropy loss.
We train the model on the input and output sequences for a specified number of epochs.
To generate text, we start with a seed text (seed_text) and generate the next words iteratively. We convert the seed text to a sequence, pad it, and predict the next word using the trained model. We append the predicted word to the seed text and repeat the process for the desired number of words.
Finally, we print the generated text.
Note that this is a simple example to demonstrate the basic concept of an RNN-based language model. In practice, you would typically use a larger dataset, more advanced architectures (e.g., LSTM, Transformer), and various techniques like teacher forcing and beam search for better results.