Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
In scikit-learn, TF-IDF is computed by TfidfVectorizer, which turns a list of raw text documents into a sparse matrix of tf-idf weights in one call: TfidfVectorizer().fit_transform(corpus). The scikit-learn 1.9.1 documentation describes it as equivalent to CountVectorizer followed by TfidfTransformer. Each row of the result is one document, each column is one vocabulary term, and by default every row is L2-normalised.
What TF-IDF in scikit-learn is used for in research
Researchers use tf-idf weights to represent documents as numeric vectors before clustering abstracts, ranking documents against a query, or feeding text to a classifier. The weight of a term in a document is its frequency in that document multiplied by an inverse document frequency that down-weights terms found in many documents. For the concept itself, including a hand-worked example, see the CASRAI guide to scikit-learn for research for the general fit, transform and evaluate workflow; this page concentrates on the function-level API.
The same functionality appears under several spellings in searches (sklearn tf idf, sklearn tf-idf, tf idf sklearn). They all point at the same two classes in sklearn.feature_extraction.text: TfidfVectorizer (raw text in) and TfidfTransformer (a count matrix in).
sklearn tf-idf versus the textbook formula
The scikit-learn documentation states that tf-idf(t, d) = tf(t, d) × idf(t). With the default smooth_idf=True, idf(t) = ln[(1 + n) / (1 + df(t))] + 1, where n is the number of documents and df(t) the number of documents containing the term. With smooth_idf=False it is ln[n / df(t)] + 1. The documentation notes that the added 1 stops terms that appear in every document from being zeroed out, and that this differs from the textbook form ln[n / (1 + df)]. If you compare scikit-learn output with a hand calculation or with another package, this difference is the usual cause of mismatched numbers.
How to install or access it
The scikit-learn installation page gives pip install -U scikit-learn for Windows and macOS and pip3 install -U scikit-learn for Linux, and describes a virtual environment as optional but strongly recommended. Nothing else is needed: TfidfVectorizer ships inside the library. Import it with:
from sklearn.feature_extraction.text import TfidfVectorizer
Check sklearn.__version__ and cite the version in your methods record, because defaults and available arguments are documented per release.
Step-by-step: compute tf-idf with TfidfVectorizer
The steps below use the four-document example corpus from the official TfidfVectorizer documentation. All outputs shown were produced by running the code on scikit-learn 1.9.1.
- Prepare the corpus. A list of strings, one per document.
corpus = [ 'This is the first document.', 'This document is the second document.', 'And this is the third one.', 'Is this the first document?', ] - Create and fit the vectorizer.
vectorizer = TfidfVectorizer() X = vectorizer.fit_transform(corpus)fit_transformlearns the vocabulary and the idf values from the corpus and returns the weighted matrix. - Inspect the shape and vocabulary.
print(vectorizer.get_feature_names_out()) print(X.shape)This prints
['and' 'document' 'first' 'is' 'one' 'second' 'the' 'third' 'this']and(4, 9): four documents, nine terms. - Read the learned idf values.
dict(zip(vectorizer.get_feature_names_out(), vectorizer.idf_))With default settings,
and,one,secondandthirdeach get 1.9163,firstgets 1.5108,documentgets 1.2231, andis,theandthisget 1.0. - Score new documents without refitting.
query = vectorizer.transform(['the second document']) scores = (X @ query.T).toarray().ravel()Use
transform, notfit_transform, for any document that was not in the fitting corpus, so that it is weighted with the idf values learned from the corpus. Here the scores are 0.386, 0.867, 0.108 and 0.386 for the four documents.
Verify one number by hand
The corpus has n = 4 documents and the term document occurs in 3 of them, so with smoothing idf = ln(5/4) + 1 = 1.2231. In document 1, document appears once, so its raw weight is 1.2231; first contributes 1.5108 and is, the and this contribute 1.0 each. The vector length is the square root of 1.2231² + 1.5108² + 3 × 1.0², which is about 2.6036. Dividing gives 1.2231 / 2.6036 = 0.4698, the value scikit-learn reports for document in row 0. Doing this once on your own data is the quickest way to confirm that you understand which parameters are active.
sklearn tf idf from an existing count matrix
If you already have counts from CountVectorizer, apply TfidfTransformer(norm='l2', use_idf=True, smooth_idf=True, sublinear_tf=False) to them with fit and transform. Its documentation example uses CountVectorizer with a fixed vocabulary in a Pipeline and reports idf_ values of 1.0 for terms in every document and 1.9163 for terms in one of four.
Output and how to read it
X is a SciPy sparse matrix, so use X.toarray() only on small corpora. Each row has a unit Euclidean length under the default norm='l2'. The documentation states that the dot product of two such rows is their cosine similarity, which is why X @ X.T gives a document-by-document similarity matrix. On the example corpus it is:
| Document | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| 1 ‘This is the first document.’ | 1.000 | 0.647 | 0.308 | 1.000 |
| 2 ‘This document is the second document.’ | 0.647 | 1.000 | 0.225 | 0.647 |
| 3 ‘And this is the third one.’ | 0.308 | 0.225 | 1.000 | 0.308 |
| 4 ‘Is this the first document?’ | 1.000 | 0.647 | 0.308 | 1.000 |
Documents 1 and 4 score exactly 1.000 even though they are different sentences, because the vectorizer builds a bag of words and ignores word order, and the default lowercasing and tokenisation remove the punctuation. Treat that as a property of the representation when you interpret similarity scores. Other attributes useful for a methods record are vocabulary_ (a dictionary from term to column index) and idf_. Use inverse_transform to list the terms present in each row.
Parameters that change the numbers
The data table below lists the main TfidfVectorizer arguments with their documented defaults in scikit-learn 1.9.1. Two points trip people up. First, sublinear_tf defaults to False, so term frequency is the raw count unless you set it to True, which replaces tf with 1 + ln(tf). Second, smooth_idf defaults to True. On the example corpus, setting sublinear_tf=True, smooth_idf=False changes the idf values to 2.3863 (terms in one document), 1.6931 (first), 1.2877 (document) and 1.0, so report the settings you used. Setting use_idf=False makes idf equal to 1, leaving normalised term frequencies.
min_df, max_df and max_features
For min_df and max_df, a float is read as a proportion of documents and an integer as an absolute count. max_features keeps only the top terms ordered by term frequency across the corpus. On the example corpus, TfidfVectorizer(min_df=2) keeps document, first, is, the and this, and ngram_range=(1, 2) raises the vocabulary from 9 to 22 columns.
Troubleshooting
ValueError: empty vocabulary
The default token_pattern is r'(?u)\b\w\w+\b', which keeps only tokens of two or more word characters. Fitting on a document such as 'a b I' raises ValueError: empty vocabulary; perhaps the documents only contain stop words in scikit-learn 1.9.1. Single-character tokens (for example variable names, chemical symbols or the pronoun I) are silently dropped. Change token_pattern or supply your own tokenizer if they matter.
Stop words removed that carry meaning
Setting stop_words='english' uses a built-in list. The scikit-learn user guide warns: “Please take care in choosing a stop word list. Popular stop word lists may include words that are highly informative to some tasks, such as computer.” It also warns that a stop list can disagree with your tokenizer: “we’ve” is split into “we” and “ve”, and if “ve” is not in stop_words it is kept. Check get_stop_words() against your own tokenisation.
get_feature_names versus get_feature_names_out
Current documentation lists get_feature_names_out(). Older tutorials use get_feature_names(), which does not appear in the 1.9.1 method list, so copied code from older tutorials can fail on a current install.
Fitting on test data
Calling fit_transform on a validation or test set re-learns the vocabulary and idf from that set, so features no longer line up with the training matrix and information leaks across splits. Fit on the training documents only, then call transform on the rest. A scikit-learn Pipeline keeps this consistent during cross-validation; see the scikit-learn tutorial for the fit and evaluate pattern. If you pass the matrix on to another step that expects its own scaling, NumPy normalization explains the L2 normalisation that norm='l2' already applies.
Callable analyzers and file input
The documentation notes that since version 0.21, with input='filename' or 'file' and a callable analyzer, the data is first read from the file and then passed to the callable. If you pass a callable analyzer, check which input type you set.
Free alternatives and equivalent routes
All of these are free to use within scikit-learn itself; they are alternative ways to obtain the same weights or the underlying counts.
| Route | Input | What you get | When to use it |
|---|---|---|---|
TfidfVectorizer |
Raw text documents | Tf-idf matrix (default norm l2) | One-step pipeline from text |
CountVectorizer then TfidfTransformer |
Raw text, then counts | The same matrix, with the counts kept | You need raw counts as well as weights |
TfidfTransformer alone |
An existing count matrix | Tf-idf matrix, idf_ attribute |
Counts already built by your own tokenisation |
CountVectorizer alone |
Raw text | Term counts only | Models that expect counts |
Categorical, non-text features are handled differently; see sklearn OneHotEncoder. Bundled example text corpora are described in Scikit Learn Datasets.
Frequently asked questions
What is the difference between TfidfVectorizer and TfidfTransformer?
TfidfVectorizer takes raw text and does tokenising, counting and weighting; TfidfTransformer takes an existing count matrix and only does the weighting. The documentation describes the vectorizer as equivalent to CountVectorizer followed by TfidfTransformer.
Does sklearn use the textbook tf-idf formula?
No. By default idf = ln[(1 + n) / (1 + df)] + 1, and the result is L2-normalised. The documentation says this differs from the textbook formula.
Is sublinear tf scaling on by default?
No. sublinear_tf defaults to False in the 1.9.1 documentation.
How do I get the terms for the columns?
Call get_feature_names_out() on the fitted vectorizer; vocabulary_ gives the term-to-index mapping.
How do I vectorise a new document after fitting?
Call vectorizer.transform([text]). This uses the vocabulary and idf values learned during fitting.
Sources
- scikit-learn 1.9.1, sklearn.feature_extraction.text.TfidfVectorizer: https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html (read 2026-11-14)
- scikit-learn 1.9.1, sklearn.feature_extraction.text.TfidfTransformer: https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html (read 2026-11-14)
- scikit-learn user guide, Feature extraction (tf-idf term weighting, stop words): https://scikit-learn.org/stable/modules/feature_extraction.html (read 2026-11-14)
- scikit-learn, Installing scikit-learn: https://scikit-learn.org/stable/install.html (read 2026-11-14)
- Example outputs: computed by running the code on scikit-learn 1.9.1, 2026-11-14.
Data: TfidfVectorizer default parameters in scikit-learn 1.9.1
Selected TfidfVectorizer constructor arguments with their documented default values and effect, compiled from the scikit-learn 1.9.1 API reference for TfidfVectorizer and TfidfTransformer. Values are reproduced as stated in the signature and parameter descriptions.
| Parameter | Default | Effect of the default |
|---|---|---|
| input | 'content' | Whether documents are strings or file names/objects |
| lowercase | True | Lowercase text before tokenising |
| stop_words | None | No stop-word removal unless set (for example 'english') |
| token_pattern | (?u)\b\w\w+\b | Tokens of two or more word characters; one-character tokens are dropped |
| ngram_range | (1, 1) | Unigrams only by default |
| max_df | 1.0 | Float is a document proportion, integer a count |
| min_df | 1 | Float is a document proportion, integer a count |
| max_features | None | No cap on vocabulary size unless set |
| norm | l2 | Row vectors have unit length; row dot product equals cosine similarity |
| use_idf | True | Inverse-document-frequency weighting on |
| smooth_idf | True | idf = ln[(1+n)/(1+df)] + 1 |
| sublinear_tf | False | Raw term frequency; True uses 1 + ln(tf) |
Sources
- scikit-learn 1.9.1 TfidfVectorizer (accessed 2026-11-14)
- scikit-learn 1.9.1 TfidfTransformer (accessed 2026-11-14)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







