AI Wiki中文/EN

TF-IDF: a weighting formula is part of the model

TF-IDF

Separate count transforms, named IDF formulas, normalization and cosine; test zero vectors and reference-corpus changes.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A word repeated everywhere tells you little about where to look

Suppose an invented four-document collection contains the tokens below. A query asks for orbit satellite.

DocumentSupplied tokens
0guide orbit orbit satellite
1guide ocean tide
2guide orbit tide
3guide ocean ocean tide

guide appears in every document. satellite occurs in just one. Counting both words equally ignores a useful distinction: in this collection, observing satellite narrows the candidate documents more than observing guide does.

Term frequency–inverse document frequency, TF-IDF, combines within-document repetition with a collection-dependent weight. A term receives more inverse-document-frequency weight when it occurs in fewer reference documents. That is a weighting rule, not a proof that rarity implies meaning or relevance. A unique typo is rare too. IR book, IDF

Start from bag-of-words counts. Keep three decisions separate: how to transform a count, how to compute IDF, and whether to normalize the resulting document vector. A fourth decision chooses a score between vectors. Two systems labeled “TF-IDF” can differ in all four.

Computed pure-log and smoothed-plus-one IDF weights differ on the same five terms. The figure checks a query cosine and changes in weights after refitting the reference collection.
All IDF bars share a 0–3 scale and natural logs. A zero query follows a declared retrieval policy; these scores have no relevance labels.

Name the formula before comparing the numbers

Document frequency is a presence count

Let N be the number of reference documents, and df_t the number containing term t at least once. Repetition inside one document raises its term count c_td, but not df_t. For our sorted vocabulary [guide,ocean,orbit,satellite,tide], df is [4,2,2,1,3].

The following pure-log convention is the one on the linked IR book page:

idf⁡IR(t)=log⁡bNdf⁡t,b>1.\operatorname{idf}_{\mathrm{IR}}(t)=\log_b\frac{N}{\operatorname{df}_t},\qquad b>1.

A fitted vocabulary contains only observed terms, so df_t is positive. If the reference documents were sampled uniformly, df_t/N would be the empirical probability that a sampled document contains t. Negative log of that fraction produces this formula. It motivates a rarity weight; it is not a model of query relevance or of the probability of a word at a token position. IR book, IDF

Use natural logs unless otherwise stated. In the example, guide has IDF 0, ocean and orbit have ln2, satellite has ln4, and tide has ln(4/3). Multiplying by raw counts gives:

wtd=ctdidf⁡(t).w_{td}=c_{td}\operatorname{idf}(t).

Document 0 has unnormalized vector [0,0,2ln2,ln4,0]. Since ln4=2ln2, its orbit and satellite coordinates are equal despite their different counts. This cancellation follows from this particular collection and formula, not from a rule that the two terms are interchangeable. IR book, TF-IDF weighting

An added one changes more than numerical stability

The pinned scikit-learn default uses a different IDF; disabling its smoothing still retains an outside plus one:

idf⁡smooth(t)=ln⁡N+1df⁡t+1+1,idf⁡no smooth(t)=ln⁡Ndf⁡t+1.\operatorname{idf}_{\mathrm{smooth}}(t)=\ln\frac{N+1}{\operatorname{df}_t+1}+1,\qquad \operatorname{idf}_{\mathrm{no\ smooth}}(t)=\ln\frac{N}{\operatorname{df}_t}+1.

The default ratio can be viewed as adding one reference document containing every vocabulary term once. The outside +1 is a separate choice. A term found everywhere gets weight 1 in both of these conventions; in the pure-log convention it gets 0. Consequently, a query containing only guide disappears under pure-log IDF but survives under either plus-one variant. scikit-learn 1.7.2, weighting formulas

Here “IR-book,” “sklearn-smooth” and “sklearn-no-smooth” name explicit formulas. There is no single formula shared by everything called textbook TF-IDF. Our code also offers none, which assigns every IDF weight 1. It generalizes the IDF log base for experiments; this does not claim to be the library’s full API.

Repetition, then multiplication, then normalization

The implementation offers raw, binary and sublinear TF. For a count c:

tf⁡raw(c)=c,tf⁡binary(c)=1[c>0],tf⁡sublinear(c)={0c=0,1+ln⁡cc>0.\operatorname{tf}_{\mathrm{raw}}(c)=c,\quad \operatorname{tf}_{\mathrm{binary}}(c)=\mathbf{1}[c>0],\quad \operatorname{tf}_{\mathrm{sublinear}}(c)= \begin{cases}0&c=0,\\1+\ln c&c>0.\end{cases}

The sublinear option reduces the extra contribution from repetition while retaining a positive weight for one occurrence. In this program its log is always natural, even when the IDF experiment uses another log base. The pinned implementation places sublinear TF before IDF multiplication and row normalization. scikit-learn 1.7.2, implementation

For weighted vector w_d, L2 normalization divides every coordinate by its Euclidean length. L1 instead divides by the sum of absolute coordinate values:

w^d=wd∥wd∥2,∥wd∥2=∑twtd2,∥wd∥1=∑t∣wtd∣.\widehat w_d=\frac{w_d}{\|w_d\|_2},\qquad \|w_d\|_2=\sqrt{\sum_t w_{td}^2},\qquad \|w_d\|_1=\sum_t|w_{td}|.

These divisions require a nonzero denominator. L1-normalized nonnegative entries sum to one, but this construction alone does not make them a calibrated language probability model. L2 normalization fixes length, not the sum of entries. See norms for the geometric distinction.

With raw TF and fixed IDF, repeating every token in a nonzero document k times multiplies its weighted vector by k. L2 normalization then cancels that common factor. With sublinear TF, 1+ln(kc) is generally not a common multiple of 1+ln(c) across unequal counts, so repeating a document can change its direction. Binary TF ignores those repetitions entirely.

A query uses the same coordinates

Transform the query with the fitted vocabulary and IDF. For two nonzero vectors q and d, cosine similarity is the dot product divided by both lengths:

cos⁡(q,d)=∑tqtdt∥q∥2∥d∥2.\operatorname{cos}(q,d)=\frac{\sum_t q_td_t}{\|q\|_2\|d\|_2}.

This equals the dot product of their L2-normalized versions. A plain dot product of unnormalized vectors also responds to length. L1 normalization does not make its dot product equal cosine. IR book, dot products, equation 24

Under pure-log IDF, document 0 has normalized nonzero coordinates [1/√2,1/√2]. The query orbit satellite has coordinates [1/√5,2/√5]. Their cosine is 3/√10, about 0.948683. Before normalization their dot product is 6(ln2)². These are two different scoring definitions applied to the same example.

A zero vector has no cosine direction. Our arithmetic function returns None, not a fabricated cosine value. The retrieval wrapper then declares a policy: a zero query returns no ranking; a zero document receives retrieval score 0 for a nonzero query. Other documents with score 0 remain in the results, and ties follow original document indices. A score of zero in this result is a retrieval convention, not a theorem that the mathematical cosine exists.

The reference collection is part of the model

Add four one-token satellite documents to the reference collection and refit. N becomes 8. satellite now occurs in five documents, changing its pure-log IDF from ln4 to ln(8/5); orbit still occurs in two, so its IDF rises from ln2 to ln4. The original documents did not change, but their refitted weighted directions can change.

Keeping the old model instead keeps the old statistics. transform and rank perform no refit. In supervised learning, fit these statistics inside the training fold; in an index, document which indexed collection version supplies them. Mixing old query weights with a newly fitted document representation changes the intended scoring contract.

The IDF log base is also worth recording. For pure-log IDF, changing b multiplies every coordinate’s IDF by the same positive constant. With a fixed TF rule, this cancels under L2 normalization and cosine; a raw dot score is rescaled. With an outside +1, changing the log base does not generally produce a common scale, so directions and cosine scores can change.

Inspect every stage of a four-document retrieval

Save the complete block as tf_idf.py and run python3 tf_idf.py. It uses only the standard library; repository checks use Python 3.12.4. Each transformed document reports raw counts, pre-normalization weights, the denominator, the final vector and unknown tokens. The example uses dense lists to expose the arithmetic.

"""Original inspectable TF-IDF and retrieval experiment on supplied token lists.

Named weighting formulas are separate from tokenization, vocabulary fitting,
normalization and scoring. No scikit-learn import or claimed full API clone.
"""
from collections import Counter
import json
import math


def document(row):
    if not isinstance(row,(list,tuple)) or any(not isinstance(t,str) or not t or any(0xD800<=ord(c)<=0xDFFF for c in t) for t in row):
        raise ValueError('Supply nonempty Unicode tokens without surrogates in a list')
    return list(row)


def corpus(rows,allow_empty=False):
    if not isinstance(rows,(list,tuple)) or (not rows and not allow_empty):raise ValueError('A document collection is required')
    return [document(row) for row in rows]


def fit(reference,tf='raw',idf='sklearn-smooth',norm='l2',log_base=math.e):
    reference=corpus(reference)
    if tf not in ['raw','binary','sublinear']:raise ValueError('Choose raw, binary or sublinear TF')
    if idf not in ['ir-book','sklearn-smooth','sklearn-no-smooth','none']:raise ValueError('Choose a named IDF formula')
    if norm not in ['none','l1','l2']:raise ValueError('Choose none, l1 or l2 normalization')
    if isinstance(log_base,bool) or not isinstance(log_base,(int,float)) or not math.isfinite(log_base) or log_base<=1:raise ValueError('Finite log base greater than one required')
    df=Counter();cf=Counter()
    for row in reference:df.update(set(row));cf.update(row)
    vocabulary=tuple(sorted(df))
    if not vocabulary:raise ValueError('The reference collection has no terms')
    n=len(reference);weights=[]
    for token in vocabulary:
        if idf=='none':value=1.
        elif idf=='sklearn-smooth':value=math.log((n+1)/(df[token]+1))/math.log(log_base)+1
        else:value=math.log(n/df[token])/math.log(log_base)+int(idf=='sklearn-no-smooth')
        weights.append(value)
    return {'vocabulary':vocabulary,'index':{t:i for i,t in enumerate(vocabulary)},'idf_weights':tuple(weights),
            'document_frequency':tuple(df[t] for t in vocabulary),'collection_frequency':tuple(cf[t] for t in vocabulary),
            'reference_documents':n,'tf':tf,'idf':idf,'norm':norm,'log_base':float(log_base)}


def transform(model,rows):
    result=[]
    for row in corpus(rows,allow_empty=True):
        counts=Counter(row);raw=[counts[t] for t in model['vocabulary']];weights=[]
        for count,idf in zip(raw,model['idf_weights']):
            if count==0:tf=0.
            elif model['tf']=='binary':tf=1.
            elif model['tf']=='sublinear':tf=1+math.log(count)
            else:tf=float(count)
            weights.append(tf*idf)
        length=math.hypot(*weights) if model['norm']=='l2' else math.fsum(abs(v) for v in weights)
        denominator=length if model['norm']!='none' else 1.
        if not math.isfinite(denominator):raise ValueError('Vector norm overflow')
        vector=[v/denominator for v in weights] if denominator else weights
        zero=not any(vector);unknown={t:c for t,c in sorted(counts.items()) if t not in model['index']}
        reason=('empty_input' if not row else 'all_oov' if not any(raw) else 'zero_idf_weights') if zero else None
        result.append({'counts':raw,'weighted':weights,'vector':vector,'zero_vector':zero,'zero_reason':reason,
                       'normalizer':denominator,'oov':unknown})
    return result


def checked_vectors(a,b):
    if not isinstance(a,(list,tuple)) or not isinstance(b,(list,tuple)) or len(a)!=len(b):raise ValueError('Matching vector shapes required')
    if any(isinstance(v,bool) or not isinstance(v,(int,float)) or not math.isfinite(v) for v in [*a,*b]):raise ValueError('Finite vector entries required')


def dot(a,b):
    checked_vectors(a,b)
    try:value=math.fsum(x*y for x,y in zip(a,b))
    except OverflowError as error:raise ValueError('Dot product overflow') from error
    if not math.isfinite(value):raise ValueError('Dot product overflow')
    return value


def cosine(a,b):
    checked_vectors(a,b);na=math.hypot(*a);nb=math.hypot(*b)
    if not math.isfinite(na) or not math.isfinite(nb):raise ValueError('Vector norm overflow')
    if na==0 or nb==0:return None  # The cosine is mathematically undefined.
    return dot([v/na for v in a],[v/nb for v in b])


def rank(model,rows,query,metric='cosine'):
    if metric not in ['cosine','dot']:raise ValueError('Choose cosine or dot')
    rows=corpus(rows,allow_empty=True);query=document(query)
    q=transform(model,[query])[0];d=transform(model,rows)
    if q['zero_vector']:return {'status':'zero_query','query':q,'results':[],
                                'policy':'A zero query produces no ranking; it is not a perfectly matching query.'}
    results=[]
    for i,row in enumerate(d):
        value=cosine(q['vector'],row['vector']) if metric=='cosine' else dot(q['vector'],row['vector'])
        results.append({'document':i,'score':value if value is not None else 0.,'zero_document':row['zero_vector']})
    return {'status':'scored','query':q,'results':sorted(results,key=lambda x:(-x['score'],x['document'])),
            'policy':'Undefined zero-document cosine assigned retrieval score0; ties use original document index. No relevance labels or performance claim.'}


def describe(model):
    return {k:(list(v) if isinstance(v,tuple) else v) for k,v in model.items() if k!='index'}


def demo():
    reference=[['guide','orbit','orbit','satellite'],['guide','ocean','tide'],
               ['guide','orbit','tide'],['guide','ocean','ocean','tide']]
    query=['orbit','satellite'];variants={}
    for scheme in ['ir-book','sklearn-smooth','sklearn-no-smooth','none']:
        model=fit(reference,idf=scheme)
        variants[scheme]={'model':describe(model),'documents':transform(model,reference),
                          'ranking':rank(model,reference,query),'common_query':rank(model,reference,['guide'])}
    base=fit(reference,idf='ir-book');shifted=fit(reference+[['satellite']]*4,idf='ir-book')
    unnormalized=fit(reference,idf='ir-book',norm='none');binary=fit(reference,idf='ir-book',tf='binary')
    sublinear=fit(reference,idf='ir-book',tf='sublinear')
    return {'reference':reference,'query':query,'variants':variants,
            'dot_without_normalization':rank(unnormalized,reference,query,metric='dot'),
            'binary_documents':transform(binary,reference),'sublinear_documents':transform(sublinear,reference),
            'zero_cases':transform(base,[[],['unknownword'],['guide']]),
            'reference_shift':{'additional_documents':[['satellite']]*4,'old_idf':list(base['idf_weights']),
                               'new_idf':list(shifted['idf_weights']),'vocabulary':list(base['vocabulary']),
                               'old_model_documents':transform(base,reference),'new_model_documents':transform(shifted,reference)},
            'scope':'Original four-document collection. Raw tokens supplied; log-base affects IDF, while sublinear TF uses natural log. Reference statistics stay fixed during transform/rank. No tokenizer/API equivalence or real retrieval benchmark.'}


if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))

zero_cases deliberately separates an empty input, a document containing only unknownword, and the known common-only document guide under pure-log IDF. All three produce a zero vector, for empty_input, all_oov and zero_idf_weights respectively. A fitted collection with no observed terms is rejected, but an empty document inside an otherwise nonempty reference collection counts toward N. That policy affects IDF and must be consistent across comparisons.

The output also compares all four IDF variants, binary and sublinear TF, a raw dot ranking, and the fixed versus refitted reference collection. There are no relevance labels: the program computes scores and does not measure retrieval quality. Very large vectors can overflow a dot product; finite checks turn that into an error. math.hypot computes vector length without naively squaring each large element first, although an unrepresentably large final norm is still rejected.

Let T be the total number of reference tokens, N the reference document count and V the vocabulary size. Under expected constant-time token hashing and bounded token comparison costs, fitting takes O(T + N + V log V) work and O(V) persistent statistics, beyond the copied input. For M transformed documents with T’ total tokens, these dense vectors take O(T’ + MV) core counting/weighting work, plus sorting each document’s distinct tokens for its OOV report; the returned diagnostic arrays use O(MV) numeric entries. String lengths affect hash and comparison costs. Scoring a query against M documents takes O(MV), and sorting all scores takes O(M log M). This implementation materializes full output and is for small experiments. Sparse vectors and an inverted index can avoid inspecting every vocabulary coordinate, but they are a different implementation.

Rare is not the same as relevant

An unusual misspelling may receive high IDF; a common domain term may be essential. Synonyms can have no lexical overlap, and negation can share nearly all its vocabulary with an affirmative statement. TF-IDF changes weights but retains the information limits of the underlying bag.

Normalization controls one form of length sensitivity; it does not solve document segmentation, changing corpora, adversarial repetition or relevance calibration. Compare with binary/raw counts, a specified probabilistic retrieval method such as BM25, or semantic retrieval using fixed judgments and the same candidate set. Different methods can help with different failure cases; the four-document arithmetic does not rank their real-world quality.

A deployable retrieval experiment needs a declared reference collection, tokenizer, vocabulary pruning, exact weighting formula, normalization, score, tie policy and zero-query policy. Record all of them with the model. Reporting only “TF-IDF baseline” leaves too many reasons for two reproductions to disagree.

Change one decision at a time

1. Understanding: a word present everywhere

What happens to a query containing only guide under pure-log IDF, smoothed plus-one IDF and unsmoothed plus-one IDF?

Answer: Its pure-log weight is ln(4/4)=0, so the query vector is zero and our retrieval policy returns no ranking. Both plus-one variants give it weight 1 and produce a nonzero query. Omitting ratio smoothing does not remove the outside +1.

2. Hand calculation: a cosine you can simplify

Compute the cosine between document 0 and orbit satellite with raw TF and pure-log IDF. Compute the unnormalized dot product too.

Answer: Write a=ln2. Their nonzero weighted coordinates are [2a,2a] and [a,2a]. The dot product is 6a²; the lengths are √8 a and √5 a. Dividing gives 6/√40=3/√10, approximately 0.948683. After both L2 normalizations, their dot product equals that cosine.

3. Boundary case: empty documents in fitting

Fit pure-log IDF on [a,a,b], [a,c] and an empty document. What are N and df_a? Is [a] a zero vector? What changes if the empty reference document is removed?

Answer: N=3 and df_a=2, so a has IDF ln(3/2), and [a] is nonzero. Removing the empty document makes N=2 while df_a stays 2; a then gets IDF 0 and [a] becomes a zero vector. Empty-reference policy changes the learned statistics, even though it adds no token.

4. Transfer: new documents in an index

Four single-token satellite documents arrive. Find the new pure-log IDFs for satellite and orbit. Can you update document weights while keeping old query weights and call this the same model?

Answer: Refitting gives N=8, df_satellite=5 and df_orbit=2, hence ln(8/5) and ln4. Keeping the old model gives ln4 and ln2 instead. A consistent refitted model transforms documents and queries with the new statistics; mixing versions is a different score, requiring its own explicit definition and evaluation. Version the reference collection and weight configuration together.

Read weighting and scoring as separate choices

The linked IR sections define document frequency, a pure-log IDF, TF-IDF multiplication and cosine. The pinned scikit-learn 1.7.2 documentation and implementation specify another convention and the order of transformations. Reading both makes the otherwise hidden outside +1 visible.

The source checks cover those IR sections, cached cosine HTML lines 112–179 including equation 24, documentation lines 436–485, and implementation lines 1535–1576, 1648–1685 and 1705–1725. No library execution, full tokenizer/API equivalence, original invention claim or real retrieval benchmark is implied. The corpus, numerical comparisons and code are original.

Make a prediction, then check

A term occurs in every reference document. What are its IR-book IDF and default scikit-learn IDF?

Choose one answer

Learning objectives

  • Derive and distinguish the named IDF variants.
  • Separate TF weighting, row normalization and the scoring metric.
  • Explain three causes of a zero query vector.
  • Evaluate how reference-corpus changes affect fixed and refitted weights.

Prerequisites & connections

Explore related knowledge →

References

  1. Introduction to Information Retrieval: inverse document frequency
    Christopher D. Manning; Prabhakar Raghavan; Hinrich Schütze · 2008
  2. Introduction to Information Retrieval: tf-idf weighting
    Christopher D. Manning; Prabhakar Raghavan; Hinrich Schütze · 2008
  3. Introduction to Information Retrieval: dot products
    Christopher D. Manning; Prabhakar Raghavan; Hinrich Schütze · 2008
  4. scikit-learn 1.7.2: TF-IDF weighting
    scikit-learn contributors
  5. scikit-learn 1.7.2: TfidfTransformer implementation
    scikit-learn contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-08 · Codex single-AI-author technical check: scoped IR and pinned scikit-learn 1.7.2 definitions, six paired equations, named IDF variants, count/TF/normalization/scoring order, zero-vector and retrieval policies, cosine hand calculation, corpus and log-base changes, dense implementation complexity and four explained exercises. Original four-document data; no relevance benchmark, library execution or invention attribution.

  • Compared both languages: pure-log, smoothed-plus-one and unsmoothed-plus-one IDF, separate natural-log sublinear TF, L1/L2 and dot/cosine, empty/all-OOV/zero-IDF causes, defined retrieval zero policy, fixed/refitted reference statistics and log-base effects. Six equations and four explained exercises correspond.
  • Formal suite executes production MDX:18 original prototype checks,3 article hand/boundary/identity cases and6 publication checks. Independent cosine3/sqrt(10), raw dot6*(ln2)^2 and corpus-shift weights checked. Dense implementation and materialized diagnostic costs are stated; empty reference documents count toward N.
  • Four original SVGs bind the exact MDX results; seven figure tests check data, arithmetic, bars and bilingual references. Isolated18 language/width combinations and four fallback fonts passed after a recorded English-label repair. Actual desktop/mobile screenshots inspected. Full article browser acceptance recorded separately; no human peer review or upstream code execution.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.