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"
c= sorted ( set ( text) )
char_to_index= { char:index for index, char in enumerate ( c) }
index_to_char= { index:char for index, char in enumerate ( c) }
t_indices= [ char_to_index[ char] for char in text]
seq_len, seq, n_char= 20 , [ ] , [ ]
for i in range ( 0 , len ( t_indices) -seq_len) :
seq.append ( t_indices[ i:i+seq_len] )
n_char.append ( t_indices[ i+seq_len] )
X, y= np.array ( seq) , np.array ( n_char)
model= Sequential( [ Embedding( input_dim= len ( c) , output_dim= 50 , input_length= seq_len) , SimpleRNN( 100 , return_sequences= False ) , Dense( len ( c) , activation= "softmax" ) ] )
model.compile ( loss= "sparse_categorical_crossentropy" , optimizer= "adam" )
model.fit ( X, y, batch_size= 64 , epochs= 20 )
s_text= "This is a sample txt"
g_text= s_text
num_chars_to_generate= 100
for _ in range ( num_chars_to_generate) :
s_indices= [ char_to_index[ char] for char in s_text]
if len ( s_indices) < seq_len:
diff= seq_len-len ( s_indices)
s_indices= [ 0 ] *diff+s_indices
s_indices= np.array ( s_indices) .reshape ( 1 , -1 )
n_index= model.predict ( s_indices) .argmax ( )
n_char= index_to_char[ n_index]
g_text+= n_char
s_text= s_text[ 1 :] +n_char
print ( g_text)
aW1wb3J0IG51bXB5IGFzIG5wCmltcG9ydCB0ZW5zb3JmbG93IGFzIHRmCmZyb20gdGVuc29yZmxvdy5rZXJhcy5tb2RlbHMgaW1wb3J0IFNlcXVlbnRpYWwKZnJvbSB0ZW5zb3JmbG93LmtlcmFzLmxheWVycyBpbXBvcnQgRW1iZWRkaW5nLFNpbXBsZVJOTixEZW5zZQp0ZXh0PSJUaGlzIGlzIGEgc2FtcGxlIHRleHQiCmM9c29ydGVkKHNldCh0ZXh0KSkKY2hhcl90b19pbmRleD17Y2hhcjppbmRleCBmb3IgaW5kZXgsY2hhciBpbiBlbnVtZXJhdGUoYyl9CmluZGV4X3RvX2NoYXI9e2lu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