CoolFace
Modelpublic

ovinduG/phi3-domain-classifier-98.26

sourceHugging Facemitupdated 9mo agoView on Hugging Face
0likes
Model Card

๐Ÿ† Phi-3 Domain Classification Model - 98.26% Accuracy

Fine-tuned Phi-3-mini-4k-instruct achieving 98.26% accuracy on domain classification across 16 domains.

๐ŸŽฏ Model Performance

  • โ€”Test Accuracy: 98.26%
  • โ€”F1 (Macro): 97.18%
  • โ€”F1 (Weighted): 98.07%
  • โ€”Perfect Domains: 9/16 (100% precision & recall)
  • โ€”Near-Perfect Domains: 15/16 (>95% F1)

๐Ÿ“Š Performance Metrics

MetricValue
Accuracy98.26%
F1 (Macro)97.18%
F1 (Weighted)98.07%
Training Time~3-4 hours
Perfect Domains9/16

๐ŸŽจ Supported Domains

The model classifies text into 16 domains:

  1. 1.coding - Programming and software development (98% F1)
  2. 2.api_generation - API design and implementation (98% F1)
  3. 3.mathematics - Mathematical problems and concepts (99% F1)
  4. 4.data_analysis - Data science and analytics (96% F1)
  5. 5.science - Scientific queries (100% F1) โญ
  6. 6.medicine - Medical and healthcare topics (100% F1) โญ
  7. 7.business - Business and commerce (97% F1)
  8. 8.law - Legal matters (100% F1) โญ
  9. 9.technology - Tech industry and products (100% F1) โญ
  10. 10.literature - Books, writing, poetry (100% F1) โญ
  11. 11.creative_content - Art, music, creative work (100% F1) โญ
  12. 12.education - Learning and teaching (100% F1) โญ
  13. 13.general_knowledge - General information (97% F1)
  14. 14.ambiguous - Unclear or multi-interpretation queries (100% F1) โญ
  15. 15.sensitive - Sensitive topics requiring care (100% F1) โญ
  16. 16.multi_domain - Cross-domain queries (71% F1)

โญ = Perfect classification (100% precision & recall)

๐Ÿ”ง Training Configuration

Model Architecture

  • โ€”Base Model: microsoft/Phi-3-mini-4k-instruct (3.82B parameters)
  • โ€”Fine-tuning Method: LoRA (Low-Rank Adaptation)
  • โ€”LoRA Rank: 32
  • โ€”LoRA Alpha: 64
  • โ€”Target Modules: qkvproj, oproj, gateupproj, down_proj

Training Hyperparameters

  • โ€”Epochs: 25 (proven optimal)
  • โ€”Learning Rate: 2e-4
  • โ€”LR Scheduler: Cosine
  • โ€”Warmup Ratio: 10%
  • โ€”Batch Size: 32 (effective)
  • โ€”Label Smoothing: 0.1
  • โ€”Precision: BF16

Training Strategy

  • โ€”โœ… Clean dataset (no data augmentation)
  • โ€”โœ… Standard cosine schedule
  • โ€”โœ… Best checkpoint loading
  • โ€”โœ… Gradient checkpointing
  • โ€”โœ… Reproducible (seed=42)

๐Ÿš€ Quick Start

Installation

bash
pip install transformers peft torch

Basic Usage

python
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
import torch
import json

# Load model
base_model = AutoModelForCausalLM.from_pretrained(
    "microsoft/Phi-3-mini-4k-instruct",
    torch_dtype=torch.bfloat16,
    device_map="auto",
    trust_remote_code=True
)

model = PeftModel.from_pretrained(
    base_model,
    "ovinduG/phi3-domain-classifier-98.26"
)

tokenizer = AutoTokenizer.from_pretrained(
    "ovinduG/phi3-domain-classifier-98.26",
    trust_remote_code=True
)

# Classification function
def classify_domain(text):
    messages = [
        {
            "role": "system",
            "content": "You are a domain classifier. Respond with JSON."
        },
        {
            "role": "user",
            "content": f"Classify: {text}"
        }
    ]

    inputs = tokenizer.apply_chat_template(
        messages,
        add_generation_prompt=True,
        tokenize=True,
        return_dict=True,
        return_tensors="pt"
    ).to(model.device)

    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            max_new_tokens=50,
            temperature=0.1,
            do_sample=True,
            pad_token_id=tokenizer.pad_token_id
        )

    response = tokenizer.decode(
        outputs[0][inputs["input_ids"].shape[-1]:],
        skip_special_tokens=True
    )

    # Parse JSON response
    try:
        response_clean = response.strip()
        if '```' in response_clean:
            response_clean = response_clean.split('```')[1]
        if response_clean.startswith('json'):
            response_clean = response_clean[4:]
        return json.loads(response_clean.strip())
    except:
        return {"primary_domain": "unknown", "confidence": "low"}

# Example usage
result = classify_domain("Write a Python function to sort a list")
print(result)
# Output: {"primary_domain": "coding", "confidence": "high"}

result = classify_domain("What are the symptoms of diabetes?")
print(result)
# Output: {"primary_domain": "medicine", "confidence": "high"}

result = classify_domain("Explain quantum entanglement")
print(result)
# Output: {"primary_domain": "science", "confidence": "high"}

Batch Classification

python
def classify_batch(texts, batch_size=8):
    # Classify multiple texts efficiently
    results = []
    for i in range(0, len(texts), batch_size):
        batch = texts[i:i+batch_size]
        for text in batch:
            results.append(classify_domain(text))
    return results

# Example
texts = [
    "How to implement OAuth2?",
    "Best practices for diabetes management",
    "Write a sorting algorithm in Python"
]

results = classify_batch(texts)
for text, result in zip(texts, results):
    print(f"{text[:50]:50s} โ†’ {result['primary_domain']}")

๐Ÿ“ˆ Performance Details

Per-Domain Results

DomainPrecisionRecallF1-ScoreSupport
ambiguous1.001.001.0045
api_generation0.961.000.9845
business0.960.980.9744
coding0.951.000.9842
creative_content1.001.001.0045
data_analysis0.931.000.9641
education1.001.001.0045
general_knowledge0.960.980.9745
law1.001.001.0046
literature1.001.001.0045
mathematics0.981.000.9946
medicine1.001.001.0045
multi_domain1.000.550.7122
science1.001.001.0045
sensitive1.001.001.0045
technology1.001.001.0044

Comparison with Baselines

ModelAccuracyNotes
This model (25 epochs)98.26%โœ… Optimal
Original 25 epochs97.97%Good baseline
30 epochs attempt94.64%Overfitted โŒ
50 epochs attempt~85-90%Severe overfitting โŒ

๐ŸŽฏ Use Cases

1. Content Routing

Route user queries to appropriate specialists or systems:

python
query = "How do I treat a sprained ankle?"
domain = classify_domain(query)["primary_domain"]
# โ†’ "medicine" โ†’ Route to medical expert

2. Support Ticket Classification

Automatically categorize support tickets:

python
ticket = "Our API returns 401 errors"
domain = classify_domain(ticket)["primary_domain"]
# โ†’ "api_generation" โ†’ Route to API team

3. Content Moderation

Identify sensitive content requiring review:

python
post = "Discussion about controversial topic"
result = classify_domain(post)
if result["primary_domain"] == "sensitive":
    # Flag for manual review
    pass

4. Search & Discovery

Improve search by understanding query intent:

python
search_query = "best sorting algorithms"
domain = classify_domain(search_query)["primary_domain"]
# โ†’ "coding" โ†’ Show programming results

๐Ÿ” Model Behavior

Strengths

  • โ€”โœ… 9 perfect domains (100% precision & recall)
  • โ€”โœ… High precision across all domains (93-100%)
  • โ€”โœ… Consistent performance on similar queries
  • โ€”โœ… Fast inference with LoRA
  • โ€”โœ… Low memory footprint (~200MB adapters)

Limitations

  • โ€”โš ๏ธ Multi-domain classification is challenging (71% F1)
  • โ€”Queries spanning multiple domains are harder to classify
  • โ€”Model tends to pick a single primary domain
  • โ€”โš ๏ธ Requires exact domain list - cannot handle new domains without retraining
  • โ€”โš ๏ธ English only - trained on English text

Recommendations

  • โ€”For multi-domain queries, consider using ensemble or multi-label classification
  • โ€”Validate outputs in production with confidence thresholds
  • โ€”Monitor edge cases and collect feedback for model improvements

๐Ÿ“ Repository Contents

  • โ€”adapter_config.json - LoRA configuration
  • โ€”adapter_model.safetensors - Fine-tuned LoRA weights
  • โ€”tokenizer files - Tokenizer configuration
  • โ€”test_results.json - Comprehensive evaluation metrics
  • โ€”training_curves.png - Training/validation loss curves
  • โ€”confusion_matrix.png - Per-domain performance visualization
  • โ€”final_dataset_*.csv - Training/validation/test datasets

๐Ÿ”„ Reproducibility

This model can be reproduced using the exact configuration above. Key factors:

  • โ€”Seed: 42 (for reproducibility)
  • โ€”No data augmentation (clean training)
  • โ€”Exact hyperparameters documented
  • โ€”Best checkpoint selection (not last)

๐Ÿ“Š Training History

The model was trained with several attempts to optimize performance:

  1. 1.Original run: 97.97% accuracy (25 epochs)
  2. 2.30 epochs attempt: 94.64% - overfitted due to data augmentation
  3. 3.50 epochs attempt: ~85-90% - severe overfitting
  4. 4.Final reproduction: 98.26% - optimal configuration โœ…

Key insight: 25 epochs is the sweet spot for this task and dataset.

โš–๏ธ License & Citation

License

This model is released under MIT License. The base Phi-3 model has its own license from Microsoft.

Citation

If you use this model, please cite:

bibtex
@model{phi3-domain-classifier-98,
  author = {ovinduG},
  title = {Phi-3 Domain Classification Model - 98.26% Accuracy},
  year = {2024},
  publisher = {Hugging Face},
  howpublished = {\url{https://huggingface.co/ovinduG/phi3-domain-classifier-98.26}}
}

Also cite the original Phi-3 paper:

bibtex
@article{phi3,
  title={Phi-3 Technical Report},
  author={Microsoft},
  year={2024}
}

๐Ÿค Contributing

Found an issue or have suggestions? Please open an issue on the model repository.

๐Ÿ“ž Contact

  • โ€”Author: ovinduG
  • โ€”Repository: https://huggingface.co/ovinduG/phi3-domain-classifier-98.26
  • โ€”Upload Date: 2025-12-16

๐Ÿ™ Acknowledgments

  • โ€”Microsoft for the Phi-3 base model
  • โ€”Hugging Face for the transformers library
  • โ€”PEFT library for LoRA implementation

Model Status: โœ… Production-Ready | Accuracy: 98.26% | Perfect Domains: 9/16