What makes two documents look alike?
Open the Support Tickets preset and enter “SSO login” in the search box. Two customers describe different symptoms, yet both mention the same login mechanism. Their tickets rise together in the results. Select either document in the term chart to see how much of its weight belongs to those two words. Then try “identity provider” and watch the ranking change. The documents and their pairwise similarities stay fixed while the query picks out a more specific detail of one customer’s report.
TF-IDF stands for term frequency times inverse document frequency. It gives each document a row of numbers with one column for each term found in the collection. A large number means that the term accounts for a substantial part of that row after weighting and normalization. Cosine similarity compares two such rows. Reading the term weights alongside the similarity score lets you explain a match in the language of the original documents, down to the particular words both writers used.
Count occurrences and choose the document boundary
Imagine three short entries on separate lines. The first reads “battery battery case”, the second reads “battery cable”, and the third reads “case hinge”. The first row has a raw term frequency of two for battery and one for case. Cable and hinge have counts of zero there. Across the collection, battery has a document frequency of two because it occurs on two lines. Its second appearance on the first line contributes to the raw count only.
This distinction makes the choice of document boundary consequential. If each row represents a review, a review that mentions a defective hinge five times casts one vote toward the document frequency of hinge. Split that review into five lines and the same author may cast five votes. Decide whether your retrieval system should return complete reviews, paragraphs, or individual sentences, and give the calculator one such unit per line. Keep that choice consistent when comparing two sets of settings.
Calculate inverse document frequency and dampen repetition
With smoothing enabled, the inverse document frequency is log((1+n)/(1+df))+1. Here n counts all documents, df counts those containing the term, and the logarithm is natural. In the three-line example, battery receives about 1.288 and hinge receives about 1.693. A word shared by every document receives exactly one. It still contributes evidence of overlap. The vocabulary table displays this shared IDF weight once per term. Every row uses the same multiplier for that column.
Turning smoothing off gives hinge a weight of about 2.099, since its document frequency is one and the collection contains three documents. The gap between common and rare terms therefore depends on both the setting and the size of the collection. Try adding a fourth line that mentions hinge and compare its new IDF with the original. A collection of nearly identical product descriptions gives a different estimate of rarity from a collection covering many unrelated products.
Sublinear TF changes the other half of the calculation. For a positive count it uses 1 + log(tf), and an absent term keeps its zero. The two mentions of battery in the first entry now contribute about 1.693 before IDF weighting. A single mention still contributes one. In support tickets this setting can reduce the influence of an error string repeated throughout a pasted log. Inspect the document’s chart before and after toggling it to see which other terms gain relative weight.
Read cosine similarity from normalized rows
After multiplying counts by IDF, the vectorizer divides each nonempty row by its L2 norm, the square root of the sum of its squared weights. As a small arithmetic example, two weights of three and four have a norm of five and become 0.6 and 0.8. The squares of the normalized weights add up to one. This step lets a short ticket and a long ticket be compared by the proportions of evidence they assign to their terms.
Cosine similarity divides the dot product of two rows by the product of their norms. For two normalized nonzero rows that denominator is one, so adding the products of corresponding weights gives the cosine directly. Against a query containing just the second term in the arithmetic example, the score is 0.8. Only shared terms contribute products above zero. A score of one means the rows point in the same direction, which can happen even when the original wording or length differs.
Read across a heatmap row to compare a document with its neighbors. Each pair appears twice because reversing the comparison gives the same number. The mean shown above the chart counts each distinct pair once and leaves out self comparisons. A row that loses every token during filtering has zero norm. The calculator assigns zero to comparisons involving that row, including its diagonal cell. With a single document there is no pair to average.
Give a phrase its own column
With unigrams, “express shipping” contributes one feature for express and one for shipping. A review mentioning both words in another order still overlaps in both columns. Turn on bigrams and the consecutive pair “express shipping” gains a third column of its own. Search for the phrase and examine how the document table changes. The individual words still contribute, so a review sharing only shipping can retain a partial match even after you enable phrase features.
The tokenizer lowercases text and retains runs of at least two letters, numbers, or underscores. Punctuation separates tokens. The optional English stop list removes common words before pairs are formed. For example, “quality of materials” can contribute “quality materials” when filtering removes “of”. Think about what a phrase means in your application before interpreting a bigram as a literal quotation. Also check variations such as battery and batteries. These spellings occupy separate columns, so a reader may recognize a relationship that produces little lexical overlap.
Inspect sparse features and reproduce a ranking
Browser NLP often produces a wide matrix because every distinct retained term gets a column, while a short review uses only a handful of them. The JavaScript vectorizer returns a CSRMatrix in compressed sparse row format. It stores the nonzero values, the column index for each value, and offsets identifying where each row begins and ends. The nonzero count on the dashboard comes directly from that structure. Divide it by the number of possible document and term combinations to obtain density. The remaining fraction is sparsity.
This calculator expands the small feature matrix for inspection and CSV export. The pairwise result has a different shape and cost. Doubling the number of documents gives the heatmap four times as many cells even if the vocabulary stays constant. For a larger search application, a single query needs only one comparison per stored document. Fit the vectorizer on your searchable collection, keep its vocabulary and IDF, and transform incoming queries with that fitted instance. Fitting each query separately would assign new column meanings and discard the collection’s evidence about rarity.
The JavaScript and Python tabs include your documents, query, stop list, and weighting options. Run the JavaScript example with @kanaries/ml or the Python example with scikit-learn. To check parity, compare feature names first, align columns by term, and inspect the IDF of a rare term you can count by hand. Then compare its normalized weight in a particular document and the resulting query score. Use unrounded values for numerical comparisons. The heatmap rounds scores to two decimal places so neighboring cells are easy to scan, while the CSV preserves the calculated values.