import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, SimpleRNN, Dense
text = "This is a sample text for language modeling using RNN."
chars = sorted(set(text))
char_to_index = {char: index for index, char in enumerate(chars)}
index_to_char = {index: char for index, char in enumerate(chars)}
text_indices = [char_to_index[char] for char in text]
seq_length = 20
sequences = []
next_char = []
for i in range(0, len(text_indices) - seq_length):
 sequences.append(text_indices[i : i + seq_length])
 next_char.append(text_indices[i + seq_length])
X = np.array(sequences)
y = np.array(next_char)
17
model = Sequential([Embedding(input_dim=len(chars), output_dim=50, input_length=seq_length),SimpleRNN(100, return_sequences=False),Dense(len(chars), activation="softmax")])
model.compile(loss="sparse_categorical_crossentropy", optimizer="adam")
model.fit(X, y, batch_size=64, epochs=50)
seed_text = "This is a sample te"
generated_text = seed_text
num_chars_to_generate = 100
for _ in range(num_chars_to_generate):
 seed_indices = [char_to_index[char] for char in seed_text]

 if len(seed_indices) < seq_length:
     diff = seq_length - len(seed_indices)
     seed_indices = [0] * diff + seed_indices

 seed_indices = np.array(seed_indices).reshape(1, -1)
 next_index = model.predict(seed_indices).argmax()
 next_char = index_to_char[next_index]
 generated_text += next_char
 seed_text = seed_text[1:] + next_char
print(generated_text)