AI Wiki中文/EN

Bag of words: count the words, inspect what disappears

词袋模型

Build fixed-vocabulary sparse counts, distinguish CF and DF, and test order, stop-word and unknown-feature failures.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Who is training whom?

Consider two invented sentences: nurses train pilots and pilots train nurses. Each contains one nurse-group token, one pilot-group token and the verb train. Their roles differ, but a word counter gives the same answer for both.

A bag of words represents a document by how often each vocabulary item occurs. “Bag” allows repeated items; it discards their positions. That trade lets a document become a fixed-length vector that a classifier or retrieval system can consume. It also creates distinctions no downstream model can recover from that vector alone. IR book, term frequency

This article begins with supplied token lists. Tokenization determines the units; text normalization determines which written forms merge. Neither choice is automatically part of a word counter. In our experiment, train, trains and Train are three possible features, and a supplied token containing a space is still one token.

The practical question is whether the distinctions retained by the vector are enough for a specified task. Topic classification may benefit from repeated subject words. A task about who did what needs information this unigram map removes. The example establishes an information loss, not a measured accuracy for either task.

The computed count matrix shows equal vectors for role-swapped sentences; the same bigram bag also describes two different letter sequences. CSR entry counts exceed dense cells in this tiny example.
Counts use a fixed training vocabulary. The storage comparison counts entries, not bytes; it does not measure classifier quality.

A vocabulary turns counts into coordinates

Fit the columns before transforming new text

Let the training collection contain N documents. After the declared preprocessing, choose a vocabulary of V distinct features, with a fixed feature v_j in column j. A document d_i becomes row i of the document-term matrix X:

Xij=c(vj,di),X∈N0N×V.X_{ij}=c(v_j,d_i),\qquad X\in\mathbb{N}_0^{N\times V}.

Here c counts occurrences, including repetition. A binary representation instead uses B_ij = 1 when X_ij is positive and 0 otherwise. Both are bags: neither records positions. The scikit-learn documentation separates vocabulary construction, counting and the resulting matrix; our implementation uses original code with an explicit policy. scikit-learn 1.7.2, bag of words

Use these four invented, already tokenized documents:

RowTokensarrivenursespilotsquiettraintrains
0nurses train pilots011010
1pilots train nurses011010
2pilots train pilots002010
3quiet trains arrive100101

Row 2 contains two occurrences of pilots. Its binary version has a 1 in that column. The third occurrence of train elsewhere in the collection has no effect on this row’s count.

Collection frequency CF adds occurrences across rows. Document frequency DF adds indicators of presence, so a document contributes at most one to DF:

CF⁡(v)=∑i=1Nc(v,di),DF⁡(v)=∑i=1N1[c(v,di)>0].\operatorname{CF}(v)=\sum_{i=1}^{N}c(v,d_i),\qquad \operatorname{DF}(v)=\sum_{i=1}^{N}\mathbf{1}[c(v,d_i)>0].

For the columns above, CF is [1,2,4,1,3,1] and DF is [1,2,3,1,3,1]. In particular, pilots occurs four times in three documents. In this program, min_df=2 keeps nurses, pilots and train. A separate max_features=2, with the default minimum, keeps the two largest CF values: pilots and train. A feature repeated ten times in one document still fails a two-document minimum.

Filtering uses training documents only. After fitting, column meanings remain fixed during transformation. A supervised experiment must fit the vocabulary inside each training split, including each cross-validation fold. An explicitly declared search collection can instead be the reference collection for a retrieval index. State which setting supplies the statistics before comparing results.

Sparse rows without a rectangular list of zeros

Compressed sparse row storage, or CSR, keeps three arrays. data contains nonzero counts; indices contains their column numbers; indptr marks where each row begins and ends in those arrays. For our matrix:

indptr = [0, 3, 6, 8, 11]
indices = [1, 2, 4, 1, 2, 4, 2, 4, 0, 3, 5]
data    = [1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1]

Row 2 occupies offsets 6 through 7, because its half-open interval is [indptr[2],indptr[3]) = [6,8). These entries say column 2 has value 2 and column 4 has value 1. An empty row has equal adjacent pointers and still occupies its own row number.

If K is the number of nonzero cells, a dense matrix has NV cells, while these CSR arrays contain K values, K column indices and N+1 pointers:

Sdense=NV,SCSR=2K+N+1.S_{\mathrm{dense}}=NV,\qquad S_{\mathrm{CSR}}=2K+N+1.

These are entry counts, not measured bytes. Here N=4, V=6 and K=11: CSR needs 27 entries versus 24 dense cells. With ten one-word documents and a fitted vocabulary of 1,000 words, K=10 yields 31 CSR entries versus 10,000 dense cells. Python integers, lists, vocabulary strings and index dictionaries add overhead; use an actual memory measurement and specified numeric dtypes for a byte comparison.

What a score can and cannot recover

A linear model can score a row without expanding it to V positions. For weights w_j and bias b:

s(di)=b+∑j:Xij≠0wjXij.s(d_i)=b+\sum_{j:X_{ij}\ne0}w_jX_{ij}.

Set weights to [0,2,−1,0,0.5,0] and bias to zero. Rows 0 and 1 each score 1.5; row 2 scores −1.5; row 3 scores 0. These are supplied arithmetic weights, not fitted classifier coefficients or probabilities.

Changing the weights cannot separate the first two rows. The stronger statement holds for every deterministic downstream function f using only this representation φ:

ϕ(a)=ϕ(b) ⟹ f(ϕ(a))=f(ϕ(b)).\phi(a)=\phi(b)\ \Longrightarrow\ f(\phi(a))=f(\phi(b)).

A nonlinear classifier has the same problem. To distinguish the two texts, change the available features or add another input. More layers cannot infer which of two identical inputs was originally supplied.

Local order is useful without being complete order

A bigram feature is an ordered pair of adjacent tokens; a trigram is an ordered triple. Our order=2 uses only bigrams, rather than concatenating unigram and bigram features. The two role-swapped sentences now have different pairs. This is a feature representation, not the conditional probability model in n-gram language models.

A bag of bigrams can still collide. Treat each letter as a token. abaca and acaba both contain the pairs ab, ba, ac, ca once each. Their global order differs even though all bigram counts agree. Increasing local context changes what survives; it does not make a fixed short-order bag a universal record of a sequence.

Preprocessing can introduce further collisions. If not is removed, tea not hot and tea hot become identical. Because this program removes stop words before constructing n-grams, it also creates a tea hot bigram that was not adjacent in the original first text. Neither stop-word removal nor retaining every token is universally best; choose with the task and a held-out evaluation in view.

Run the representation and inspect its losses

Save the complete block as bag_of_words.py and run python3 bag_of_words.py. It uses only the Python standard library. The repository checks use Python 3.12.4. The JSON prints the matrix above, CF and DF, sparse arrays, binary rows, supplied scores, the two order examples and the stop-word collision.

fit counts features, filters by integer document frequency, caps by descending collection frequency with lexical ties, and finally sorts selected tuples into stable column order. transform never grows the vocabulary. It reports dropped feature occurrences instead of silently adding an unknown column. Feature tuples avoid ambiguity between one supplied token a b and two tokens a, b.

"""Original sparse count-vector teaching implementation on supplied token lists.

No tokenizer, automatic lowercasing, pretrained vocabulary or hidden UNK column.
Ordered n-grams retain local adjacency but their bag still loses global order.
"""
from collections import Counter
import json
import math


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


def documents(corpus,allow_empty=False):
    if not isinstance(corpus,(list,tuple)) or (not corpus and not allow_empty):
        raise ValueError('Supply a document collection')
    return [tokens(row) for row in corpus]


def feature_counts(document,order=1,stop_words=()):
    row=tokens(document)
    if type(order) is not int or not 1<=order<=3:raise ValueError('Feature orders are1–3')
    stop=set(tokens(stop_words));kept=[word for word in row if word not in stop]
    return Counter(tuple(kept[i:i+order]) for i in range(max(0,len(kept)-order+1)))


def fit(corpus,order=1,min_df=1,max_features=None,stop_words=()):
    corpus=documents(corpus)
    if type(min_df) is not int or not 1<=min_df<=len(corpus):raise ValueError('min_df is an integer document count in1…N')
    if max_features is not None and (type(max_features) is not int or max_features<1):raise ValueError('Positive max_features or None required')
    stop=tuple(sorted(set(tokens(stop_words))));cf=Counter();df=Counter()
    for row in corpus:
        counts=feature_counts(row,order,stop);cf.update(counts);df.update(counts.keys())
    eligible=[f for f in cf if df[f]>=min_df]
    selected=sorted(eligible,key=lambda f:(-cf[f],f))[:max_features]
    vocabulary=tuple(sorted(selected))
    if not vocabulary:raise ValueError('No feature survives the declared training policy')
    return {'vocabulary':vocabulary,'index':{f:i for i,f in enumerate(vocabulary)},
            'document_frequency':tuple(df[f] for f in vocabulary),
            'collection_frequency':tuple(cf[f] for f in vocabulary),
            'training_documents':len(corpus),'order':order,'stop_words':stop,
            'min_df':min_df,'max_features':max_features}


def transform(model,corpus,binary=False):
    if type(binary) is not bool:raise ValueError('binary must be a Boolean')
    corpus=documents(corpus,allow_empty=True);indptr=[0];indices=[];data=[];unknown=[];occurrences=[]
    for row in corpus:
        counts=feature_counts(row,model['order'],model['stop_words']);items=[];missing=[]
        for feature,count in counts.items():
            if feature in model['index']:items.append((model['index'][feature],1 if binary else count))
            else:missing.append({'feature':list(feature),'occurrences':count})
        for column,value in sorted(items):indices.append(column);data.append(value)
        indptr.append(len(indices));unknown.append(sorted(missing,key=lambda x:x['feature']))
        occurrences.append(sum(counts.values()))
    return {'shape':[len(corpus),len(model['vocabulary'])],'indptr':indptr,'indices':indices,'data':data,
            'unknown_features':unknown,'generated_feature_occurrences':occurrences,'binary':binary}


def dense(matrix):
    n,d=matrix['shape'];result=[[0]*d for _ in range(n)]
    for row in range(n):
        for i in range(matrix['indptr'][row],matrix['indptr'][row+1]):
            result[row][matrix['indices'][i]]=matrix['data'][i]
    return result


def linear_scores(matrix,weights,bias=0.):
    if not isinstance(weights,(tuple,list)) or len(weights)!=matrix['shape'][1]:raise ValueError('One weight per vocabulary column required')
    if any(isinstance(v,bool) or not isinstance(v,(int,float)) or not math.isfinite(v) for v in [*weights,bias]):raise ValueError('Finite scalar weights and bias required')
    scores=[]
    for row in range(matrix['shape'][0]):
        try:score=math.fsum([bias]+[weights[matrix['indices'][i]]*matrix['data'][i] for i in range(matrix['indptr'][row],matrix['indptr'][row+1])])
        except OverflowError as error:raise ValueError('Linear score overflow') from error
        if not math.isfinite(score):raise ValueError('Linear score overflow')
        scores.append(score)
    return scores


def storage_counts(matrix):
    n,d=matrix['shape'];nnz=len(matrix['data'])
    return {'dense_cells':n*d,'nonzero_cells':nnz,'csr_numeric_entries':2*nnz+n+1,
            'density':nnz/(n*d) if n*d else 0.,
            'scope':'Entry counts only; Python object overhead and vocabulary storage are not bytes measured here.'}


def demo():
    train=[['nurses','train','pilots'],['pilots','train','nurses'],['pilots','train','pilots'],['quiet','trains','arrive']]
    model=fit(train);matrix=transform(model,train);binary=transform(model,train,binary=True)
    weights=[{'nurses':2.,'pilots':-1.,'train':.5}.get(f[0],0.) for f in model['vocabulary']]
    bigram=fit(train,order=2)
    # The same multiset of directed bigrams can still form different sequences.
    walks=[list('abaca'),list('acaba')];walk_model=fit(walks,order=2)
    stop_examples=[['tea','not','hot'],['tea','hot']]
    stop_model=fit(stop_examples,stop_words=('not',))
    pruned=fit(train,max_features=2)
    return {'training':train,'vocabulary':[list(f) for f in model['vocabulary']],
            'document_frequency':list(model['document_frequency']),'collection_frequency':list(model['collection_frequency']),
            'counts':matrix,'dense_counts':dense(matrix),'binary_counts':dense(binary),'storage':storage_counts(matrix),
            'linear_weights':weights,'linear_scores':linear_scores(matrix,weights),
            'unigram_role_swap_equal':dense(matrix)[0]==dense(matrix)[1],
            'bigram_role_swap_equal':dense(transform(bigram,train[:2]))[0]==dense(transform(bigram,train[:2]))[1],
            'bigram_walk_collision':{'sequences':walks,'vocabulary':[list(f) for f in walk_model['vocabulary']],
                                     'counts':dense(transform(walk_model,walks))},
            'stopword_collision':{'documents':stop_examples,'stop_words':['not'],'counts':dense(transform(stop_model,stop_examples))},
            'held_out':transform(model,[['nurses','newword','newword'],[],['Nurses']]),
            'pruned_vocabulary':[list(f) for f in pruned['vocabulary']],
            'scope':'Original tiny supplied token lists, deterministic training-only vocabulary and CSR entry counts. No classifier fitting, tokenizer or retrieval-quality benchmark.'}


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

The held-out row ['nurses','newword','newword'] has only one stored count and reports two unknown occurrences. [] produces a zero row; ['Nurses'] also produces a zero row, but reports an unknown capitalized token. These zero rows have different causes. For count mode, each document obeys a useful accounting identity:

∑jXij+Ui=Gi,\sum_jX_{ij}+U_i=G_i,

where U_i counts discarded out-of-vocabulary feature occurrences and G_i counts generated occurrences after preprocessing. The identity does not hold with binary values when a known feature repeats: binary presence intentionally forgets that multiplicity.

For a fixed n-gram order at most three, let T be the total number of input tokens, F the number of distinct training features and k_i the number of distinct retained features in row i. For a fixed stop-word list, under expected constant-time hash operations and treating bounded token comparisons as unit work, fitting takes O(T + N + F log F): the sort determines the cap and column order. Transformation also sorts each row’s retained and unknown features. If u_i is the number of distinct unknown features, its work is O(T + Σ_i(k_i log k_i + u_i log u_i)); the returned sparse arrays use O(K+N) entries, and the unknown-feature reports consume additional storage. String hashing/comparison costs grow with token length, so the unit-cost model must not be read as a character-level bound.

This inspectable implementation copies token collections and retains diagnostic reports. It is not a streaming memory design. dense deliberately allocates NV cells; call it only for small displays. Scoring the sparse matrix takes O(K+N) arithmetic work. The code checks finite weights and reports numerical overflow instead of presenting infinity as a valid score.

The representation chooses which errors are possible

The vocabulary can grow sharply with n-grams, and new text can contain many discarded features. A stable vocabulary makes models compatible across calls but needs versioning when refitted. Persist its column order and preprocessing policy together with any learned weights.

Raw counts favor repetition in an unnormalized linear score. Binary counts remove multiplicity; TF-IDF adds corpus-dependent weights. Neither weighting restores lost syntax. Character features may help with spelling variation; sequence representations can retain order; both change the problem and need their own evaluation.

The numerical example verifies representation behavior. It contains no labels, fitted classifier, retrieval judgments or corpus-level quality benchmark. For a real comparison, keep data splits fixed, inspect negation and role reversals separately, and count unknown features alongside the chosen task metric. A good average score can hide exactly the distinction the task depends on.

Predict the row before running it

1. Basic understanding: repetition and presence

What changes when row 2 becomes binary? Does its DF contribution for pilots change?

Answer: Its pilots value changes from 2 to 1; the train value remains 1. Its DF contribution was already one and remains one. In this implementation binary transformation does not refit the vocabulary or change the training CF used by a feature cap.

2. Hand calculation: reconstruct CSR

Use the arrays above to recover row 3 and its supplied linear score. Why does the tiny CSR representation have more entries than the dense one?

Answer: Pointers 8 and 11 select columns [0,3,5] with values [1,1,1], giving [1,0,0,1,0,1]. All three supplied weights are zero, so the score is zero. CSR stores both indices and values plus five pointers: 11+11+5=27, compared with 4×6=24 dense cells. This does not measure Python memory bytes.

3. Counterexample: more local order

List the bigrams of abaca and acaba. Can a deterministic classifier using only their bigram bags label the two strings differently?

Answer: The first order is ab, ba, ac, ca; the second is ac, ca, ab, ba. Each bag has the same four counts. The classifier receives identical vectors, so it cannot separate them without another input. The fact that bigrams separated the earlier role swap does not establish complete order preservation.

4. Transfer: an unseen term in validation

A validation document contains nurses newword newword. Should you refit the vocabulary on it to eliminate the two unknown occurrences? What would you log?

Answer: In the stated supervised validation setup, keep the training vocabulary fixed. Refitting would change the experiment’s feature selection using held-out data and could change column meanings. Log one retained count, two discarded occurrences, the preprocessing version and the task outcome. A later intentional refit must produce a new vocabulary/model version and a fresh evaluation; it is a separate operation from transforming this document.

Read the representation before borrowing an API

The IR book explains why term counts omit order. The pinned scikit-learn section shows how a vocabulary yields a document-term matrix and why sparse storage matters. These readings support the representation, not a claim that our original functions reproduce that library’s tokenizer, pruning API or memory behavior.

All sentences, count tables, supplied weights, collision examples and code here are original teaching material. The source review covers the linked IR section and scikit-learn document lines 244–297. It does not include executing scikit-learn or adopting the documentation’s corpus-scale sparsity figures.

Make a prediction, then check

Two texts have identical unigram vectors but different labels. Can a deterministic classifier using only those vectors separate them?

Choose one answer

Learning objectives

  • Construct a fixed vocabulary and distinguish collection from document frequency.
  • Reconstruct count rows from CSR pointers, indices and values.
  • Prove which sentence distinctions a chosen feature map removes.
  • Audit stop-word, n-gram, unknown-feature and storage policies.

Prerequisites & connections

Explore related knowledge →

References

  1. Introduction to Information Retrieval: term frequency and weighting
    Christopher D. Manning; Prabhakar Raghavan; Hinrich Schütze · 2008
  2. scikit-learn 1.7.2: the bag of words representation
    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/scikit-learn count representation, six paired equations, fixed training vocabulary, CF versus DF, CSR reconstruction and entry-not-byte comparison, deterministic representation collisions, explicit preprocessing/OOV policies, bounded hashing/string-cost complexity and four explained exercises. Original supplied documents and weights; not classifier quality or library execution. Production browser acceptance recorded separately.

  • Compared both languages and program: complete 4×6 matrix, CF/DF, fixed training-only vocabulary, binary multiplicity, stop-before-ngram adjacency, unknown-feature accounting, arbitrary deterministic functions on identical vectors and the abaca/acaba bigram collision. 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. Sparse storage compares27 entries with24 dense cells, not bytes. Complexity includes empty-document traversal and explicit fixed-stop-list/string-cost assumptions.
  • 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.