Text classification
Text Classification (Text Classification) is one of the most fundamental and important tasks in Natural Language Processing (NLP). Its goal is to automatically assign a given text document to one or more predefined categories.
Basic concepts
Text classification is like a librarian in a library, who needs to categorize books and place them on the correct shelves according to their content. In computing, we need to teach machines how to understand text content and make correct classification decisions.
Application scenarios
Text classification has wide applications in modern society:
- Sentiment analysis: Determine whether a review is positive or negative
- Spam Filtering: Distinguish normal emails from spam
- News Classification: Categorize news into sections such as sports, finance, and technology
- Intent recognition: Understand the real intent behind user queries
- Medical Diagnosis: Classify disease types based on symptom descriptions
Basic Process of Text Classification
A complete text classification system usually includes the following steps:

1. Text Preprocessing
Text preprocessing converts raw text into a form suitable for machine learning models:
Example
import
re
import
nltk
from
nltk.
corpus
import
stopwords
from
nltk.
stem
import
PorterStemmer
def
preprocess_text
(
text
)
:
Convert to lowercase
text
=
text.
lower
(
)
Remove special characters and numbers
text
=
re
.
sub
(
r
'[^a-zA-Z\s]'
,
''
,
text
)
Tokenization
words
=
text.
split
(
)
Remove stop words
stop_words
=
set
(
stopwords.
words
(
'english'
)
)
words
=
[
word
for
word
in
words
if
word
not
in
stop_words
]
Stemming
stemmer
=
PorterStemmer
(
)
words
=
[
stemmer.
stem
(
word
)
for
word
in
words
]
return
' '
.
join
(
words
)
2. Feature Extraction
Convert text into numerical feature representations; common methods include:
| Method | Description | Advantages | Disadvantages |
|---|---|---|---|
| Bag-of-Words model (BoW) | Count word frequencies | Simple and intuitive | Ignores word order and semantics |
| TF-IDF | Considers word importance | More precise than BoW | Still ignores context |
| Word2Vec | Word Vector Representation | Captures semantic relationships | Cannot handle polysemy |
| BERT | Contextual Embeddings | State-of-the-art representation | High computational resource requirements |
3. Classification Model Selection
Choose an appropriate classification algorithm based on task requirements and data characteristics:
-
Traditional Machine Learning Methods:
-
Deep Learning Methods:
Practical Example: News Classification
Let us demonstrate how to implement text classification using Python through a practical example. We will use the 20 Newsgroups dataset, a classic news classification dataset.
1. Data Preparation
Example
from
sklearn.
datasets
import
fetch_20newsgroups
Select 4 categories as examples
categories
=
[
'alt.atheism'
,
'soc.religion.christian'
,
'comp.graphics'
,
'sci.med'
]
Load the training set and test set
newsgroups_train
=
fetch_20newsgroups
(
subset
=
'train'
,
categories
=
categories
)
newsgroups_test
=
fetch_20newsgroups
(
subset
=
'test'
,
categories
=
categories
)
(
f
"Number of training samples: {len(newsgroups_train.data)}"
)
(
f
"Number of test samples: {len(newsgroups_test.data)}"
)
2. Feature Extraction (TF-IDF)
Example
from
sklearn.
feature_extraction
.
text
import
TfidfVectorizer
Create a TF-IDF vectorizer
vectorizer
=
TfidfVectorizer
(
max_features
=
5000
)
Transform the training set and test set
X_train
=
vectorizer.
fit_transform
(
newsgroups_train.
data
)
X_test
=
vectorizer.
transform
(
newsgroups_test.
data
)
y_train
=
newsgroups_train.
target
y_test
=
newsgroups_test.
target
3. Model Training (Logistic Regression)
Example
from
sklearn.
linear_model
import
LogisticRegression
from
sklearn.
metrics
import
accuracy_score
,
classification_report
Create and train the model
model
=
LogisticRegression
(
max_iter
=
1000
)
model.
fit
(
X_train
,
y_train
)
Predict on the test set
y_pred
=
model.
predict
(
X_test
)
Evaluate the model
(
f
"Accuracy: {accuracy_score(y_test, y_pred):.2f}"
)
(
"\nClassification Report:"
)
(
classification_report
(
y_test
,
y_pred
,
target_names
=
newsgroups_test.
target_names
)
)
4. Result Analysis
Typical output results might look like the following:
准确率: 0.91
Classification Report:
precision recall f1-score support
alt.atheism 0.90 0.87 0.89 319
soc.religion.christian 0.93 0.95 0.94 389
comp.graphics 0.89 0.90 0.90 396
sci.med 0.92 0.91 0.92 398
accuracy 0.91 1502
macro avg 0.91 0.91 0.91 1502
weighted avg 0.91 0.91 0.91 1502
Advanced Techniques and Challenges
Handling Class Imbalance
When some classes have far more samples than others, you can try:
- Resampling (oversample the minority class or undersample the majority class)
- Use class weights
- Try different evaluation metrics (e.g., F1-score instead of accuracy)
Methods to Improve Model Performance
-
Feature Engineering:
-
Model optimization:
-
Data augmentation:
Common challenges
- Multi-label Classification: A document may belong to multiple categories
- Domain adaptation: Model performance degrades in new domains
- Few-shot Learning: Situations with limited labeled data
- Interpretability: Understand why a model makes a particular classification decision
Summary and Learning Path
Text classification is a fundamental NLP task; mastering it is crucial for understanding more complex NLP applications. Recommended learning path:
- Start with traditional machine learning methods (e.g., TF-IDF + SVM)
- Understand the concepts and applications of word embeddings (Word2Vec, GloVe)
- Learn the application of deep learning models (CNN, LSTM) in text classification
- Explore transfer learning with pre-trained language models (BERT, GPT)
Through continuous practice and trying different methods, you will be able to build powerful and practical text classification systems.