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
# Define the model parameters
vocab_size = 10000
max_length = 20
embedding_dim = 100
rnn_units = 128
# Prepare the training data
texts = [
"This is a sample text.",
"Another example sentence.",
"Language modeling is fun!",
# Add more training texts here
]
# Tokenize the texts
tokenizer = Tokenizer(num_words=vocab_size)
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)
padded_sequences = pad_sequences(sequences, maxlen=max_length, padding='post')
# Create the model
model = Sequential([
Embedding(vocab_size, embedding_dim, input_length=max_length),
GRU(rnn_units, return_sequences=True),
GRU(rnn_units),
Dense(vocab_size, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(padded_sequences, tf.keras.utils.to_categorical(padded_sequences[:, 1:], num_classes=vocab_size), epochs=10)
# Generate text using the trained model
seed_text = "This is"
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)
predicted_word_index = tf.argmax(predicted, axis=-1).numpy()[0]
output_word = ""
for word, index in tokenizer.word_index.items():
if index == predicted_word_index:
output_word = word
break
seed_text += " " + output_word
print(seed_text)
Explanation:
We start by defining the model parameters such as vocabulary size, maximum sequence length, embedding dimensions, and the number of RNN units.
We prepare the training data by providing a list of texts. You can add more training texts to improve the model's performance.
We tokenize the texts using the Tokenizer from Keras. It converts the texts into sequences of integer tokens.
We pad the sequences to a fixed length using pad_sequences to ensure consistent input size for the model.
We create the model using the Sequential API from Keras. The model consists of an Embedding layer, two GRU layers, and a Dense output layer with softmax activation.
We compile the model with the Adam optimizer, sparse categorical cross-entropy loss, and accuracy metric.
We train the model using the fit method, passing the padded sequences as input and the corresponding target sequences as labels.
After training, we can generate new text using the trained model. We provide a seed text and specify the number of next words to generate.
We tokenize the seed text, pad it to the desired length, and predict the next word using the model.
We iterate for the specified number of next words, appending each predicted word to the seed text.
Finally, we print the generated text.
Note: This is a basic example to demonstrate the concept of an RNN-based language model using TensorFlow 2. In practice, you would need a larger dataset, more training epochs, and potentially more complex model architectures to achieve better results.