Text Classification
Transformers
Safetensors
ONNX
Swahili
Swahili (macrolanguage)
roberta
swahili
classification
multilabel
africa
nlp
text-embeddings-inference
Run this model with HF Jobs
Run NeboTech/swahili-text-classifier on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/NeboTech/swahili-text-classifier. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/NeboTech/swahili-text-classifier on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use NeboTech/swahili-text-classifier with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use NeboTech/swahili-text-classifier with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="NeboTech/swahili-text-classifier")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForSequenceClassification tokenizer = AutoTokenizer.from_pretrained("NeboTech/swahili-text-classifier") model = AutoModelForSequenceClassification.from_pretrained("NeboTech/swahili-text-classifier", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Create README.md
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276---tags:- swahili- classification- multilabel- roberta- transformers- onnx- africa- nlplicense: apache-2.0language:- sw- swadatasets:- custommetrics:- f1_score- precision- recall- hamming_losspipeline_tag: text-classificationtask_categories:- text-classificationtask_ids:- multi-label-classificationbase_model:- benjamin/roberta-base-wechsel-swahililibrary_name: transformers---
# Swahili Topic Classifier - Multi-label Classification
## Model Details
### Model DescriptionA multi-label text classification model fine-tuned on RoBERTa-base Wechsel Swahili for classifying Swahili text into 8 predefined topics. The model can identify multiple applicable topics for a given text, providing confidence scores for each topic.
- **Developed by**: NeboTech- **Model type**: Transformer-based (RoBERTa)- **Language(s)**: Swahili (Kiswahili)- **License**: Apache 2.0- **Finetuned from**: [RoBERTa-base Wechsel Swahili](https://huggingface.co/roberta-base-wechsel-swahili)- **Model version**: v2.0 (Multi-label Classification)
### Model Architecture- **Base Model**: RoBERTa-base Wechsel Swahili- **Task**: Multi-label Sequence Classification- **Problem Type**: `multi_label_classification`- **Number of Labels**: 8- **Activation Function**: Sigmoid (for multi-label)- **Loss Function**: BCEWithLogitsLoss- **Output Format**: Binary vectors [batch_size, num_labels]
### Model Variants- **v2.0** (Current): Multi-label classification - Returns multiple topics with confidence scores- **v1.0** (Legacy): Single-label classification - Returns single topic (available at `revision="v1.0-single-label"`)
## Intended Use
### Primary Use Cases- **Content Classification**: Categorize Swahili text messages, reports, or documents- **Case Management**: Automatically tag and route cases to appropriate departments- **Content Moderation**: Identify topics requiring attention (e.g., health emergencies, violence)- **Data Analytics**: Analyze trends and patterns in Swahili text data- **Information Routing**: Direct messages to relevant stakeholders based on topics
### Out-of-Scope Uses- **Not suitable for**: Languages other than Swahili- **Not suitable for**: Very short text (< 5 words) or very long text (> 512 tokens)- **Not suitable for**: Real-time critical decision making without human oversight- **Not suitable for**: Medical diagnosis or legal advice
## Training Details
### Training Data- **Dataset**: Custom Swahili text dataset- **Language**: Swahili (Kiswahili)- **Data Collection**: U-Report platform messages and related Swahili text- **Preprocessing**: Text cleaning, normalization, and tokenization- **Data Balance**: Dataset balanced across 8 topics
### Training Procedure- **Training Type**: Fine-tuning from pre-trained RoBERTa-base Wechsel Swahili- **Optimizer**: AdamW- **Learning Rate**: 2e-5- **Batch Size**: Variable (with gradient accumulation)- **Epochs**: 3- **Gradient Accumulation**: 4 steps- **Weight Decay**: 0.01- **Mixed Precision**: Enabled (FP16)- **Early Stopping**: Enabled (patience=2)
### Training Hyperparametersllearning_rate: 2e-5per_device_train_batch_size: 4gradient_accumulation_steps: 4num_train_epochs: 3weight_decay: 0.01warmup_steps: 0max_grad_norm: 1.0fp16: true## Evaluation
### Testing Data, Factors & Metrics- **Evaluation Dataset**: Held-out test set from balanced dataset- **Evaluation Metrics**: - **F1 Score (Micro)**: Aggregated across all labels - **F1 Score (Macro)**: Average per-label F1 - **F1 Score (Samples)**: Average per-sample F1 - **Precision (Micro/Macro)**: Classification precision - **Recall (Micro/Macro)**: Classification recall - **Hamming Loss**: Fraction of incorrectly predicted labels - **Subset Accuracy**: Exact match accuracy
### Results| Metric | Score ||--------|-------|| F1 Score (Micro) | 0.96 || F1 Score (Macro) |0.96 || F1 Score (Samples) |0.96 || Precision (Micro) | 0.96 || Recall (Micro) | 0.96 || Hamming Loss | 0.009054 || Subset Accuracy | 0.962 |
## Model Performance Characteristics
### Strengths- **Multi-label Capability**: Can identify multiple topics in a single text- **Confidence Scores**: Provides probability scores for each topic- **Swahili Language Support**: Specifically fine-tuned for Swahili text- **Efficient Inference**: ONNX format available for fast CPU inference- **Balanced Performance**: Trained on balanced dataset across all topics
### Limitations- **Language Specific**: Only works with Swahili text- **Topic Coverage**: Limited to 8 predefined topics- **Context Dependency**: Performance may vary with text length and context- **Dialect Variations**: May not handle all Swahili dialects equally well- **Threshold Sensitivity**: Requires careful threshold tuning for optimal performance
### Known Biases- **Training Data Bias**: Model reflects biases present in training data- **Geographic Bias**: May perform better on texts from regions in training data- **Topic Imbalance**: Some topics may have better representation in training data- **Cultural Context**: May not capture all cultural nuances in Swahili communication
## How to Get Started with the Model
### Using Transformers (PyTorch)
from transformers import AutoModelForSequenceClassification, AutoTokenizerimport torch
# Load modelmodel = AutoModelForSequenceClassification.from_pretrained( "NeboTech/swahili-text-classifier", problem_type="multi_label_classification" # CRITICAL for multi-label)tokenizer = AutoTokenizer.from_pretrained("NeboTech/swahili-text-classifier")
# Prepare inputtext = "Nataka kujua dalili za COVID-19 na jinsi ya kujilinda"inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=256)
# Get predictionsmodel.eval()with torch.no_grad(): outputs = model(**inputs) logits = outputs.logits # Shape: [1, 8]
# Apply sigmoid for multi-labelprobs = torch.sigmoid(logits)
# Apply thresholdthreshold = 0.5predictions = (probs > threshold).float()
# Get applicable topicsapplicable_topics = torch.where(predictions[0] == 1)[0].tolist()print(f"Applicable topics: {applicable_topics}")print(f"Probabilities: {probs[0].tolist()}")### Using ONNX Runtime
import onnxruntime as ortimport numpy as npfrom transformers import AutoTokenizer
# Load tokenizertokenizer = AutoTokenizer.from_pretrained("NeboTech/swahili-text-classifier")
# Load ONNX modelsession = ort.InferenceSession("swahili_classifier.onnx")
# Prepare inputtext = "Nataka kujua dalili za COVID-19"inputs = tokenizer(text, return_tensors="np", padding="max_length", truncation=True, max_length=256)
# Run inferenceoutputs = session.run( None, { "input_ids": inputs["input_ids"].astype(np.int64), "attention_mask": inputs["attention_mask"].astype(np.int64) })
logits = outputs[0] # Shape: [1, 8]
# Apply sigmoidprobs = 1 / (1 + np.exp(-logits))
# Apply thresholdthreshold = 0.5predictions = (probs > threshold).astype(float)
# Get topicsapplicable_topics = np.where(predictions[0] == 1)[0]print(f"Applicable topics: {applicable_topics}")## Topics (Label Mapping)
| ID | Topic | Description ||----|-------|-------------|| 0 | COVID | COVID-19 related topics, symptoms, prevention || 1 | EDUCATION | Educational content, school-related topics || 2 | HEALTH | General health topics, medical information || 3 | HIV/AIDS | HIV/AIDS related information and support || 4 | MENSTRUAL HYGIENE | Menstrual health and hygiene topics || 5 | NUTRITION | Nutrition, food, and dietary information || 6 | U-REPORT | U-Report platform related content || 7 | VIOLENCE AGAINST CHILDREN | Child protection and violence prevention |
## Ethical Considerations
### Ethical Use- **Human Oversight**: Always include human review for critical decisions- **Privacy**: Respect user privacy when processing text data- **Transparency**: Inform users when automated classification is used- **Fairness**: Monitor for biased outcomes across different user groups
### Potential Risks- **Misclassification**: Incorrect topic assignment could misroute important messages- **False Positives/Negatives**: May miss urgent cases or flag non-urgent content- **Privacy Concerns**: Processing sensitive health and personal information- **Cultural Sensitivity**: May not fully capture cultural context and nuances
### Recommendations- **Regular Monitoring**: Continuously monitor model performance in production- **Human Review**: Implement human review for high-stakes classifications- **Feedback Loop**: Collect and incorporate user feedback for improvements- **Bias Auditing**: Regularly audit for biases and fairness issues- **Threshold Tuning**: Adjust thresholds based on use case requirements
## Citation
@misc{swahili-topic-classifier-multilabel, title={Swahili Topic Classifier - Multi-label Classification}, author={NeboTech}, year={2024}, publisher={Hugging Face}, howpublished={\\url{https://huggingface.co/NeboTech/swahili-text-classifier}}, note={Version 2.0 - Multi-label Classification}}## Additional Information
### Model Files- `config.json`: Model configuration- `pytorch_model.bin` or `model.safetensors`: Model weights- `tokenizer.json`: Tokenizer model- `tokenizer_config.json`: Tokenizer configuration- `vocab.json`, `merges.txt`: Vocabulary files- `swahili_classifier.onnx`: ONNX model (separate repository)
### Version History- **v2.0** (Current): Multi-label classification with sigmoid activation- **v1.0** (Legacy): Single-label classification with softmax activation
### ContactFor questions, issues, or contributionsREADME.mdAdded+276