Views
No views yet
| Pred Swahili | Pred Dholuo | Pred Kalenjin | |
|---|---|---|---|
| True Swahili | 8,356 | 210 | 90 |
| True Dholuo | 135 | 11,368 | 127 |
| True Kalenjin | 60 | 137 | 15,637 |
numpy and huggingface_hub.1import numpy as np
2import pickle
3from collections import Counter
4from huggingface_hub import hf_hub_download
5
6# 1. Download model weights and mapping from Hugging Face
7model_path = hf_hub_download(repo_id="amidblue/ke-lang-id", filename="lang_id_model.pkl")
8
9with open(model_path, "rb") as f:
10 model_data = pickle.load(f)
11
12def softmax(z):
13 return np.exp(z - np.max(z)) / np.exp(z - np.max(z)).sum()
14
15def extract_ngrams(text, n):
16 return ["".join(s) for s in (zip(*[text[i:] for i in range(n)]))]
17
18def predict(text):
19 # Vectorize text based on the trained feature map
20 ngrams = extract_ngrams(text, model_data["ngram_length"])
21 counts = Counter(ngrams)
22
23 x = np.zeros(len(model_data["feature_map"]))
24 for ngram, count in counts.items():
25 if ngram in model_data["feature_map"]:
26 x[model_data["feature_map"][ngram]] = count
27
28 # Add bias term (1.0) at the start of the vector
29 x_aug = np.insert(x, 0, 1)
30
31 # Compute scores and apply softmax
32 z = model_data["W"].dot(x_aug)
33 probs = softmax(z)
34
35 return model_data["lang_list"][np.argmax(probs)]
36
37# Example Usage
38text = "Kuna tashwishi ambao umetokea kulingana na mazungumzo ya wanaharakati"
39print(f"Predicted Language: {predict(text)}")
40