Text Classification: Categorizing Text with Machine Learning
Learn how to classify text documents into categories using bag-of-words, TF-IDF, and ML models, with a complete workflow from data preparation to evaluation.
Text Classification: Categorizing Text with Machine Learning
Text classification assigns a category label to a piece of text. It is one of the most common NLP tasks, used for spam detection, customer support routing, news categorization, language detection, and more.
---
Real-World Examples
| Task | Input | Output Categories |
|---|---|---|
| Spam detection | Email content | Spam / Not Spam |
| Support ticket routing | Customer message | Billing / Technical / General |
| News categorization | Article text | Sports / Politics / Technology / Business |
| Language detection | Any text | English / Spanish / French / ... |
| Intent detection | Chatbot message | Order status / Return / Complaint / Question |
Text Classification Workflow
---1. Collect labeled data (text + category) ↓↓
- Preprocess text (clean, tokenize, stem/lemmatize)
↓
- Extract features (Bag of Words, TF-IDF)
↓
- Split into train/test sets
↓
- Train a classifier
↓
- Evaluate performance
Predict new text
Step 1: Prepare Labeled Data
You need a dataset with two columns:
- Text: The raw text content
- Label: The category (e.g., "spam", "not spam")
| Requirement | Minimum | Recommended |
|---|---|---|
| Samples per class | 50+ | 200-500+ |
| Number of classes | 2+ | Keep reasonable (2-20) |
| Label quality | Consistent | Reviewed by humans |
---
Step 2: Preprocess Text
Apply the standard preprocessing pipeline:
- Lowercase
- Remove punctuation and special characters
- Tokenize
- Remove stop words
- Stem or lemmatize
---
Step 3: Feature Extraction
ML models need numbers, not text. Feature extraction converts text into numeric vectors.
Bag of Words (BoW)
Count how many times each word appears in each document.
| Document | "data" | "science" | "machine" | "learning" |
|---|---|---|---|---|
| "data science" | 1 | 1 | 0 | 0 |
| "machine learning" | 0 | 0 | 1 | 1 |
| "data science and machine learning" | 1 | 1 | 1 | 1 |
| Pros | Cons |
|---|---|
| Simple and fast | Ignores word order |
| Works well for many tasks | Large vocabulary = many features |
| Easy to understand | Does not capture word importance |
TF-IDF (Term Frequency - Inverse Document Frequency)
Weights words by how important they are: common words get lower weight, rare (but present) words get higher weight.
- TF: How often a word appears in this document
- IDF: How rare the word is across all documents
- TF-IDF: TF × IDF
| Pros | Cons |
|---|---|
| Downweights common words | Still ignores word order |
| Highlights distinctive words | Larger feature vectors |
| Generally better than raw BoW | Does not capture semantics |
Word Embeddings (Advanced)
Represent words as dense vectors that capture meaning. Similar words have similar vectors.
| Method | Dimensionality | Captures Meaning? |
|---|---|---|
| BoW / TF-IDF | High (vocabulary size) | No |
| Word2Vec / GloVe | Low (50-300) | Yes |
| Sentence embeddings | Low (384-768) | Yes (full sentence) |
Step 4: Choose a Classifier
| Algorithm | Speed | Accuracy | Best For |
|---|---|---|---|
| Naive Bayes | Very fast | Good for text | Quick baseline, spam detection |
| Logistic Regression | Fast | Good | Binary and multi-class text |
| SVM | Medium | Very good | High-dimensional text features |
| Random Forest | Medium | Good | General purpose |
| XGBoost | Medium | Very good | When accuracy matters |
| Neural Network | Slow | Best (with enough data) | Large datasets, complex tasks |
Naive Bayes — The Text Classification Workhorse
Naive Bayes works especially well for text because:
- It handles high-dimensional data (many words) efficiently
- It performs well even with limited training data
- It is very fast to train and predict
Step 5: Train and Evaluate
Using the Platform
- Go to NLP → Classification
- Select your dataset
- Choose the text column and label column
- Configure preprocessing (auto or manual)
- Select a classifier
- Set train/test split (e.g., 80/20)
- Click Train
Key Metrics for Text Classification
| Metric | When to Focus On It |
|---|---|
| Accuracy | Balanced classes |
| F1 Score | Imbalanced classes |
| Precision | False positives are costly |
| Recall | Missing a class is costly |
| Confusion Matrix | See which classes are confused |
Step 6: Improve Performance
| Strategy | How It Helps |
|---|---|
| More training data | Better generalization |
| Better preprocessing | Cleaner features |
| TF-IDF instead of BoW | Better word weighting |
| Bigrams / trigrams | Captures phrases like "not good" |
| Remove noisy features | Reduce overfitting |
| Try different algorithms | Find the best fit |
| Hyperparameter tuning | Optimize model settings |
| Handle class imbalance | SMOTE, class weights |
Multi-Label Classification
Sometimes a document belongs to multiple categories (e.g., a news article about "Technology" AND "Business").
| Type | Each document gets... | Example |
|---|---|---|
| Multi-class | Exactly one label | Spam OR Not Spam |
| Multi-label | One or more labels | Technology AND Business |
- One-vs-Rest (train a binary classifier per label)
- Multi-label specific algorithms
Common Pitfalls
| Pitfall | Problem | Fix |
|---|---|---|
| Not preprocessing text | Noisy features, poor accuracy | Always clean text first |
| Too few training samples | Model cannot learn patterns | Get more labeled data, use data augmentation |
| Ignoring class imbalance | Model predicts majority class | Use class weights, oversample minority |
| Using accuracy on imbalanced data | Misleading metric | Use F1, precision, recall instead |
| Overfitting on small datasets | Perfect train accuracy, poor test | Use cross-validation, regularization |
| Ignoring word order | "not good" and "good" treated the same | Use bigrams, or sentence embeddings |
Quick Reference
| Step | Options |
|---|---|
| Preprocessing | Lowercase, tokenize, remove stop words, stem/lemmatize |
| Feature extraction | Bag of Words, TF-IDF, word embeddings |
| Algorithms | Naive Bayes, Logistic Regression, SVM, XGBoost |
| Evaluation | Accuracy, F1, Precision, Recall, Confusion Matrix |
| Improvement | More data, better features, tuning, class balance |
What's Next?
- [Sentiment Analysis Guide](sentiment-analysis-guide) — A special case of text classification
- [Topic Modeling Guide](topic-modeling-guide) — Discover topics without labels
- [Text Preprocessing Guide](text-preprocessing-deep-dive) — Clean text for analysis
- [Model Evaluation Metrics](model-evaluation-metrics) — All evaluation metrics explained
Related Articles
Natural Language Processing (NLP) Overview
A beginner-friendly guide to NLP: text preprocessing, BOW and TF-IDF, word clouds, text classification, sentiment analysis, and topic modeling.
Text Preprocessing: Tokenization, Stop Words, Stemming, and Lemmatization
Learn the essential text preprocessing steps — tokenization, lowercasing, stop word removal, stemming, lemmatization, and regex cleaning — that prepare raw text for NLP analysis.
Sentiment Analysis: Detecting Opinions and Emotions in Text
Learn how to detect positive, negative, and neutral sentiment in text using lexicon-based and machine learning approaches, with practical tips for accurate results.
Model Evaluation Metrics: Accuracy, Precision, Recall, F1, AUC, RMSE, and More
Understand all major ML evaluation metrics for classification and regression, learn when to use each one, and avoid common metric selection mistakes.
Was this helpful?