Views
No views yet
| Metric | Score | Rank |
|---|---|---|
| Test Perplexity | 88.31 | 🟢 Good |
| BLEU Score | 0.2900 | 🟢 Competitive |
| Top-1 Accuracy | 0.2595 (25.95%) | 🟢 Strong |
| Top-5 Accuracy | 0.4857 (48.57%) | 🟢 Excellent |
| Top-10 Accuracy | 0.5677 (56.77%) | 🟢 Very Good |
| Mean Reciprocal Rank | 0.3643 | 🟢 Strong |
pip install torch huggingface_hub1import torch
2import pickle
3from huggingface_hub import hf_hub_download
4
5# Download model files
6model_path = hf_hub_download(
7 repo_id="cosmicshubham/next-word-predictor-lstm",
8 filename="best_model.pth"
9)
10tokenizer_path = hf_hub_download(
11 repo_id="cosmicshubham/next-word-predictor-lstm",
12 filename="tokenizer.pkl"
13)
14
15# Load tokenizer
16with open(tokenizer_path, 'rb') as f:
17 tokenizer = pickle.load(f)
18
19# Define model architecture
20import torch.nn as nn
21
22class NextWordLSTM(nn.Module):
23 def __init__(self, vocab_size, embedding_dim=256, hidden_dim=512,
24 num_layers=2, dropout=0.5):
25 super(NextWordLSTM, self).__init__()
26 self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=0)
27 self.embedding_dropout = nn.Dropout(0.2)
28 self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers,
29 batch_first=True,
30 dropout=dropout if num_layers > 1 else 0)
31 self.dropout = nn.Dropout(dropout)
32 self.fc = nn.Linear(hidden_dim, vocab_size)
33
34 def forward(self, x):
35 embedded = self.embedding(x)
36 embedded = self.embedding_dropout(embedded)
37 lstm_out, _ = self.lstm(embedded)
38 last_output = lstm_out[:, -1, :]
39 dropped = self.dropout(last_output)
40 output = self.fc(dropped)
41 return output
42
43# Load model
44device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
45model = NextWordLSTM(vocab_size=len(tokenizer.word2idx))
46
47checkpoint = torch.load(model_path, map_location=device, weights_only=False)
48model.load_state_dict(checkpoint['model_state_dict'])
49model.to(device)
50model.eval()
51
52# Prediction function
53def predict_next_word(text, top_k=5):
54 SEQ_LENGTH = 20
55 tokens = tokenizer.encode(text)
56
57 if len(tokens) < SEQ_LENGTH:
58 tokens = [0] * (SEQ_LENGTH - len(tokens)) + tokens
59 else:
60 tokens = tokens[-SEQ_LENGTH:]
61
62 input_tensor = torch.tensor([tokens], dtype=torch.long).to(device)
63
64 with torch.no_grad():
65 output = model(input_tensor)
66 probs = torch.softmax(output, dim=1)
67 top_probs, top_indices = probs.topk(top_k * 3, dim=1)
68
69 predictions = []
70 for prob, idx in zip(top_probs[0], top_indices[0]):
71 word = tokenizer.idx2word.get(idx.item(), '<UNK>')
72 # Filter special tokens
73 if word in ['<PAD>', '<UNK>', '<EOS>', '.', ',', '!', '?']:
74 continue
75 predictions.append((word, prob.item()))
76 if len(predictions) >= top_k:
77 break
78
79 return predictions
80
81# Example usage
82text = "I am going to the"
83predictions = predict_next_word(text, top_k=5)
84
85print(f"Input: '{text}'\nPredictions:")
86for i, (word, prob) in enumerate(predictions, 1):
87 print(f" {i}. {word:.<20} {prob*100:5.2f}%")Input: 'I am going to the'
Predictions:
1. right............... 0.93%
2. city................ 0.85%
3. north............... 0.74%
4. end................. 0.71%
5. new................. 0.70%NextWordLSTM(
(embedding): Embedding(10000, 256, padding_idx=0)
(embedding_dropout): Dropout(p=0.2)
(lstm): LSTM(256, 512, num_layers=2, batch_first=True, dropout=0.5)
(dropout): Dropout(p=0.5)
(fc): Linear(in_features=512, out_features=10000)
)
Total Parameters: ~13 Million<UNK>best_model.pth - Model checkpoint with best validation performancetokenizer.pkl - Vocabulary and tokenization mappingsevaluation_metrics.json - Complete training metrics and historyREADME.md - This documentation| Model | Test PPL | Top-1 Acc | Notes |
|---|---|---|---|
| Random Baseline | ~10000 | 0.01% | Random guessing |
| N-gram (5-gram) | ~200 | 15% | Traditional approach |
| This Model | 88.31 | 25.95% | LSTM-based |
| GPT-2 Small | ~35 | 45% | Much larger (117M params) |
1@misc{next-word-predictor-lstm-2026,
2 author = {Shubham Kumar (cosmicshubham)},
3 title = {Next Word Predictor: LSTM-based Language Model},
4 year = {2025},
5 month = {January},
6 publisher = {Hugging Face},
7 howpublished = {\url{https://huggingface.co/cosmicshubham/next-word-predictor-lstm}},
8 note = {Trained on WikiText-2 dataset}
9}