Character- and word-level Urdu language models in Keras, with LSTM, GRU and SimpleRNN compared on the same data.
You give it a short Urdu seed phrase. It keeps writing, one character or one word at a time.
There are two notebooks:
| Notebook | Predicts | Context window | Models |
|---|---|---|---|
Text-Generation_Char-Level.ipynb |
the next character | 20 characters | LSTM, SimpleRNN, GRU |
Text-Generation_Word-Level.ipynb |
the next word | 5 words | LSTM, SimpleRNN, GRU |
Every model gets the same seed, بس اتنی سی بات, and writes five continuations at temperature 0.7.
- Load the corpus. It's an Urdu text corpus from Kaggle: an
.xlsxfile with one line of text per row, in aText Linescolumn. The word-level notebook uses a smaller version of it (reduced-Urdu-Corpus.xlsx). - Tokenize. The Keras
Tokenizerruns withfilters='', so Urdu punctuation such as۔survives. It splits into characters (char_level=True) or words. - Make training pairs. A window slides over each line. The first n tokens are the input and the next token is the label, one-hot encoded.
- Train. Each model is
Embedding → recurrent layer → Dense(softmax), trained with Adam on categorical cross-entropy. The three recurrent layers are swapped in one at a time. - Generate.
generate_text()predicts a distribution and rescales it by temperature:log(p) / T, then softmax. It samples the next token, appends it, and repeats.
def generate_text(seed_text, next_chars=100, temperature=1.0): for _ in range(next_chars): encoded = tokenizer.texts_to_sequences([seed_text])[-1] encoded = pad_sequences([encoded], maxlen=seq_length, truncating='pre') preds = model.predict(encoded, verbose=0)[0] preds = np.log(preds + 1e-8) / temperature preds = np.exp(preds) / np.sum(np.exp(preds)) next_index = np.random.choice(range(total_chars), p=preds) seed_text += tokenizer.index_word.get(next_index, '') return seed_text
All runs were on a Kaggle Tesla T4. The numbers are copied from the training logs saved in the notebooks. They are training accuracy and loss; the notebooks don't hold out a validation set.
Character level. Each model has a 128-unit embedding and a 128-unit recurrent layer. Each trained for 10 epochs, with 4,486 batches of 128 per epoch.
| Model | Final accuracy | Final loss | Time per epoch |
|---|---|---|---|
| GRU | 0.5304 | 1.6682 | ~22 s |
| LSTM | 0.5115 | 1.7560 | ~24 s |
| SimpleRNN | 0.5008 | 1.7987 | ~15 s |
GRU learned fastest and finished best. SimpleRNN was the quickest per epoch but plateaued first.
Sample continuations of بس اتنی سی بات (40 characters, T = 0.7), copied from the notebook output:
| Model | Output |
|---|---|
| GRU | بس اتنی سی بات کر دیا تو وہ ایک انہی اور ہم کیا جائے ۔ |
| LSTM | بس اتنی سی بات میں یہ انتظامہ کی جواب ہوتی ہے۔ متعلقہ |
| SimpleRNN | بس اتنی سی بات کرنے ہی ایک مقامات کی سرمایہ دیتے ہیں۔ا |
The models produce real Urdu words, correct spacing, sentence endings and plausible word order. The meaning doesn't hold together over a whole sentence, which is what you'd expect from a 20-character window.
Word level. This was a much smaller experiment on the reduced corpus:
| Model | Setup | Final accuracy | Final loss |
|---|---|---|---|
| LSTM | 5-dim embedding, 5 units, 3 epochs | 0.0343 | 6.7479 |
| SimpleRNN | 64-dim, 64 units, 5 epochs | 0.0423 | 6.2137 |
| GRU | 128-dim, 128 units, 10 epochs | 0.0416 | 6.0605 |
With a large vocabulary and little text, the word-level models stay underfit. Their output is grammatical in places and mostly incoherent. That gap is the main finding: on a small Urdu corpus, character-level modelling works far better.
The notebooks were written for Kaggle, which is the easiest place to run them: GPU on, corpus attached as a dataset.
To run locally:
git clone https://github.com/shakaibarsalan/Urdu-Text-Generation.git
cd Urdu-Text-Generation
pip install tensorflow pandas numpy matplotlib openpyxl jupyter
jupyter notebookThen point the pd.read_excel(...) path in cell 1 at your copy of the corpus. Any .xlsx with a Text Lines column works, so you can train on your own Urdu text. A GPU helps: each character-level epoch took 15–25 seconds on a T4.
Things worth changing:
seq_lengthsets the context window.- The embedding size and recurrent units set model capacity.
epochssets training length.temperatureinexample()trades safe text (low values) for more varied text (high values).
Python 3.11 · TensorFlow / Keras · NumPy · pandas · Matplotlib · Jupyter on Kaggle (Tesla T4)
The code is under the MIT License. The Urdu corpus isn't included in this repo and stays under its original terms on Kaggle.
Muhammad Shakaib Arsalan: shakaib.vercel.app · LinkedIn
