TF-IDF с scikit-learn
Векторизуйте корпус всего за несколько строк
«TF-IDF с scikit-learn» — бесплатный урок NLP Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения NLP Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс NLP Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
No Need to Hand-Code It
You understand the math, so now let scikit-learn do the heavy lifting. Its TfidfVectorizer turns raw documents into a weighted matrix in a few lines.
Import the Vectorizer
Everything lives in the feature_extraction.text module. Import TfidfVectorizer and you are ready to vectorize any list of text strings.
from sklearn.feature_extraction.text import TfidfVectorizerYour Corpus Is a List
A corpus is just a Python list of strings, one per document. Each entry is the full text you want scored and compared.
corpus = [
"the cat sat on the mat",
"the dog chased the cat",
]Fit and Transform
Call fit_transform to learn the vocabulary and compute TF-IDF in one step. It returns a sparse matrix of weighted features.
vec = TfidfVectorizer()
X = vec.fit_transform(corpus)
print(X.shape)What fit Learned
The fit step builds the vocabulary and the IDF values from your corpus. After this the vectorizer knows every term and how rare it is.
Inspect the Vocabulary
You can list the learned feature names to see the columns. get_feature_names_out shows each word in vocabulary order. 🔎
print(vec.get_feature_names_out())The Output Is Sparse
Most documents use only a few words, so the matrix is mostly zeros. scikit-learn stores it as a memory-saving sparse matrix by default.
Peek at Real Numbers
Convert a row to a dense array to actually read the weights. The fillers near zero and topic words stand out clearly.
print(X.toarray()[0].round(3))Tune With Parameters
Handy options let you drop rare or common terms instantly. Set min_df and stop_words to clean the vocabulary as you vectorize.
vec = TfidfVectorizer(stop_words="english", min_df=2)Reuse on New Text
Fit once on training data, then call transform on fresh documents. New text is mapped into the exact same vocabulary and IDF scale.
new_docs = ["a new cat appeared"]
X_new = vec.transform(new_docs)Ready for a Model
This weighted matrix plugs straight into any scikit-learn classifier. TF-IDF features are a strong, fast baseline for real text tasks.
Quick Check
Which method learns the vocabulary and computes the TF-IDF matrix together?
Recap
You imported TfidfVectorizer, fit it on a corpus, inspected the sparse output, and learned to reuse it on new text. The math is now a one-liner. ✅
Часто задаваемые вопросы
Урок «TF-IDF с scikit-learn» бесплатный?
Да — полный текст урока «TF-IDF с scikit-learn» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс NLP Academy, подпишись на CoddyKit PRO. Курс NLP Academy содержит 4 уроков всего.
Чему я научусь в уроке «TF-IDF с scikit-learn»?
Векторизуйте корпус всего за несколько строк Ты практикуешь NLP Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать NLP Academy?
Предыдущий опыт не требуется. NLP Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «TF-IDF с scikit-learn»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке NLP Academy?
Да. Каждый урок NLP Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Проблема необработанных подсчётов
- Частота терма и обратная частота документа
- TF-IDF с scikit-learn
- Поиск самых важных слов