
Vectorizacion de documentos en python
La vectorizacion de documentos en python es un paso fundamental en el preprocesamiento del lenguaje natural (NLP). Permite transformar el texto en representaciones numéricas que los algoritmos de machine learning pueden procesar. A continuación, exploramos los tres enfoques más utilizados: CountVectorizer, TF-IDF y HashingVectorizer, junto con ejemplos en Python.
CountVectorizer: representación por frecuencia de términos
Convierte un conjunto de documentos de texto en una matriz de conteo de palabras. Cada fila representa un documento, y cada columna una palabra (token) del vocabulario. El valor en la matriz representa cuántas veces aparece una palabra en ese documento. Entre las ventajas que tiene es que sencillo de implementar y tiene buena base para los modelos estadísticos.
Ejemplo en Python:
'The sun is shining',
'The weather is sweet'
'The sun is shining, the weather is sweet, and one and one is two'
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
count = CountVectorizer()
docs = np.array([
'The sun is shining',
'The weather is sweet',
'The sun is shining, the weather is sweet, and one and one is two'])
bag = count.fit_transform(docs)
print(count.vocabulary_)
print(bag.toarray())
[[0 1 0 1 1 0 1 0 0] [0 1 0 0 0 1 1 0 1]
[2 3 2 1 1 1 2 1 1]]
| Numero de frase | and | is | one | shining | sun | sweet | the | wheather | two |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0 | 1 | 0 | 1 | 1 | 0 | 1 | 0 | 0 |
| 2 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 1 |
| 3 | 2 | 3 | 2 | 1 | 1 | 1 | 2 | 1 | 1 |
Frecuencia ponderada por relevancia(TF-IDF)
Es una técnica que pondera la frecuencia de los términos teniendo en cuenta su importancia relativa. Penaliza las palabras que aparecen en muchos documentos (menos informativas) y resalta las que son más representativas en un contexto específico. Entre las ventajas que tiene es que reduce el peso de palabras muy comunes y mejora la representación semántica del documento.
Por ejemplo:
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
documento = np.array([
'The sun is shining',
'The weather is sweet',
'The sun is shining, the weather is sweet, and one and one is two'])
count = CountVectorizer()
bag = count.fit_transform(documento)
tfidf = TfidfTransformer(use_idf=True,
norm='l2',
smooth_idf=True)
np.set_printoptions(precision=2)
print(count.vocabulary_)
print(tfidf.fit_transform(bag)
.toarray())
[[0. 0.43 0. 0.56 0.56 0. 0.43 0. 0. ] [0. 0.43 0. 0. 0. 0.56 0.43 0. 0.56] [0.5 0.45 0.5 0.19 0.19 0.19 0.3 0.25 0.19]]
En este segundo ejemplo vamos a convertir una colección de filas de documentos en una matriz de td-idf caracteristicas usando TfidfVectorizer que equivale a CountVectorizer seguido por TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer import numpy as np documento = np.array([ 'The sun is shining', 'The weather is sweet', 'The sun is shining, the weather is sweet, and one and one is two']) tfidf = TfidfVectorizer(strip_accents=None, lowercase=True, preprocessor=None) np.set_printoptions(precision=2) X = tfidf.fit_transform(documento) vocabulario=tfidf.get_feature_names_out() print(vocabulario) print(X.toarray())
['and' 'is' 'one' 'shining' 'sun' 'sweet' 'the' 'two' 'weather']
[[0. 0.43 0. 0.56 0.56 0. 0.43 0. 0. ] [0. 0.43 0. 0. 0. 0.56 0.43 0. 0.56] [0.5 0.45 0.5 0.19 0.19 0.19 0.3 0.25 0.19]]
HashingVectorizer: eficiencia y escalabilidad
HashingVectorizer transforma el texto en vectores utilizando una función hash. No necesita construir un vocabulario ni almacenar todos los términos, lo que lo hace ideal para grandes volúmenes de datos o sistemas en tiempo real.
Ventajas:
- Eficiente en memoria.
- Ideal para procesamiento en streaming.
Desventajas:
- No permite acceder directamente al vocabulario.
- Posibilidad de colisiones entre tokens (aunque poco frecuente).
Ejemplo en Python:
from sklearn.feature_extraction.text import HashingVectorizer
import numpy as np
documento = np.array([
'The sun is shining',
'The weather is sweet',
'The sun is shining, the weather is sweet, and one and one is two'])
hvectorizer = HashingVectorizer(n_features=10,norm=None,alternate_sign=False)
X = hvectorizer.fit_transform(documento)
print(X.shape)
print(hvectorizer.fit_transform(documento).toarray())
(3, 10)
[[0. 0. 0. 0. 1. 1. 0. 1. 1. 0.] [1. 0. 0. 0. 0. 1. 0. 1. 1. 0.] [1. 0. 0. 0. 3. 4. 1. 3. 2. 0.]]
Comparación de Métodos
| Método | Vocabulario | Memoria eficiente | Recomendado para |
| CountVectorizer | ✅ | ❌ | Modelos básicos y exploración |
| TF-IDF | ✅ | ❌ | Modelos que priorizan relevancia |
| HashingVectorizer | ❌ | ✅ | Sistemas en producción o big data |
Conclusión
La vectorización de texto es clave para preparar los datos antes de aplicar cualquier modelo de aprendizaje automático. Elegir entre CountVectorizer, TF-IDF o HashingVectorizer depende del volumen de datos, la importancia semántica de los términos y los requisitos del sistema.


