Text Representation Methods
Text representation is a fundamental task in Natural Language Processing (NLP); it transforms unstructured text data into numerical forms that computers can process.
This article systematically introduces common text representation methods in NLP, from traditional methods to modern deep learning techniques, helping readers fully understand this core concept.
Traditional Text Representation
Bag-of-Words Model (Bag of Words)
The Bag-of-Words model is one of the simplest text representation methods; it treats text as an unordered collection of words.
Basic concepts
- Ignores word order and grammar, focusing only on whether words appear
- Build a vocabulary and count the occurrences of each word in a document
- Ultimately represented as a high-dimensional sparse vector
Code Example
Example
from
sklearn.
feature_extraction
.
text
import
CountVectorizer
corpus
=
[
'This is the first document.'
,
'This document is the second document.'
,
'And this is the third one.'
,
'Is this the first document?'
]
vectorizer
=
CountVectorizer
(
)
X
=
vectorizer.
fit_transform
(
corpus
)
(
vectorizer.
get_feature_names_out
(
)
)
(
X.
toarray
(
)
)
Analysis of Pros and Cons
✅ Advantages:
- Simple to implement, computationally efficient
- Suitable for small datasets and simple tasks
❌ Disadvantages:
- Ignores word order and semantic information
- High-dimensional sparsity problem
- Cannot handle synonyms and polysemy
TF-IDF
TF-IDF (Term Frequency-Inverse Document Frequency) is an improvement over the Bag-of-Words model, considering the importance of words in the entire corpus.
Calculation Formula
- TF (Term Frequency):
词在文档中出现的次数 / 文档总词数 - IDF (Inverse Document Frequency):
log(文档总数 / 包含该词的文档数) - TF-IDF = TF × IDF
Code Implementation
Example
from
sklearn.
feature_extraction
.
text
import
TfidfVectorizer
tfidf_vectorizer
=
TfidfVectorizer
(
)
X_tfidf
=
tfidf_vectorizer.
fit_transform
(
corpus
)
(
tfidf_vectorizer.
get_feature_names_out
(
)
)
(
X_tfidf.
toarray
(
)
)
Pros and Cons
✅ Advantages:
- Reduce the influence of common words, highlight important words
- Performs better than the simple Bag-of-Words model
❌ Disadvantages:
- Still cannot capture semantic relationships
- The high-dimensionality problem still exists
N-gram Model
The N-gram model considers word order information, representing text through combinations of n consecutive words.
Common Types
- Unigram (1-gram): A single word
- Bigram (2-gram): A combination of two consecutive words
- Trigram (3-gram): A combination of three consecutive words
Code Example
Example
bigram_vectorizer
=
CountVectorizer
(
ngram_range
=
(
2
,
2
)
)
X_bigram
=
bigram_vectorizer.
fit_transform
(
corpus
)
(
bigram_vectorizer.
get_feature_names_out
(
)
)
Pros and Cons
✅ Advantages:
- Captures local word order information
- Can represent phrases and fixed collocations
❌ Disadvantages:
- More severe dimensionality explosion problem
- Still cannot handle long-distance dependencies
Word Vector Representation
Word2Vec Principles and Implementation
Word2Vec is a neural network-based word vector representation method proposed by Google in 2013.
Two Model Architectures
- CBOW (Continuous Bag of Words): Predict the current word from its context
- Skip-gram: Predict the context from the current word
Code Implementation
Example
from
gensim.
models
import
Word2Vec
sentences
=
[
[
"cat"
,
"say"
,
"meow"
]
,
[
"dog"
,
"say"
,
"woof"
]
]
model
=
Word2Vec
(
sentences
,
vector_size
=
100
,
window
=
5
,
min_count
=
1
,
workers
=
4
)
Obtain word vectors
vector
=
model.
wv
[
'cat'
]
Find similar words
similar_words
=
model.
wv
.
most_similar
(
'cat'
)
Feature
- Low-dimensional dense vectors (usually 50-300 dimensions)
- Can capture semantic and syntactic relationships of words
- Supports vector operations (e.g., king - man + woman ≈ queen)
GloVe Word Vectors
GloVe (Global Vectors for Word Representation) combines the advantages of global statistics and local context windows.
Core idea
- Based on a word co-occurrence matrix
- The optimization objective is to make the dot product of two word vectors equal to the logarithm of their co-occurrence count
Comparison with Word2Vec
| Feature | Word2Vec | GloVe |
|---|---|---|
| Training Method | Local window | Global statistics |
| Computational efficiency | Higher | Lower |
| Performance on small datasets | Good | Average |
| Performance on large datasets | Good | Better |
FastText
FastText is a word vector model developed by Facebook, characterized by considering subword information.
Main Features
- Represent words as a set of character n-grams
- Can handle out-of-vocabulary (OOV) words
- Especially suitable for morphologically rich languages
Code Example
Example
from
gensim.
models
import
FastText
model
=
FastText
(
sentences
,
vector_size
=
100
,
window
=
5
,
min_count
=
1
,
workers
=
4
)
Can obtain vectors even when a word is not in the dictionary
vector
=
model.
wv
[
'unseenword'
]
Context-aware Representations
ELMo Model
ELMo (Embeddings from Language Models) is one of the earliest context-dependent word representation methods.
Core features
- Based on a bidirectional LSTM language model
- A word's representation depends on the entire input sentence
- Generates multi-layer representations (semantics from different levels can be combined)
Architecture Diagram

BERT and Its Variants
BERT (Bidirectional Encoder Representations from Transformers) is a pre-trained language model proposed by Google.
Key innovations
- Transformer Architecture
- Masked Language Model (MLM) training objective
- Next Sentence Prediction (NSP) task
Common Variants
- RoBERTa: Optimized training strategy
- DistilBERT: Lightweight version of BERT
- ALBERT: Parameter sharing to reduce model size
Code Example
Example
from
transformers
import
BertTokenizer
,
BertModel
tokenizer
=
BertTokenizer.
from_pretrained
(
'bert-base-uncased'
)
model
=
BertModel.
from_pretrained
(
'bert-base-uncased'
)
inputs
=
tokenizer
(
"Hello, my dog is cute"
,
return_tensors
=
"pt"
)
outputs
=
model
(
**inputs
)
last_hidden_states
=
outputs.
last_hidden_state
Overview of Pre-trained Language Models
Modern NLP mainly uses the pre-training + fine-tuning paradigm:
- Pre-training Stage: Train general language representations on large-scale corpora
- Fine-tuning Stage: Adjust model parameters on task-specific data
Model Comparison
| Model | Release date | Main Features |
|---|---|---|
| Word2Vec | 2013 | Static word vectors |
| GloVe | 2014 | Global statistics + local window |
| ELMo | 2018 | Bidirectional LSTM, context-dependent |
| BERT | 2018 | Transformer, bidirectional context |
| GPT-3 | 2020 | Unidirectional Transformer, strong generation capability |
Document-level Representation
Doc2Vec
Doc2Vec is an extension of Word2Vec that can directly learn vector representations of documents.
Two Models
- PV-DM (Distributed Memory): Similar to CBOW, with document ID added
- PV-DBOW (Distributed Bag of Words): Similar to Skip-gram
Code Example
Example
from
gensim.
models
import
Doc2Vec
from
gensim.
models
.
doc2vec
import
TaggedDocument
documents
=
[
TaggedDocument
(
doc
,
[
i
]
)
for
i
,
doc
in
enumerate
(
corpus
)
]
model
=
Doc2Vec
(
documents
,
vector_size
=
100
,
window
=
5
,
min_count
=
1
,
workers
=
4
)
vector
=
model.
infer_vector
(
[
"new"
,
"document"
,
"text"
]
)
Sentence Vectors and Document Vectors
// 2022-01-01 00:00:00 GMT
- Averaging Method: Average the word vectors
- SIF: Smooth inverse frequency weighted average
- BERT sentence embeddings: Use the [CLS] token or average all word vectors
Code example (using Sentence-BERT)
Example
from
sentence_transformers
import
SentenceTransformer
model
=
SentenceTransformer
(
'all-MiniLM-L6-v2'
)
sentences
=
[
"This is an example sentence"
,
"Each sentence is converted"
]
embeddings
=
model.
encode
(
sentences
)
Topic Model (LDA)
Latent Dirichlet Allocation (LDA) is an unsupervised topic modeling method.
Basic Principles
- Represent a document as a mixture of multiple topics
- Each topic is a probability distribution over words
- Learned via variational inference or Gibbs sampling
Code Example
Example
from
sklearn.
decomposition
import
LatentDirichletAllocation
from
sklearn.
feature_extraction
.
text
import
CountVectorizer
vectorizer
=
CountVectorizer
(
)
X
=
vectorizer.
fit_transform
(
corpus
)
lda
=
LatentDirichletAllocation
(
n_components
=
2
)
lda.
fit
(
X
)
Application scenarios
- Document Clustering
- Content Recommendation
- Text summarization
Summary
The development of text representation methods has evolved from simple statistics to deep learning:
- Traditional Methods: Simple and efficient, suitable for small-scale data
- Word Vectors: Capture semantic relations, low dimensionality
- Context-Aware Models: Dynamic representations, best performance but high computational cost
- Document Representation: Extend from word level to document level
When choosing a text representation method, consider:
- Task requirements (whether semantic understanding is needed)
- Data Scale
- Computational Resources
- Language Characteristics
With the development of large language models, text representation techniques are still evolving rapidly, but understanding these fundamental methods remains crucial for mastering NLP.