PyTorch torchtext
Aunque en el ecosistema de PyTorch haytorchvisionprocesamiento de datos de imágenes,torchaudioprocesamiento de datos de audio, pero en el ámbito del procesamiento de texto, la biblioteca proporcionada oficialmentetorchtextha sufrido algunos cambios. Esta sección presenta cómo utilizar diversos métodos para el preprocesamiento de datos de texto, construcción de vocabulario, carga de datos, etc.
Nota: la biblioteca torchtext ha sufrido algunas refactorizaciones. Se recomienda usartorchtext.legacyo construir tu propio pipeline de procesamiento de texto. La versión más reciente de torchtext ha regresado y ofrece una API más moderna.
1. Conceptos básicos de preprocesamiento de datos de texto
El preprocesamiento de texto es el primer paso en tareas de NLP, e incluye operaciones como tokenización, construcción de vocabulario y codificación.
1.1 Flujo básico de procesamiento de texto
Ejemplo
from collections import Counter
class SimpleTokenizer:
"""
Tokenizador simple: tokenizar por espacios y puntuación
"""
def __init__(self):
# Mapa de puntuación
self.punctuation = str.maketrans('', '', '.,!?;:"\'-()[]{}')
def tokenize(self, text):
# Convertir a minúsculas
text = text.lower()
# Eliminar puntuación
text = text.translate(self.punctuation)
# Tokenizar
tokens = text.split()
return tokens
class Vocabulary:
"""
Construcción de vocabulario
"""
def __init__(self, min_freq=2, max_size=10000):
self.min_freq = min_freq
self.max_size = max_size
self.word2idx = {'<PAD>': 0, '<UNK>': 1}
self.idx2word = {0: '<PAD>', 1: '<UNK>'}
self.word_count = Counter()
def build_vocab(self, texts):
"""Construir vocabulario a partir de una lista de textos"""
tokenizer = SimpleTokenizer()
# Contar frecuencias de palabras
for text in texts:
tokens = tokenizer.tokenize(text)
self.word_count.update(tokens)
# Construir vocabulario
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
print(f"Tamaño del vocabulario: {len(self.word2idx)}")
def encode(self, text, max_len=50):
"""Codificar texto a secuencia de índices"""
tokenizer = SimpleTokenizer()
tokens = tokenizer.tokenize(text)[:max_len]
# Codificar
indices = [
self.word2idx.get(token, self.word2idx['<UNK>'])
for token in tokens
]
# Rellenar con ceros
if len(indices) < max_len:
indices += [self.word2idx['<PAD>']] * (max_len - len(indices))
return indices
def decode(self, indices):
"""Decodificar secuencia de índices a texto"""
tokens = [self.idx2word.get(idx, '<UNK>') for idx in indices]
return ' '.join(tokens)
# Ejemplo de uso
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)
# Codificar
encoded = vocab.encode("Hello deep learning world!", max_len=10)
print(f"Resultado de codificación: {encoded}")
# Decodificar
decoded = vocab.decode(encoded)
print(f"Resultado de decodificación: {decoded}")
2. Usar torchtext (Legacy)
Si torchtext está instalado, puede utilizar el módulo legacy para el procesamiento de texto.
2.1 Instalación e importación
Ejemplo
# pip install torchtext
# Importar módulo legacy
try:
import torchtext
from torchtext.legacy import data
from torchtext.legacy import datasets
print(f"Versión de torchtext: {torchtext.__version__}")
TORCHTEXT_AVAILABLE = True
except ImportError:
print(torchtext no está instalado, usando implementación personalizada)
TORCHTEXT_AVAILABLE = False
# O prueba la nueva versión
try:
from torchtext import transforms
from torchtext.datasets import AG_NEWS
print("La nueva versión de torchtext está disponible")
except ImportError:
print("La nueva versión de torchtext no está disponible")
2.2 Field y Dataset
Ejemplo
from torchtext.legacy import data
from torchtext.legacy import datasets
from torchtext.legacy.data import Field, TabularDataset, BucketIterator
# Definir campos
TEXT = Field(
tokenize='spacy', # Usar spacy para tokenizar
tokenizer_language='en_core_web_sm',
lower=True, # Convertir a minúsculas
include_lengths=True, # Devolver la longitud de la secuencia
batch_first=True # la dimensión batch va primero
)
LABEL = Field(
sequential=False,
use_vocab=False,
dtype=torch.long
)
# Definir conjunto de datos
# Supongamos que el archivo CSV tiene el formato: label,text
# 1,This is a positive review
# 0,This is a negative review
# o usar el conjunto de datos integrado (por ejemplo, IMDB)
# train_data, test_data = datasets.IMDB.splits(TEXT, LABEL)
print("Field y Dataset configurados")
2.3 Construcción de vocabulario e iteradores
Ejemplo
# TEXT.build_vocab(train_data, vectors="glove.6B.100d", max_size=10000)
# Crear iterador
# train_iterator, test_iterator = BucketIterator.splits(
# (train_data, test_data),
# batch_size=32,
# sort_within_batch=True,
# device=torch.device('cuda')
# )
# Entrenar iterativamente
# for batch in train_iterator:
# text, lengths = batch.text
# labels = batch.label
# # Código de entrenamiento
print("Vocabulario e iterador configurados")
3. Pipeline de datos de NLP personalizado
Se recomienda utilizar un método de procesamiento de datos personalizado más flexible, sin depender de torchtext.
3.1 Implementación de la clase de conjunto de datos
Ejemplo
from torch.utils.data import Dataset, DataLoader
from collections import Counter
import re
class TextDataset(Dataset):
"""
Conjunto de datos de texto
"""
def __init__(self, texts, labels, vocab=None, max_len=128, min_freq=2):
self.texts = texts
self.labels = labels
self.max_len = max_len
# Construir o utilizar un vocabulario existente
if vocab is None:
self.vocab = self._build_vocab(texts, min_freq)
else:
self.vocab = vocab
def _build_vocab(self, texts, min_freq):
"""estructuraconstruirpalabratabla"""
word_counts = Counter()
for text in texts:
tokens = self._tokenize(text)
word_counts.update(tokens)
# Crear vocabulario
word2idx = {'<PAD>': 0, '<UNK>': 1}
for word, count in word_counts.items():
if count >= min_freq:
word2idx[word] = len(word2idx)
return word2idx
def _tokenize(self, text):
"""simple,dividirpalabra"""
# Convertir a minúsculas
text = text.lower()
# Eliminar caracteres especiales, conservar caracteres alfanuméricos y espacios
text = re.sub(r'[^a-z0-9\s]', ' ', text)
# Segmentación
tokens = text.split()
return tokens
def _encode(self, text):
"""codificacióntextoedición"""
tokens = self._tokenize(text)[:self.max_len]
indices = [
self.vocab.get(token, self.vocab['<UNK>'])
for token in tokens
]
# Relleno de ceros
if len(indices) < self.max_len:
indices += [self.vocab['<PAD>']] * (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)
# Ejemplo de uso
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)
print(fTamaño del conjunto de datos: {len(dataset)})
print(fTamaño del vocabulario: {len(dataset.vocab)})
# Obtener muestras
text, label = dataset[0]
print(f"Codificación de texto: {text[:5]}...")
print(f"Etiqueta: {label}")
3.2 Tokenizador avanzado
Ejemplo
def tokenize_with_spacy(text):
"""Usar spacy para la tokenización"""
try:
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp(text)
return [token.text for token in doc]
except ImportError:
print("spacy no está instalado, se utiliza segmentación simple")
return text.lower().split()
# Usar nltk para tokenización y stemming
def tokenize_with_nltk(text):
"""Usar nltk para la tokenización"""
try:
import nltk
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer
# Segmentación
tokens = word_tokenize(text.lower())
# Opcional: stemming
stemmer = PorterStemmer()
tokens = [stemmer.stem(token) for token in tokens if token.isalnum()]
return tokens
except ImportError:
return text.lower().split()
# Usar SentencePiece para la tokenización de subpalabras
class SentencePieceTokenizer:
"""
Usar SentencePiece para la tokenización de subpalabras
"""
def __init__(self, model_path=None):
self.model_path = model_path
self.sp = None
def train(self, texts, vocab_size=10000):
"""Entrenar el modelo SentencePiece"""
try:
import sentencepiece as spm
import tempfile
# Escribir en un archivo temporal
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as f:
for text in texts:
f.write(text + '\n')
temp_file = f.name
# Entrenamiento
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:
print("sentencepiece no está instalado")
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 Cargador de datos completo
Ejemplo
from torch.utils.data import Dataset, DataLoader
from collections import Counter
class NLPDataset(Dataset):
"""
Clase completa de conjunto de datos de NLP
Soporta secuencias de longitud variable, construcción de vocabulario y relleno por lotes
"""
def __init__(self, texts, labels, min_freq=2, max_vocab=30000):
self.texts = texts
self.labels = labels
self.min_freq = min_freq
# Construir vocabulario
self.word2idx, self.idx2word = self._build_vocab(texts, max_vocab)
self.pad_idx = self.word2idx['<PAD>']
self.unk_idx = self.word2idx['<UNK>']
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):
"""estructuraconstruirpalabratabla"""
counter = Counter()
for text in texts:
tokens = self._tokenize(text)
counter.update(tokens)
# Construir vocabulario
word2idx = {'<PAD>': 0, '<UNK>': 1}
idx2word = {0: '<PAD>', 1: '<UNK>'}
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):
"""
Función collate personalizada: procesamiento de secuencias de longitud variable
"""
# Ordenar por longitud en orden descendente
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]
# Rellenar a la misma longitud
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)
}
# Usar DataLoader
def create_dataloader(texts, labels, batch_size=32, shuffle=True):
"""Crear cargador de datos"""
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
# Datos simulados
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:
print("Input shape:", batch['input'].shape)
print("Labels:", batch['labels'])
print("Lengths:", batch['lengths'])
print("---")
4. Carga de vectores de palabras preentrenados
El uso de vectores de palabras preentrenados puede mejorar el rendimiento del modelo.
4.1 Vectores de palabras GloVe
Ejemplo
import numpy as np
def load_glove_vectors(filepath, word2idx, embedding_dim=300):
"""
Cargar vectores de palabras preentrenados de GloVe
Parámetros:
filepath: ruta de archivo de GloVe
word2idx: diccionario de vocabulario
embedding_dim: dimensión del vector de palabras
"""
print("Cargando los vectores de palabras GloVe...")
# Inicializar la matriz de embeddings
num_words = len(word2idx)
embeddings = np.random.randn(num_words, embedding_dim).astype(np.float32)
embeddings[word2idx['<PAD>']] = np.zeros(embedding_dim) # PAD haciacantidadcolocarCero
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
print(fSe han cargado {words_loaded}/{num_words} vectores de palabras)
return torch.from_numpy(embeddings)
# Carga simulada
def create_pretrained_embedding(word2idx, embedding_dim=300, pretrained_path=None):
"""
Crear capa de incrustación preentrenada
"""
if pretrained_path and False: # Establecer en True y proporcionar una ruta válida
weights = load_glove_vectors(pretrained_path, word2idx, embedding_dim)
else:
# Usar inicialización aleatoria
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
# Ejemplo
word2idx = {'<PAD>': 0, '<UNK>': 1, 'hello': 2, 'world': 3, 'test': 4}
embedding = create_pretrained_embedding(word2idx, embedding_dim=100)
print(f"Forma de la capa de embedding: {embedding.weight.shape}")
4.2 Cargar Word2Vec usando gensim
Ejemplo
"""
Cargar Word2Vec con gensim
"""
try:
from gensim.models import KeyedVectors
# Cargar modelo
# model = KeyedVectors.load_word2vec_format(model_path, binary=True)
# Crear matriz de embedding
embedding_dim = 300
num_words = len(word2idx)
embeddings = np.random.randn(num_words, embedding_dim).astype(np.float32)
# Rellenar vectores de palabras
embeddings[word2idx['<PAD>']] = np.zeros(embedding_dim)
# Cargar vectores de palabras
# for word, idx in word2idx.items():
# if word in model:
# embeddings[idx] = model[word]
return torch.from_numpy(embeddings)
except ImportError:
print("gensim no está instalado")
return None
4.3 Incrustaciones preentrenadas personalizadas
Ejemplo
import torch.nn as nn
class PretrainedEmbedding(nn.Module):
"""
Capa de embedding que admite la carga de vectores de palabras preentrenados
"""
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
)
# Cargar pesos preentrenados
if pretrained_weights is not None:
self.embedding.weight.data.copy_(pretrained_weights)
# Si congelar
if freeze:
self.embedding.weight.requires_grad = False
def forward(self, x):
return self.embedding(x)
# Ejemplo de uso
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 # Establecer en True para congelar la capa de embedding
)
# Prueba
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
output = embedding_layer(x)
print(f"Forma de entrada: {x.shape}")
print(f"Forma de salida: {output.shape}")
5. Aumento de datos de texto
El aumento de datos puede mejorar la capacidad de generalización del modelo.
5.1 Aumento por retro-traducción
Ejemplo
def back_translation_augment(text, translator):
"""
Retro-traducción: traducir el texto a otro idioma y luego traducirlo de vuelta
"""
# Traducir al idioma de destino
translated = translator.translate(text, dest='fr')
# Traducir de vuelta al idioma de origen
back_translated = translator.translate(translated.text, dest='en')
return back_translated.text
# Ejemplo de uso
# from googletrans import Translator
# translator = Translator()
# augmented_text = back_translation_augment("I love this movie", translator)
5.2 Reemplazo de sinónimos
Ejemplo
def synonym_replacement(text, n=1, stop_words=None):
"""
Reemplazo de sinónimos
"""
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)
# Mapa de sinónimos simplificado (en la práctica se debería usar 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)
# Ejemplo de uso
text = "I loved this good movie"
augmented = synonym_replacement(text, n=2)
print(f"Oración original: {text}")
print(f"Aumentada: {augmented}")
5.3 Inserción y eliminación aleatorias
Ejemplo
def random_insertion(text, n=1):
"""
Inserción aleatoria: insertar palabras aleatoriamente en el texto
"""
words = text.lower().split()
for _ in range(n):
if len(words) > 1:
idx = random.randint(0, len(words) - 1)
# Palabras de inserción simplificadas
insert_words = ['really', 'very', 'quite', 'actually']
words.insert(idx, random.choice(insert_words))
return ' '.join(words)
def random_deletion(text, p=0.1):
"""
Eliminación aleatoria: eliminar palabras con probabilidad 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):
"""
Intercambio aleatorio: intercambiar aleatoriamente la posición de dos palabras
"""
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)
# Ejemplo de uso
text = "This is a great movie about love and happiness"
print("Original:", text)
print("Inserción:", random_insertion(text, n=2))
print("Eliminación:", random_deletion(text, p=0.2))
print("Intercambio:", random_swap(text, n=2))
6. Ejemplos de tareas comunes de NLP
6.1 Flujo completo de clasificación de texto
Ejemplo
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
# 1. Preparación de datos
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: positivo, 0: negativo
# 2. Conjunto de datos
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 = {'<PAD>': 0, '<UNK>': 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]
# Codificación simple
tokens = text.lower().split()[:self.max_len]
indices = [self.vocab.get(t, 1) for t in tokens]
# Relleno
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. Modelo
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. Entrenamiento
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)
# Entrenar algunas épocas
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()
print(f"Epoch {epoch+1}, Loss: {total_loss/len(dataloader):.4f}")
print("¡Entrenamiento completado!")
6.2 Ejemplo de etiquetado de secuencias (NER)
Ejemplo
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
# Conjunto de datos de etiquetado de secuencias
class NERDataset(Dataset):
"""
Conjunto de datos de reconocimiento de entidades nombradas
Formato: [(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]
# Codificación
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]]
# Relleno
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)
}
# Modelo NER
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
# Datos de ejemplo
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")],
]
# Construir vocabulario y tabla de etiquetas
word2idx = {'<PAD>': 0, '<UNK>': 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)
print(f"Tamaño del vocabulario: {len(word2idx)}")
print(f"Número de etiquetas: {len(tag2idx)}")
7. Alternativas recomendadas
7.1 Otras bibliotecas de procesamiento de texto
| Nombre de la biblioteca | Características | Casos de uso |
|---|---|---|
| HuggingFace Datasets | Carga y procesamiento de datos | Tareas generales de NLP |
| spacy | Herramientas avanzadas de NLP | Tokenización, NER, análisis de dependencias |
| NLTK | Herramientas clásicas de NLP | Enseñanza, desarrollo de prototipos |
| textblob | Simple y fácil de usar | Procesamiento de texto rápido |
7.2 Uso de HuggingFace Datasets
Ejemplo
# pip install datasets
from datasets import load_dataset
# Cargar el conjunto de datos
# dataset = load_dataset("imdb")
# dataset = load_dataset("squad")
# Preprocesamiento de datos
# def preprocess_function(examples):
# return tokenizer(examples['text'], truncation=True, padding='max_length')
# tokenized_dataset = dataset.map(preprocess_function, batched=True)
print("Ejemplo de uso de HuggingFace Datasets:")
print("from datasets import load_dataset")
print("dataset = load_dataset('imdb')")
8. Referencia rápida de API
8.1 Operaciones comunes de procesamiento de texto
| Operación | Método |
|---|---|
| Tokenización | text.split(), spacy, nltk, jieba |
| Construcción de vocabulario | Counter, vocab.build_vocab() |
| Codificación | vocab.encode(), tokenizer.encode() |
| Decodificación | vocab.decode(), tokenizer.decode() |
| Relleno | pad_sequence, collate_fn |
| Cargar vectores de palabras | Gensim, GloVe para carga directa |
8.2 Métodos de aumento de datos
| Método | Descripción |
|---|---|
| Reemplazo de sinónimos | Reemplazar aleatoriamente palabras por sinónimos |
| Inserción aleatoria | Insertar palabras aleatoriamente |
| Eliminación aleatoria | Eliminar palabras aleatoriamente |
| Intercambio aleatorio | Intercambiar aleatoriamente la posición de las palabras |
| Retro-traducción | Traducir y luego volver a traducir |
8.3 Flujo de procesamiento de datos recomendado
1. 数据清洗 - 去除 HTML 标签、特殊字符 - 统一编码、大小写 2. 分词 - 英文: spaCy / NLTK - 中文: jieba / pkuseg 3. 词表构建 - 过滤低频词 - 设定最大词表大小 4. 序列化 - 编码为索引 - 统一长度(填充/截断) 5. 数据增强(可选) - 同义词替换、回译 6. 批量加载 - DataLoader + 自定义 collate_fnOtras extensiones