PyTorch torchtext
Although the PyTorch ecosystem has torchvision libraries for handling image datatorchaudio and audio data, in the field of text processing the library once officially provided torchtext has undergone some changes. This section explains how to use various methods for text preprocessing, vocabulary building, data loading, and more.
Note: the torchtext library has undergone some refactoring. It is recommended to use a maintained alternative torchtext.legacy or build your own text processing pipeline. The latest torchtext version has returned with a more modern API.
1. Fundamentals of text data preprocessing
Text preprocessing is the first step in NLP tasks, including tokenization, vocabulary building, encoding, and similar operations.
1.1 Basic text processing workflow
Example
import
re
from
collections
import
Counter
class
SimpleTokenizer:
"""
Simple tokenizer: split on spaces and punctuation
"""
def
init
(
self
)
:
Punctuation mapping
self
.
punctuation
=
str
.
maketrans
(
''
,
''
,
'.,!?;:"'-()[]{}'
)
def
tokenize
(
self
,
text
)
:
Lowercase conversion
text
=
text.
lower
(
)
Remove punctuation
text
=
text.
translate
(
self
.
punctuation
)
Tokenization
tokens
=
text.
split
(
)
return
tokens
class
Vocabulary:
"""
Vocabulary construction
"""
def
init
(
self
,
min_freq
=
2
,
max_size
=
10000
)
:
self
.
min_freq
=
min_freq
self
.
max_size
=
max_size
self
.
word2idx
=
{
'
:
0
,
'
:
1
}
self
.
idx2word
=
{
0
:
'
,
1
:
'
}
self
.
word_count
=
Counter
(
)
def
build_vocab
(
self
,
texts
)
:
"""Build a vocabulary from a list of texts"""
tokenizer
=
SimpleTokenizer
(
)
Count word frequencies
for
text
in
texts:
tokens
=
tokenizer.
tokenize
(
text
)
self
.
word_count
.
update
(
tokens
)
Build the vocabulary
for
word
,
count
in
self
.
word_count
.
most_common
(
self
.
max_size
)
:
if
count
<
self
.
min_freq
:
break
if
word
not
in
self
.
word2idx
:
idx
=
len
(
self
.
word2idx
)
self
.
word2idx
[
word
]
=
idx
self
.
idx2word
[
idx
]
=
word
(
f
"Vocabulary size: {len(self.word2idx)}"
)
def
encode
(
self
,
text
,
max_len
=
50
)
:
"""Encode text into a sequence of indices"""
tokenizer
=
SimpleTokenizer
(
)
tokens
=
tokenizer.
tokenize
(
text
)
[
:max_len
]
Encoding
indices
=
[
self
.
word2idx
.
get
(
token
,
self
.
word2idx
[
'
]
)
for
token
in
tokens
]
Padding
if
len
(
indices
)
<
max_len:
indices +
=
[
self
.
word2idx
[
'
]
]
(
max_len -
len
(
indices
)
)
return
indices
def
decode
(
self
,
indices
)
:
"""Decode a sequence of indices back into text"""
tokens
=
[
self
.
idx2word
.
get
(
idx
,
'
)
for
idx
in
indices
]
return
' '
.
join
(
tokens
)
Usage examples
texts
=
[
"Hello world"
,
"This is a test"
,
"PyTorch is great for deep learning"
,
"Natural language processing is fun"
,
"Deep learning enables many applications"
,
]
vocab
=
Vocabulary
(
min_freq
=
1
,
max_size
=
100
)
vocab.
build_vocab
(
texts
)
Encoding
encoded
=
vocab.
encode
(
"Hello deep learning world!"
,
max_len
=
10
)
(
f
"Encoded result: {encoded}"
)
Decode
decoded
=
vocab.
decode
(
encoded
)
(
f
"Decoded result: {decoded}"
)
2. Using torchtext (Legacy)
If torchtext is installed, you can use its legacy module for text processing.
2.1 Installation and import
Example
Install torchtext
pip install torchtext
Import the legacy module
try
:
import
torchtext
from
torchtext.
legacy
import
data
from
torchtext.
legacy
import
datasets
(
f
"torchtext version: {torchtext.version}"
)
TORCHTEXT_AVAILABLE
=
True
except
ImportError
:
(
"torchtext not installed; using a custom implementation"
)
TORCHTEXT_AVAILABLE
=
False
Or try the newer version
try
:
from
torchtext
import
transforms
from
torchtext.
datasets
import
AG_NEWS
(
"New torchtext version available"
)
except
ImportError
:
(
"New torchtext version unavailable"
)
2.2 Field and Dataset
Example
Use torchtext.legacy
from
torchtext.
legacy
import
data
from
torchtext.
legacy
import
datasets
from
torchtext.
legacy
.
data
import
Field
,
TabularDataset
,
BucketIterator
Define fields
TEXT
=
Field
(
tokenize
=
'spacy'
,
Tokenize with spacy
tokenizer_language
=
'en_core_web_sm'
,
lower
=
True
,
Lowercase conversion
include_lengths
=
True
,
Return the sequence length
batch_first
=
True
batch dimension first
)
LABEL
=
Field
(
sequential
=
False
,
use_vocab
=
False
,
dtype
=
torch.
long
)
Define a dataset
Assume a CSV file with the format: label,text
1,This is a positive review
0,This is a negative review
Or use a built-in dataset (such as IMDB)
train_data, test_data = datasets.IMDB.splits(TEXT, LABEL)
(
"Field and Dataset configured"
)
2.3 Vocabulary construction and iterators
Example
Build the vocabulary
TEXT.build_vocab(train_data, vectors="glove.6B.100d", max_size=10000)
Create iterators
train_iterator, test_iterator = BucketIterator.splits(
(train_data, test_data),
batch_size=32,
sort_within_batch=True,
device=torch.device('cuda')
)
Iterate over training
for batch in train_iterator:
text, lengths = batch.text
labels = batch.label
# Training code
(
"Vocabulary and iterators configured"
)
3. Custom NLP data pipeline
A more flexible custom data processing approach is recommended, one that does not rely on torchtext.
3.1 Dataset class implementation
Example
import
torch
from
torch.
utils
.
data
import
Dataset
,
DataLoader
from
collections
import
Counter
import
re
class
TextDataset
(
Dataset
)
:
"""
Text dataset
"""
def
init
(
self
,
texts
,
labels
,
vocab
=
None
,
max_len
=
128
,
min_freq
=
2
)
:
self
.
texts
=
texts
self
.
labels
=
labels
self
.
max_len
=
max_len
Build or reuse an existing vocabulary
if
vocab
is
None
:
self
.
vocab
=
self
._build_vocab
(
texts
,
min_freq
)
else
:
self
.
vocab
=
vocab
def
_build_vocab
(
self
,
texts
,
min_freq
)
:
"""Build the vocabulary"""
word_counts
=
Counter
(
)
for
text
in
texts:
tokens
=
self
._tokenize
(
text
)
word_counts.
update
(
tokens
)
Create the vocabulary
word2idx
=
{
'
:
0
,
'
:
1
}
for
word
,
count
in
word_counts.
items
(
)
:
if
count
=
min_freq:
word2idx
[
word
]
=
len
(
word2idx
)
return
word2idx
def
_tokenize
(
self
,
text
)
:
"""Simple tokenization"""
Lowercase conversion
text
=
text.
lower
(
)
Remove special characters, keeping letters, digits, and spaces
text
=
re
.
sub
(
r
'[^a-z0-9\s]'
,
' '
,
text
)
Tokenization
tokens
=
text.
split
(
)
return
tokens
def
_encode
(
self
,
text
)
:
"""Encode text"""
tokens
=
self
._tokenize
(
text
)
[
:
self
.
max_len
]
indices
=
[
self
.
vocab
.
get
(
token
,
self
.
vocab
[
'
]
)
for
token
in
tokens
]
Padding
if
len
(
indices
)
<
self
.
max_len
:
indices +
=
[
self
.
vocab
[
'
]
]
(
self
.
max_len
len
(
indices
)
)
return
indices
def
len
(
self
)
:
return
len
(
self
.
texts
)
def
getitem
(
self
,
idx
)
:
text
=
self
.
texts
[
idx
]
label
=
self
.
labels
[
idx
]
encoded
=
self
._encode
(
text
)
return
torch.
tensor
(
encoded
,
dtype
=
torch.
long
)
,
torch.
tensor
(
label
,
dtype
=
torch.
long
)
Usage examples
texts
=
[
"This is a great movie"
,
"I hated this film"
,
"Amazing performance"
,
"Terrible acting"
,
"Highly recommend"
,
]
labels
=
[
1
,
0
,
1
,
0
,
1
]
dataset
=
TextDataset
(
texts
,
labels
,
max_len
=
10
)
(
f
"Dataset size: {len(dataset)}"
)
(
f
"Vocabulary size: {len(dataset.vocab)}"
)
Get a sample
text
,
label
=
dataset
[
0
]
(
f
"Text encoding: {text[:5]}..."
)
(
f
"Label: {label}"
)
3.2 Advanced tokenizers
Example
Advanced tokenization with spacy
def
tokenize_with_spacy
(
text
)
:
"""Tokenize with spacy"""
try
:
import
spacy
nlp
=
spacy.
load
(
"en_core_web_sm"
)
doc
=
nlp
(
text
)
return
[
token
.
text
for
token
in
doc
]
except
ImportError
:
(
"spacy not installed; using simple tokenization"
)
return
text.
lower
(
)
.
split
(
)
Tokenization and stemming with nltk
def
tokenize_with_nltk
(
text
)
:
"""Tokenize with nltk"""
try
:
import
nltk
from
nltk.
tokenize
import
word_tokenize
from
nltk.
stem
import
PorterStemmer
Tokenization
tokens
=
word_tokenize
(
text.
lower
(
)
)
Optional: stemming
stemmer
=
PorterStemmer
(
)
tokens
=
[
stemmer.
stem
(
token
)
for
token
in
tokens
if
token
.
isalnum
(
)
]
return
tokens
except
ImportError
:
return
text.
lower
(
)
.
split
(
)
Subword tokenization with SentencePiece
class
SentencePieceTokenizer:
"""
Subword tokenization with SentencePiece
"""
def
init
(
self
,
model_path
=
None
)
:
self
.
model_path
=
model_path
self
.
sp
=
None
def
train
(
self
,
texts
,
vocab_size
=
10000
)
:
"""Train a SentencePiece model"""
try
:
import
sentencepiece
as
spm
import
tempfile
Write to a temporary file
with
tempfile
.
NamedTemporaryFile
(
mode
=
'w'
,
delete
=
False
,
suffix
=
'.txt'
)
as
f:
for
text
in
texts:
f.
write
(
text +
'\n'
)
temp_file
=
f.
name
Training
spm.
SentencePieceTrainer
.
train
(
input
=
temp_file
,
model_prefix
=
'spm_model'
,
vocab_size
=
vocab_size
,
character_coverage
=
1.0
,
model_type
=
'unigram'
,
)
self
.
sp
=
spm.
SentencePieceProcessor
(
)
self
.
sp
.
load
(
'spm_model.model'
)
except
ImportError
:
(
"sentencepiece not installed"
)
def
encode
(
self
,
text
)
:
if
self
.
sp
:
return
self
.
sp
.
encode
(
text
,
out_type
=
str
)
return
text.
split
(
)
def
decode
(
self
,
ids
)
:
if
self
.
sp
:
return
self
.
sp
.
decode
(
ids
)
return
' '
.
join
(
ids
)
3.3 Complete data loader
Example
import
torch
from
torch.
utils
.
data
import
Dataset
,
DataLoader
from
collections
import
Counter
class
NLPDataset
(
Dataset
)
:
"""
Complete NLP dataset class
Supports variable-length sequences, vocabulary building, and batch padding
"""
def
init
(
self
,
texts
,
labels
,
min_freq
=
2
,
max_vocab
=
30000
)
:
self
.
texts
=
texts
self
.
labels
=
labels
self
.
min_freq
=
min_freq
Build the vocabulary
self
.
word2idx
,
self
.
idx2word
=
self
._build_vocab
(
texts
,
max_vocab
)
self
.
pad_idx
=
self
.
word2idx
[
'
]
self
.
unk_idx
=
self
.
word2idx
[
'
]
def
_tokenize
(
self
,
text
)
:
text
=
text.
lower
(
)
text
=
re
.
sub
(
r
'[^a-z0-9\s]'
,
' '
,
text
)
return
text.
split
(
)
def
_build_vocab
(
self
,
texts
,
max_vocab
)
:
"""Build the vocabulary"""
counter
=
Counter
(
)
for
text
in
texts:
tokens
=
self
._tokenize
(
text
)
counter.
update
(
tokens
)
Build the vocabulary
word2idx
=
{
'
:
0
,
'
:
1
}
idx2word
=
{
0
:
'
,
1
:
'
}
for
word
,
count
in
counter.
most_common
(
max_vocab
)
:
if
count
=
self
.
min_freq
and
word
not
in
word2idx:
idx
=
len
(
word2idx
)
word2idx
[
word
]
=
idx
idx2word
[
idx
]
=
word
return
word2idx
,
idx2word
def
len
(
self
)
:
return
len
(
self
.
texts
)
def
getitem
(
self
,
idx
)
:
text
=
self
.
texts
[
idx
]
tokens
=
self
._tokenize
(
text
)
indices
=
[
self
.
word2idx
.
get
(
t
,
self
.
unk_idx
)
for
t
in
tokens
]
return
{
'input'
: indices
,
'label'
:
self
.
labels
[
idx
]
,
'length'
:
len
(
indices
)
}
def
collate_fn
(
batch
,
pad_idx
=
0
)
:
"""
Custom collate function: handle variable-length sequences
"""
Sort by length in descending order
batch.
sort
(
key
=
lambda
x: x
[
'length'
]
,
reverse
=
True
)
texts
=
[
item
[
'input'
]
for
item
in
batch
]
labels
=
[
item
[
'label'
]
for
item
in
batch
]
lengths
=
[
item
[
'length'
]
for
item
in
batch
]
Pad to the same length
max_len
=
max
(
lengths
)
padded
=
[
text +
[
pad_idx
]
(
max_len -
len
(
text
)
)
for
text
in
texts
]
return
{
'input'
: torch.
tensor
(
padded
,
dtype
=
torch.
long
)
,
'labels'
: torch.
tensor
(
labels
,
dtype
=
torch.
long
)
,
'lengths'
: torch.
tensor
(
lengths
,
dtype
=
torch.
long
)
}
Use DataLoader
def
create_dataloader
(
texts
,
labels
,
batch_size
=
32
,
shuffle
=
True
)
:
"""Create the data loader"""
dataset
=
NLPDataset
(
texts
,
labels
)
pad_idx
=
dataset.
pad_idx
dataloader
=
DataLoader
(
dataset
,
batch_size
=
batch_size
,
shuffle
=
shuffle
,
collate_fn
=
lambda
b: collate_fn
(
b
,
pad_idx
)
)
return
dataloader
,
dataset
Simulated data
texts
=
[
"I love this movie"
,
"This is a bad movie"
,
"Great film"
,
"Terrible acting"
,
"I recommend this"
,
"Not worth watching"
,
]
labels
=
[
1
,
0
,
1
,
0
,
1
,
0
]
dataloader
,
dataset
=
create_dataloader
(
texts
,
labels
,
batch_size
=
2
)
for
batch
in
dataloader:
(
"Input shape:"
,
batch
[
'input'
]
.
shape
)
(
"Labels:"
,
batch
[
'labels'
]
)
(
"Lengths:"
,
batch
[
'lengths'
]
)
(
"---"
)
4. Loading pretrained word vectors
Using pretrained word vectors can improve model performance.
4.1 GloVe word vectors
Example
import
torch
import
numpy
as
np
def
load_glove_vectors
(
filepath
,
word2idx
,
embedding_dim
=
300
)
:
"""
Load GloVe pretrained word vectors
Parameters:
filepath: GloVe file path
word2idx: vocabulary dictionary
embedding_dim: word vector dimension
"""
(
"Loading GloVe word vectors..."
)
Initialize the embedding matrix
num_words
=
len
(
word2idx
)
embeddings
=
np.
random
.
randn
(
num_words
,
embedding_dim
)
.
astype
(
np.
float32
)
embeddings
[
word2idx
[
'
]
]
=
np.
zeros
(
embedding_dim
)
Set the PAD vector to zero
words_loaded
=
0
with
open
(
filepath
,
'r'
,
encoding
=
'utf-8'
)
as
f:
for
line
in
f:
values
=
line.
strip
(
)
.
split
(
)
word
=
values
[
0
]
if
word
in
word2idx:
idx
=
word2idx
[
word
]
vector
=
np.
asarray
(
values
[
1
:
]
,
dtype
=
np.
float32
)
if
len
(
vector
)
==
embedding_dim:
embeddings
[
idx
]
=
vector
words_loaded +
=
1
(
f
"Loaded {words_loaded}/{num_words} word vectors"
)
return
torch.
from_numpy
(
embeddings
)
Simulate loading
def
create_pretrained_embedding
(
word2idx
,
embedding_dim
=
300
,
pretrained_path
=
None
)
:
"""
Create a pretrained embedding layer
"""
if
pretrained_path
and
False
:
Set it to True and provide a valid path
weights
=
load_glove_vectors
(
pretrained_path
,
word2idx
,
embedding_dim
)
else
:
Use random initialization
num_words
=
len
(
word2idx
)
weights
=
torch.
randn
(
num_words
,
embedding_dim
)
0.1
embedding
=
torch.
nn
.
Embedding
.
from_pretrained
(
weights
,
padding_idx
=
0
)
return
embedding
Example
word2idx
=
{
'
:
0
,
'
:
1
,
'hello'
:
2
,
'world'
:
3
,
'test'
:
4
}
embedding
=
create_pretrained_embedding
(
word2idx
,
embedding_dim
=
100
)
(
f
"Embedding layer shape: {embedding.weight.shape}"
)
4.2 Loading Word2Vec with gensim
Example
def
load_word2vec
(
word2idx
,
model_path
=
None
)
:
"""
Load Word2Vec with gensim
"""
try
:
from
gensim.
models
import
KeyedVectors
Load model
model = KeyedVectors.load_word2vec_format(model_path, binary=True)
Create the embedding matrix
embedding_dim
=
300
num_words
=
len
(
word2idx
)
embeddings
=
np.
random
.
randn
(
num_words
,
embedding_dim
)
.
astype
(
np.
float32
)
Fill in the word vectors
embeddings
[
word2idx
[
'
]
]
=
np.
zeros
(
embedding_dim
)
Load word vectors
for word, idx in word2idx.items():
if word in model:
embeddings[idx] = model[word]
return
torch.
from_numpy
(
embeddings
)
except
ImportError
:
(
"gensim not installed"
)
return
None
4.3 Custom pretrained embeddings
Example
import
torch
import
torch.
nn
as
nn
class
PretrainedEmbedding
(
nn.
Module
)
:
"""
An embedding layer that supports loading pretrained word vectors
"""
def
init
(
self
,
vocab_size
,
embed_dim
,
pretrained_weights
=
None
,
padding_idx
=
0
,
freeze
=
False
)
:
super
(
)
.
init
(
)
self
.
embedding
=
nn.
Embedding
(
vocab_size
,
embed_dim
,
padding_idx
=
padding_idx
)
Load pretrained weights
if
pretrained_weights
is
not
None
:
self
.
embedding
.
weight
.
data
.
copy_
(
pretrained_weights
)
Whether to freeze
if
freeze:
self
.
embedding
.
weight
.
requires_grad
=
False
def
forward
(
self
,
x
)
:
return
self
.
embedding
(
x
)
Usage examples
vocab_size
=
10000
embed_dim
=
300
pretrained
=
torch.
randn
(
vocab_size
,
embed_dim
)
0.1
embedding_layer
=
PretrainedEmbedding
(
vocab_size
,
embed_dim
,
pretrained_weights
=
pretrained
,
padding_idx
=
0
,
freeze
=
False
Set to True to freeze the embedding layer
)
Testing
x
=
torch.
tensor
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
]
)
output
=
embedding_layer
(
x
)
(
f
"Input shape: {x.shape}"
)
(
f
"Output shape: {output.shape}"
)
5. Text data augmentation
Data augmentation can improve model generalization.
5.1 Back-translation augmentation
Example
Back-translation augmentation requires a translation API; the following is a conceptual example
def
back_translation_augment
(
text
,
translator
)
:
"""
Back-translation augmentation: translate text into another language and then back again
"""
Translate into the target language
translated
=
translator.
translate
(
text
,
dest
=
'fr'
)
Translate back into the source language
back_translated
=
translator.
translate
(
translated.
text
,
dest
=
'en'
)
return
back_translated.
text
Usage examples
from googletrans import Translator
translator = Translator()
augmented_text = back_translation_augment("I love this movie", translator)
5.2 Synonym replacement
Example
import
random
def
synonym_replacement
(
text
,
n
=
1
,
stop_words
=
None
)
:
"""
Synonym Replacement
"""
if
stop_words
is
None
:
stop_words
=
{
'a'
,
'an'
,
'the'
,
'is'
,
'are'
,
'was'
,
'were'
}
words
=
text.
lower
(
)
.
split
(
)
replaceable
=
[
i
for
i
,
w
in
enumerate
(
words
)
if
w
not
in
stop_words
]
if
not
replaceable:
return
text
n
=
min
(
n
,
len
(
replaceable
)
)
replace_idx
=
random
.
sample
(
replaceable
,
n
)
Simplified synonym mapping (in practice, use WordNet)
synonym_map
=
{
'good'
:
[
'great'
,
'excellent'
,
'nice'
]
,
'bad'
:
[
'poor'
,
'terrible'
,
'awful'
]
,
'movie'
:
[
'film'
,
'cinema'
]
,
'loved'
:
[
'adored'
,
'enjoyed'
]
,
}
for
idx
in
replace_idx:
word
=
words
[
idx
]
if
word
in
synonym_map:
words
[
idx
]
=
random
.
choice
(
synonym_map
[
word
]
)
return
' '
.
join
(
words
)
Usage examples
text
=
"I loved this good movie"
augmented
=
synonym_replacement
(
text
,
n
=
2
)
(
f
"Original sentence: {text}"
)
(
f
"Augmented: {augmented}"
)
5.3 Random insertion and deletion
Example
import
random
def
random_insertion
(
text
,
n
=
1
)
:
"""
Random insertion: insert words at random positions in the text
"""
words
=
text.
lower
(
)
.
split
(
)
for
_
in
range
(
n
)
:
if
len
(
words
)
1
:
idx
=
random
.
randint
(
0
,
len
(
words
)
1
)
Simplified list of words to insert
insert_words
=
[
'really'
,
'very'
,
'quite'
,
'actually'
]
words.
insert
(
idx
,
random
.
choice
(
insert_words
)
)
return
' '
.
join
(
words
)
def
random_deletion
(
text
,
p
=
0.1
)
:
"""
Random deletion: delete words with probability p
"""
words
=
text.
lower
(
)
.
split
(
)
if
len
(
words
)
==
1
:
return
text
remaining
=
[
w
for
w
in
words
if
random
.
random
(
)
p
]
if
len
(
remaining
)
==
0
:
return
random
.
choice
(
words
)
return
' '
.
join
(
remaining
)
def
random_swap
(
text
,
n
=
1
)
:
"""
Random swap: randomly exchange the positions of two words
"""
words
=
text.
lower
(
)
.
split
(
)
if
len
(
words
)
<
2
:
return
text
for
_
in
range
(
n
)
:
idx1
,
idx2
=
random
.
sample
(
range
(
len
(
words
)
)
,
2
)
words
[
idx1
]
,
words
[
idx2
]
=
words
[
idx2
]
,
words
[
idx1
]
return
' '
.
join
(
words
)
Usage examples
text
=
"This is a great movie about love and happiness"
(
"Original:"
,
text
)
(
"Insert:"
,
random_insertion
(
text
,
n
=
2
)
)
(
"Delete:"
,
random_deletion
(
text
,
p
=
0.2
)
)
(
"Swap:"
,
random_swap
(
text
,
n
=
2
)
)
6. Examples of common NLP tasks
6.1 Complete text classification workflow
Example
import
torch
import
torch.
nn
as
nn
from
torch.
utils
.
data
import
Dataset
,
DataLoader
1. Data Preparation
texts
=
[
"I love this product, it is amazing!"
,
"Terrible quality, waste of money."
,
"Great value for the price."
,
"Not satisfied with the purchase."
,
"Best purchase I have ever made!"
,
"Very disappointed with this item."
,
]
labels
=
[
1
,
0
,
1
,
0
,
1
,
0
]
1: positive, 0: negative
2. Dataset
class
TextClassificationDataset
(
Dataset
)
:
def
init
(
self
,
texts
,
labels
,
max_len
=
50
)
:
self
.
texts
=
texts
self
.
labels
=
labels
self
.
max_len
=
max_len
self
.
vocab
=
self
._build_vocab
(
texts
)
def
_build_vocab
(
self
,
texts
)
:
vocab
=
{
'
:
0
,
'
:
1
}
for
text
in
texts:
for
word
in
text.
lower
(
)
.
split
(
)
:
if
word
not
in
vocab:
vocab
[
word
]
=
len
(
vocab
)
return
vocab
def
len
(
self
)
:
return
len
(
self
.
texts
)
def
getitem
(
self
,
idx
)
:
text
=
self
.
texts
[
idx
]
label
=
self
.
labels
[
idx
]
Simple encoding
tokens
=
text.
lower
(
)
.
split
(
)
[
:
self
.
max_len
]
indices
=
[
self
.
vocab
.
get
(
t
,
1
)
for
t
in
tokens
]
Fill
if
len
(
indices
)
<
self
.
max_len
:
indices +
=
[
0
]
(
self
.
max_len
len
(
indices
)
)
return
torch.
tensor
(
indices
,
dtype
=
torch.
long
)
,
torch.
tensor
(
label
,
dtype
=
torch.
long
)
3. Model
class
TextClassifier
(
nn.
Module
)
:
def
init
(
self
,
vocab_size
,
embed_dim
=
128
,
hidden_dim
=
64
,
num_classes
=
2
)
:
super
(
)
.
init
(
)
self
.
embedding
=
nn.
Embedding
(
vocab_size
,
embed_dim
,
padding_idx
=
0
)
self
.
lstm
=
nn.
LSTM
(
embed_dim
,
hidden_dim
,
batch_first
=
True
)
self
.
fc
=
nn.
Linear
(
hidden_dim
,
num_classes
)
def
forward
(
self
,
x
)
:
embedded
=
self
.
embedding
(
x
)
_
,
(
hidden
,
_
)
=
self
.
lstm
(
embedded
)
output
=
self
.
fc
(
hidden.
squeeze
(
0
)
)
return
output
4. Training
dataset
=
TextClassificationDataset
(
texts
,
labels
)
dataloader
=
DataLoader
(
dataset
,
batch_size
=
2
,
shuffle
=
True
)
model
=
TextClassifier
(
vocab_size
=
len
(
dataset.
vocab
)
)
criterion
=
nn.
CrossEntropyLoss
(
)
optimizer
=
torch.
optim
.
Adam
(
model.
parameters
(
)
,
lr
=
0.001
)
Train for a few epochs
model.
train
(
)
for
epoch
in
range
(
10
)
:
total_loss
=
0
for
texts_batch
,
labels_batch
in
dataloader:
optimizer.
zero_grad
(
)
outputs
=
model
(
texts_batch
)
loss
=
criterion
(
outputs
,
labels_batch
)
loss.
backward
(
)
optimizer.
step
(
)
total_loss +
=
loss.
item
(
)
(
f
"Epoch {epoch+1}, Loss: {total_loss/len(dataloader):.4f}"
)
(
"Training complete!"
)
6.2 Sequence labeling (NER) example
Example
import
torch
import
torch.
nn
as
nn
from
torch.
utils
.
data
import
Dataset
,
DataLoader
Sequence labeling dataset
class
NERDataset
(
Dataset
)
:
"""
Named entity recognition dataset
Format: [(word, tag), ...]
"""
def
init
(
self
,
sentences_tags
,
word2idx
,
tag2idx
,
max_len
=
50
)
:
self
.
sentences_tags
=
sentences_tags
self
.
word2idx
=
word2idx
self
.
tag2idx
=
tag2idx
self
.
max_len
=
max_len
def
len
(
self
)
:
return
len
(
self
.
sentences_tags
)
def
getitem
(
self
,
idx
)
:
sentence_tags
=
self
.
sentences_tags
[
idx
]
words
=
[
wt
[
0
]
for
wt
in
sentence_tags
]
tags
=
[
wt
[
1
]
for
wt
in
sentence_tags
]
Encoding
word_ids
=
[
self
.
word2idx
.
get
(
w.
lower
(
)
,
1
)
for
w
in
words
[
:
self
.
max_len
]
]
tag_ids
=
[
self
.
tag2idx
[
t
]
for
t
in
tags
[
:
self
.
max_len
]
]
Fill
if
len
(
word_ids
)
<
self
.
max_len
:
word_ids +
=
[
0
]
(
self
.
max_len
len
(
word_ids
)
)
tag_ids +
=
[
0
]
(
self
.
max_len
len
(
tag_ids
)
)
return
{
'words'
: torch.
tensor
(
word_ids
,
dtype
=
torch.
long
)
,
'tags'
: torch.
tensor
(
tag_ids
,
dtype
=
torch.
long
)
}
NER model
class
NERModel
(
nn.
Module
)
:
def
init
(
self
,
vocab_size
,
tag_size
,
embed_dim
=
128
,
hidden_dim
=
256
)
:
super
(
)
.
init
(
)
self
.
embedding
=
nn.
Embedding
(
vocab_size
,
embed_dim
,
padding_idx
=
0
)
self
.
lstm
=
nn.
LSTM
(
embed_dim
,
hidden_dim
,
batch_first
=
True
,
bidirectional
=
True
)
self
.
fc
=
nn.
Linear
(
hidden_dim *
2
,
tag_size
)
def
forward
(
self
,
x
)
:
embedded
=
self
.
embedding
(
x
)
lstm_out
,
_
=
self
.
lstm
(
embedded
)
logits
=
self
.
fc
(
lstm_out
)
return
logits
Sample data
data
=
[
[
(
"John"
,
"B-PER"
)
,
(
"lives"
,
"O"
)
,
(
"in"
,
"O"
)
,
(
"New"
,
"B-LOC"
)
,
(
"York"
,
"I-LOC"
)
,
(
"."
,
"O"
)
]
,
[
(
"Apple"
,
"B-ORG"
)
,
(
"is"
,
"O"
)
,
(
"a"
,
"O"
)
,
(
"company"
,
"O"
)
,
(
"."
,
"O"
)
]
,
]
Build the word and tag vocabularies
word2idx
=
{
'
:
0
,
'
:
1
}
tag2idx
=
{
'O'
:
0
,
'B-PER'
:
1
,
'I-PER'
:
2
,
'B-LOC'
:
3
,
'I-LOC'
:
4
,
'B-ORG'
:
5
,
'I-ORG'
:
6
}
for
sent
in
data:
for
word
,
tag
in
sent:
if
word.
lower
(
)
not
in
word2idx:
word2idx
[
word.
lower
(
)
]
=
len
(
word2idx
)
(
f
"Vocabulary size: {len(word2idx)}"
)
(
f
"Number of tags: {len(tag2idx)}"
)
7. Recommended alternatives
7.1 Other text processing libraries
| Library name | Feature | Applicable scenarios |
|---|---|---|
| HuggingFace Datasets | Data loading and processing | General NLP tasks |
| spacy | Advanced NLP tools | Tokenization, NER, dependency parsing |
| NLTK | Classic NLP tools | Teaching and prototyping |
| textblob | Simple and Easy to Use | Fast text processing |
7.2 Using HuggingFace Datasets
Example
Use the HuggingFace Datasets library
pip install datasets
from
datasets
import
load_dataset
Load the dataset
dataset = load_dataset("imdb")
dataset = load_dataset("squad")
Data preprocessing
def preprocess_function(examples):
return tokenizer(examples['text'], truncation=True, padding='max_length')
tokenized_dataset = dataset.map(preprocess_function, batched=True)
(
"HuggingFace Datasets usage example:"
)
(
"from datasets import load_dataset"
)
(
"dataset = load_dataset('imdb')"
)
8. Quick API Reference
8.1 Common text processing operations
| Operation | Method |
|---|---|
| Tokenization | text.split(), spacy, nltk, jieba |
| Vocabulary construction | Counter, vocab.build_vocab() |
| Encoding | vocab.encode(), tokenizer.encode() |
| Decode | vocab.decode(), tokenizer.decode() |
| Fill | pad_sequence, collate_fn |
| Load word vectors | Load Gensim and GloVe directly |
8.2 Data augmentation methods
| Method | Description |
|---|---|
| Synonym Replacement | Randomly replace words with synonyms |
| Random insertion | Insert random words |
| Random deletion | Delete random words |
| Random swap | Swap the positions of random words |
| Back translation | Translate and then translate back |
8.3 Recommended data processing workflow
1. 数据清洗
- 去除 HTML 标签、特殊字符
- 统一编码、大小写
2. 分词
- 英文: spaCy / NLTK
- 中文: jieba / pkuseg
3. 词表构建
- 过滤低频词
- 设定最大词表大小
4. 序列化
- 编码为索引
- 统一长度(填充/截断)
5. 数据增强(可选)
- 同义词替换、回译
6. 批量加载
- DataLoader + 自定义 collate_fn