Recursos de N-grams no scikit-learn
Adicione frases ao seu vetorizador.
Recursos de N-grams no scikit-learn é uma aula grátis de NLP Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de NLP Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de NLP Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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. 🎯
Perguntas Frequentes
A aula “Recursos de N-grams no scikit-learn” é grátis?
Sim — o texto completo de “Recursos de N-grams no scikit-learn” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de NLP Academy, atualize para CoddyKit PRO. O curso de NLP Academy inclui 4 aulas no total.
O que vou aprender em “Recursos de N-grams no scikit-learn”?
Adicione frases ao seu vetorizador. Você pratica NLP Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar NLP Academy?
Nenhuma experiência prévia é necessária. NLP Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Recursos de N-grams no scikit-learn”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de NLP Academy?
Sim. Cada aula de NLP Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Por que palavras isoladas perdem significado
- Bigrams e trigrams explicados
- Recursos de N-grams no scikit-learn
- Escolhendo o intervalo certo de N-grams