BioRTC's 2025 AI Workshop
Complete Resource Guide
Day 2: Training Your Own AI Models
Welcome to Day 2! Yesterday you learned to use existing AI models through APIs and applications. Today, you’ll go deeper and actually train your own AI models from scratch. This is where the real power of AI becomes evident – creating models tailored specifically for your unique problems and data.
Why Train Your Own Models?
The Limitations of General Models
Generic AI models are like general-purpose tools:
- A Swiss Army knife is useful, but a specialized tool is better for specific jobs
- ChatGPT knows general knowledge, but doesn’t understand your specific business context
- Pre-trained models might not perform well on your unique data or requirements
Real-World Scenarios Where You Need Custom Models:
Healthcare: General models don’t understand medical terminology specific to your hospital Legal: Standard AI doesn’t know your country’s specific laws and regulations Manufacturing: Generic models can’t classify defects specific to your production line Customer Service: Off-the-shelf models don’t understand your company’s products and policies
When to Fine-Tune vs. When to Use Pre-Trained Models
Use Pre-Trained Models When:
- Your task is common (general Q&A, basic text analysis)
- You have limited data (less than 1,000 examples)
- You need a quick solution
- Your domain is well-covered by general training data
Fine-Tune Your Own Model When:
- You have domain-specific terminology or context
- You have sufficient labeled data (1,000+ examples)
- You need consistent, predictable performance
- Privacy and data control are important
- You want to optimize for your specific use case
The Business Case for Model Training
- Cost Efficiency: Pay once for training instead of ongoing API costs
- Data Privacy: Your sensitive data never leaves your infrastructure
- Performance: Models trained on your data perform better on your tasks
- Independence: No reliance on external services or rate limits
- Customization: Complete control over model behavior and outputs
Activity 4: BERT Text Classification for Complaint Categorization
Duration: 40 minutes
The Business Problem
Imagine you work for a telecommunications regulatory agency that receives thousands of citizen complaints daily about:
- Broadband Issues: Slow internet, outages, billing problems
- TV and Radio: Signal problems, content issues, accessibility
- Online Safety: Cyberbullying, data breaches, privacy violations
Currently, human staff manually read each complaint and assign it to the correct department. This process:
- Takes hours of manual work daily
- Is prone to human error and inconsistency
- Creates backlogs during busy periods
- Costs significant staff time that could be used for resolution
Your Solution: Train an AI model to automatically categorize complaints, allowing staff to focus on actually solving problems instead of sorting paperwork.
What This Application Does
Input: Raw text complaints from citizens. Visualize the dataset here.
Process:
- Data Preparation: Your labeled training data (complaint text + correct category)
- Model Training: Fine-tune BERT to understand your specific classification task
- Model Evaluation: Test accuracy on held-out data. See example here. Ideally if we feed any complaint from the data provided here, it should assign the appropriate category given here.
- Deployment: Use the trained model to classify new complaints automatically
Output:
- Trained model that understands your specific complaint categories
- Automatic classification of new complaints with high accuracy
- Significant time savings for your organization
Understanding BERT and Fine-Tuning
What is BERT? BERT (Bidirectional Encoder Representations from Transformers) is a foundational language model that:
- Understands context in both directions (left and right of words)
- Was pre-trained on massive amounts of general text
- Provides a strong foundation for specialized tasks
How Fine-Tuning Works:
- Start with Pre-trained BERT: Already understands general English
- Add Classification Layer: Specific to your number of categories
- Train on Your Data: Teach it your specific classification task
- Optimize Performance: Adjust specifically for your domain
Why BERT for Text Classification:
- Contextual Understanding: Knows that “service down” means different things in different contexts
- Transfer Learning: Leverages knowledge from billions of text examples
- Proven Performance: State-of-the-art results on text classification tasks
- Manageable Size: Can be trained and deployed on modest hardware
The Training Process Explained
1. Data Preprocessing:
- Text is tokenized into BERT-compatible format
- Labels are converted to numerical indices
- Data is split into training and validation sets
2. Model Architecture:
- Start with pre-trained BERT-base (110M parameters)
- Add a classification head for 3 categories
- Only the classification layer starts with random weights
3. Training Loop:
- Model processes batches of text and makes predictions
- Compare predictions to true labels (loss calculation)
- Adjust model weights to improve accuracy
- Repeat for multiple epochs
4. Optimization:
- Use AdamW optimizer with learning rate scheduling
- Apply techniques to prevent overfitting
- Monitor validation accuracy to know when to stop
Real-World Applications Beyond Complaints
Customer Service Automation:
- Route support tickets to appropriate departments
- Classify urgency levels automatically
- Identify sentiment and escalation needs
Content Moderation:
- Classify social media posts for policy violations
- Detect spam, harassment, or inappropriate content
- Prioritize human review for edge cases
Document Processing:
- Classify legal documents by type and urgency
- Sort medical records by specialty
- Categorize financial documents for processing
Market Research:
- Classify customer feedback by product area
- Analyze survey responses for themes
- Track brand sentiment across channels
Step-by-Step Implementation
Step 1: Download the Training Application
In your Jupyter notebook, create a new cell and run:
%cd /home
!git clone https://github.com/ictBioRtc/complaints_classification.gitWhat this does: Downloads a complete BERT fine-tuning application with training data, evaluation scripts, and deployment interface.
Step 2: Navigate to the Project
Create another cell and run:
%cd complaints_classificationWhat this does: Changes your working directory to the classification project folder.
Step 3: Install Training Dependencies
Create a new cell and run:
!pip install -r requirements.txtWhat this installs:
- Transformers: Hugging Face library for BERT and other models
- Datasets: Efficient data loading and processing
- Torch: PyTorch deep learning framework
- Scikit-learn: Machine learning utilities for evaluation
- Gradio: Web interface for model interaction
This installation takes 3-4 minutes as it downloads BERT and other dependencies.
Step 4: Set Up Hugging Face Account (Important!)
Why You Need This:
- Access to pre-trained BERT models
- Ability to save and share your trained models
- Integration with the broader ML community
Account Setup:
- Go to https://huggingface.co/
- Click “Sign Up” and create an account
- Verify your email address
- Go to Settings → Access Tokens
- Click “New token”
- Important: Select “Write” permissions (needed for model uploads)
- Copy your token – you’ll need it shortly!
Step 5: Launch the Training Application
Create a new cell and run:
!python app.pyWhat happens:
- The application initializes with a pre-trained BERT model
- Creates a comprehensive training and evaluation interface
- Provides a public URL (like: https://abc123.gradio.live)
- Click the URL to access your ML training platform
Step 6: Understanding the Training Interface
Your application opens with two main tabs:
“Train Model” Tab:
- Dataset configuration and training parameters
- Hugging Face integration for model sharing
- Real-time training progress monitoring
“Classify Complaints” Tab:
- Test your trained model on individual complaints
- Batch processing for multiple complaints
- Model comparison and evaluation tools
Step 7: Configuring Your Training Run
In the “Train Model” tab:
Step 7a: Dataset Configuration
- Dataset Name:
ictbiortc/complaint-categories-dataset - This is a pre-prepared dataset with real complaint examples
- Contains labeled examples for all three categories
Step 7b: Training Parameters Understanding what each parameter does:
- Number of Epochs (Default: 3):
- How many times the model sees the entire dataset
- More epochs = better learning but risk of overfitting
- 3 is optimal for this dataset size
- Batch Size (Default: 8):
- How many examples processed simultaneously
- Larger batches = faster training but more memory
- 8 is safe for most GPU configurations
- Learning Rate (Default: 2e-5):
- How quickly the model adjusts weights
- Too high = unstable training, too low = slow learning
- 2e-5 is proven optimal for BERT fine-tuning
Step 7c: Hugging Face Integration (Optional but Recommended)
- Expand “Hugging Face Hub Settings”
- Enter your Hugging Face token
- Check “Push Model to Hub during training”
- Enter your username and choose a model name (e.g., “bert-complaint-classifier”)
Why Save to Hugging Face:
- Preserves your work beyond the workshop
- Allows sharing with colleagues
- Enables easy deployment later
- Creates a portfolio of your ML projects
Step 8: Start Training Your Model
Click “Start Training” and watch the magic happen:
What you’ll see in real-time:
- Model initialization messages
- Dataset loading and preprocessing
- Training progress for each epoch
- Loss values decreasing (model getting better)
- Validation accuracy improvements
- Model saving confirmations
Training Timeline:
- Minutes 0-2: Model and data loading
- Minutes 2-8: Actual training (3 epochs)
- Minutes 8-10: Model saving and evaluation
- Total Time: ~10 minutes on GPU
Understanding the Training Output:
Epoch 1/3: Loss: 0.95 → Accuracy: 65%
Epoch 2/3: Loss: 0.45 → Accuracy: 85%
Epoch 3/3: Loss: 0.25 → Accuracy: 92%What this means:
- Loss decreasing: Model making fewer mistakes
- Accuracy increasing: Getting more predictions correct
- 92% accuracy: Very good performance for this task
Step 9: Testing Your Trained Model
Switch to the “Classify Complaints” tab:
Step 9a: Single Complaint Testing
- Try these example complaints:
Broadband Example: “My internet has been down for three days. I work from home and this is affecting my business. The technician was supposed to come yesterday but nobody showed up.”
TV-Radio Example: “The subtitles on Channel 5 are not working properly. As a deaf viewer, this makes it impossible for me to follow the programs. This is a serious accessibility issue.”
Online-Safety Example: “Someone has been sending threatening messages to my daughter through a social media platform. When we reported it, nothing was done. This cyberbullying needs to stop.”
- Click “Classify” for each example
- Observe how accurately your model categorizes each complaint
Step 9b: Batch Processing
- Upload the provided
test_complaints.csvfile - Click “Classify All”
- Compare predictions with the ground truth in
test_categories.csv - Calculate your model’s overall accuracy
Understanding What Happened Behind the Scenes
The Complete Training Pipeline:
- Data Loading and Preprocessing:
- Raw text complaints loaded from Hugging Face dataset
- Text tokenized using BERT’s specific tokenizer
- Labels converted to numerical format (0, 1, 2)
- Data split into training (80%) and validation (20%) sets
- Model Architecture Setup:
- Pre-trained BERT-base-uncased loaded (110M parameters)
- Classification head added for 3 output categories
- Only classification weights initialized randomly
- Rest of BERT keeps pre-trained knowledge
- Training Process:
- Model processes text in batches of 8 complaints
- Makes predictions for each complaint’s category
- Compares predictions to true labels using cross-entropy loss
- Backpropagation updates model weights to reduce errors
- Process repeats for 3 complete passes through data
- Optimization Techniques:
- AdamW optimizer with weight decay for stable training
- Learning rate scheduling for optimal convergence
- Gradient clipping to prevent exploding gradients
- Early stopping to prevent overfitting
- Model Evaluation:
- Validation set used to monitor generalization
- Accuracy, precision, and recall calculated
- Best model checkpoint saved for deployment
- Final model ready for production use
Advanced Training Concepts
Transfer Learning in Action: Your model started with BERT’s understanding of English and learned your specific task. This is why training was fast and effective – you didn’t need to teach it language from scratch.
Avoiding Overfitting: The model could memorize training examples but fail on new data. Techniques used:
- Validation set monitoring
- Weight decay regularization
- Optimal learning rate selection
- Limited training epochs
Data Quality Impact: Your model’s performance depends heavily on training data quality:
- Consistent labeling: Same criteria applied to all examples
- Balanced categories: Roughly equal examples per category
- Representative samples: Training data reflects real-world distribution
Customization for Your Own Use Cases
Adapting for Different Domains:
Legal Document Classification:
- Replace complaint categories with document types
- Train on legal briefs, contracts, motions
- Add domain-specific preprocessing
Medical Report Classification:
- Categories: Radiology, Pathology, Clinical Notes
- Include medical terminology handling
- Consider patient privacy requirements
Product Review Analysis:
- Categories: Electronics, Clothing, Books, etc.
- Include sentiment analysis alongside classification
- Handle star ratings and review text
Email Routing System:
- Categories: Sales, Support, Technical, Billing
- Include priority level classification
- Handle different email formats and attachments
Model Performance and Business Impact
Measuring Success:
- Accuracy: Percentage of correct classifications
- Precision: Of predicted positives, how many were actually correct
- Recall: Of actual positives, how many were found
- F1-Score: Harmonic mean of precision and recall
Business Metrics:
- Time Saved: Hours of manual classification eliminated
- Consistency: Reduced human error and bias
- Scalability: Handle increasing complaint volumes
- Cost Reduction: Lower operational overhead
ROI Calculation Example:
- Manual processing: 2 minutes per complaint × 1000 complaints/day = 33 hours/day
- Automated processing: 0.1 seconds per complaint × 1000 complaints/day = 1.7 minutes/day
- Time savings: 99.9% + improved accuracy and consistency
Troubleshooting Common Training Issues
“CUDA out of memory”
- Reduce batch size from 8 to 4 or 2
- Use gradient accumulation to maintain effective batch size
- Clear GPU memory between runs
“Loss not decreasing”
- Check data quality and labeling consistency
- Adjust learning rate (try 1e-5 or 5e-5)
- Ensure balanced dataset across categories
“Model overfitting”
- Reduce number of epochs
- Add more training data
- Increase regularization (weight decay)
“Poor accuracy on test data”
- Check if test data matches training distribution
- Verify label quality in training set
- Consider data augmentation techniques
“Training taking too long”
- Use smaller model (DistilBERT instead of BERT)
- Reduce sequence length if appropriate
- Use gradient checkpointing to trade memory for speed
Deployment Considerations
Model Serving Options:
- Local Deployment: Run on your own servers
- Cloud Deployment: AWS, Azure, Google Cloud
- Edge Deployment: Mobile or IoT devices
- API Services: Hugging Face Inference API
Production Monitoring:
- Track prediction accuracy over time
- Monitor for data drift (changes in complaint patterns)
- Set up alerts for unusual classification patterns
- Regular retraining with new data
Scaling Considerations:
- Batch processing for high-volume scenarios
- Load balancing for multiple concurrent users
- Caching for frequently classified text patterns
- Database integration for audit trails
Key Takeaways
- Transfer Learning Power: Started with general language understanding, specialized for your task
- Data Quality Importance: Good training data is crucial for model performance
- Training Efficiency: Fine-tuning is much faster than training from scratch
- Real Business Impact: Automated classification saves significant time and improves consistency
- Customization Potential: Same approach works for many different classification tasks
- Production Readiness: Your model is ready for real-world deployment
What You’ve Accomplished:
- Trained a state-of-the-art text classification model
- Learned the complete machine learning pipeline from data to deployment
- Created a solution that solves real business problems
- Gained hands-on experience with modern NLP techniques
- Built a foundation for tackling similar problems in your domain
Business Skills Developed:
- Understanding when to build vs. buy AI solutions
- Evaluating AI project feasibility and ROI
- Managing AI training projects and timelines
- Interpreting model performance metrics
Next: We’ll explore computer vision model training with a laboratory beaker volume recognition system – showing how the same principles apply to image-based AI tasks!
