Certainly! Here's an example of how you can create a simple RNN-based Language Model (LLM) 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
# Hyperparameters
vocab_size = 10000
max_length = 100
embedding_dim = 128
rnn_units = 256
batch_size = 32
epochs = 10
# Prepare the dataset
texts = [
"This is a sample text.",
"Another example sentence.",
"Language modeling is fun!",
# Add more text data...
]
# Tokenize the text data
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 RNN 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(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Train the model
model.fit(padded_sequences, padded_sequences, batch_size=batch_size, epochs=epochs)
# Generate text using the trained model
def generate_text(seed_text, num_words):
for _ in range(num_words):
token_list = tokenizer.texts_to_sequences([seed_text])[0]
token_list = pad_sequences([token_list], maxlen=max_length, padding='post')
predicted_probs = model.predict(token_list, verbose=0)
predicted_token = tf.argmax(predicted_probs, axis=-1).numpy()[0]
output_word = ""
for word, index in tokenizer.word_index.items():
if index == predicted_token:
output_word = word
break
seed_text += " " + output_word
return seed_text
# Example usage
seed_text = "The quick brown fox"
num_words = 10
generated_text = generate_text(seed_text, num_words)
print(generated_text)
In this example:
We define the hyperparameters for the model, such as the vocabulary size, maximum sequence length, embedding dimensions, RNN units, batch size, and the number of epochs.
We prepare the dataset by tokenizing the text data using the Tokenizer from Keras. The text data is converted into sequences of token indices, and the sequences are padded to a fixed length.
We create the RNN model using the Sequential API from Keras. The model consists of an Embedding layer, two GRU layers, and a Dense output layer with a softmax activation function.
We compile the model with the sparse categorical cross-entropy loss, Adam optimizer, and accuracy metric.
We train the model using the fit() method, passing the padded sequences as both input and target.
We define a generate_text() function that takes a seed text and the number of words to generate. It uses the trained model to predict the next word based on the current sequence and appends it to the seed text.
Finally, we provide an example usage of the generate_text() function by specifying a seed text and the desired number of words to generate.
Note that this is a simplified example, and you may need to adjust the hyperparameters, model architecture, and dataset based on your specific requirements and the complexity of the language modeling task.