Características de N-gramas en scikit-learn
Añadir frases a su vectorizador
Características de N-gramas en scikit-learn es una lección gratuita de NLP Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de NLP Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de NLP Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Let the Library Do It
You could hand-roll n-grams, but scikit-learn builds them for you. The trick is one small argument on your vectorizer.
The ngram_range Knob
Every text vectorizer accepts ngram_range, a tuple of min and max sizes. It tells the vectorizer which n-grams to count.
from sklearn.feature_extraction.text import CountVectorizer
vec = CountVectorizer(ngram_range=(1, 2))Unigrams Are the Default
Leave it alone and ngram_range is (1, 1), pure single words. That is the plain bag-of-words you already know.
Adding Bigrams
Set ngram_range to (1, 2) and the vectorizer keeps single words and every adjacent pair, all in one feature space.
vec = CountVectorizer(ngram_range=(1, 2))
X = vec.fit_transform(["this is not good"])Bigrams Only
Want pairs alone? Use (2, 2). Now single words vanish and only bigrams survive as features.
vec = CountVectorizer(ngram_range=(2, 2))Inspect the Vocabulary
After fitting, peek at the learned features with get_feature_names_out. You will see both words and joined phrases listed.
print(vec.get_feature_names_out())
# ['is not', 'not good', 'this is']Phrases Joined by Space
scikit-learn names each bigram by joining its words with a single space, like not good. That string becomes one column.
Same Knob, TF-IDF
The same ngram_range works on TfidfVectorizer too. You get n-gram phrases that are also weighted by how distinctive they are.
from sklearn.feature_extraction.text import TfidfVectorizer
vec = TfidfVectorizer(ngram_range=(1, 2))Now Negation Survives
With bigrams on, not good lands in its own column. Your classifier can finally learn that this pair signals a negative review.
Watch the Feature Count
Adding bigrams can multiply your columns dramatically. The matrix stays sparse, but the vocabulary grows fast.
print(X.shape) # many more columns than unigrams alonePair It With min_df
To tame the blow-up, combine ngram_range with min_df. Dropping rare phrases keeps only the n-grams that repeat usefully.
vec = CountVectorizer(ngram_range=(1, 2), min_df=2)Quick Check
Which ngram_range gives you single words plus adjacent pairs in one vectorizer?
Recap: N-Grams in scikit-learn
One ngram_range tuple turns any vectorizer into an n-gram machine. Inspect features, then trim with min_df. Next you will choose the right range. 🎯
Preguntas frecuentes
¿La lección «Características de N-gramas en scikit-learn» es gratis?
Sí — el texto completo de «Características de N-gramas en scikit-learn» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de NLP Academy, actualiza a CoddyKit PRO. El curso de NLP Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Características de N-gramas en scikit-learn»?
Añadir frases a su vectorizador Practicas NLP Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar NLP Academy?
No se requiere experiencia previa. NLP Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Características de N-gramas en scikit-learn»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de NLP Academy?
Sí. Cada lección de NLP Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Por qué las palabras aisladas pierden significado
- Bigramas y trigramas explicados
- Características de N-gramas en scikit-learn
- Elección del intervalo adecuado de N-gramas