Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Text Representation Methods

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

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

)

print

(

vectorizer.

get_feature_names_out

(

)

)

print

(

X.

toarray

(

)

)

Analysis of Pros and Cons

✅ Advantages:

❌ Disadvantages:


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

Code Implementation

Example

from

sklearn.

feature_extraction

.

text

import

TfidfVectorizer

tfidf_vectorizer

=

TfidfVectorizer

(

)

X_tfidf

=

tfidf_vectorizer.

fit_transform

(

corpus

)

print

(

tfidf_vectorizer.

get_feature_names_out

(

)

)

print

(

X_tfidf.

toarray

(

)

)

Pros and Cons

✅ Advantages:

❌ Disadvantages:


N-gram Model

The N-gram model considers word order information, representing text through combinations of n consecutive words.

Common Types

Code Example

Example

bigram_vectorizer

=

CountVectorizer

(

ngram_range

=

(

2

,

2

)

)

X_bigram

=

bigram_vectorizer.

fit_transform

(

corpus

)

print

(

bigram_vectorizer.

get_feature_names_out

(

)

)

Pros and Cons

✅ Advantages:

❌ Disadvantages:


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

  1. CBOW (Continuous Bag of Words): Predict the current word from its context
  2. 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


GloVe Word Vectors

GloVe (Global Vectors for Word Representation) combines the advantages of global statistics and local context windows.

Core idea

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

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

Architecture Diagram


BERT and Its Variants

BERT (Bidirectional Encoder Representations from Transformers) is a pre-trained language model proposed by Google.

Key innovations

Common Variants

  1. RoBERTa: Optimized training strategy
  2. DistilBERT: Lightweight version of BERT
  3. 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:

  1. Pre-training Stage: Train general language representations on large-scale corpora
  2. 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

  1. PV-DM (Distributed Memory): Similar to CBOW, with document ID added
  2. 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

  1. Averaging Method: Average the word vectors
  2. SIF: Smooth inverse frequency weighted average
  3. 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

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


Summary

The development of text representation methods has evolved from simple statistics to deep learning:

  1. Traditional Methods: Simple and efficient, suitable for small-scale data
  2. Word Vectors: Capture semantic relations, low dimensionality
  3. Context-Aware Models: Dynamic representations, best performance but high computational cost
  4. Document Representation: Extend from word level to document level

When choosing a text representation method, consider:

With the development of large language models, text representation techniques are still evolving rapidly, but understanding these fundamental methods remains crucial for mastering NLP.