Free browser-based ML tool

TF-IDF & Cosine Similarity Calculator

Build a TF-IDF text matrix in your browser, compare documents with cosine similarity, rank live search queries, and export term weights and heatmaps.

Free to useNo upload or sign-inRuns entirely in your browser
Live calculation
Powered by @kanaries/ml

Enter one document per line, up to 64 documents. Blank lines are ignored.

Documents
6
Vocabulary Size
54
Non-Zero Entries (nnz)
62
Matrix Sparsity
80.9%
Mean Pairwise Similarity
0.037
Most Similar Pair
D2 / D3
N-gram Range
[1, 1]

Document × document cosine similarity

D1D1D1 × D1: 1.00001.00D1 × D2: 0.00000.00D1 × D3: 0.06110.06D1 × D4: 0.00000.00D1 × D5: 0.00000.00D1 × D6: 0.00000.00D2D2D2 × D1: 0.00000.00D2 × D2: 1.00001.00D2 × D3: 0.25960.26D2 × D4: 0.00000.00D2 × D5: 0.07540.08D2 × D6: 0.00000.00D3D3D3 × D1: 0.06110.06D3 × D2: 0.25960.26D3 × D3: 1.00001.00D3 × D4: 0.00000.00D3 × D5: 0.00000.00D3 × D6: 0.00000.00D4D4D4 × D1: 0.00000.00D4 × D2: 0.00000.00D4 × D3: 0.00000.00D4 × D4: 1.00001.00D4 × D5: 0.00000.00D4 × D6: 0.16230.16D5D5D5 × D1: 0.00000.00D5 × D2: 0.07540.08D5 × D3: 0.00000.00D5 × D4: 0.00000.00D5 × D5: 1.00001.00D5 × D6: 0.00000.00D6D6D6 × D1: 0.00000.00D6 × D2: 0.00000.00D6 × D3: 0.00000.00D6 × D4: 0.16230.16D6 × D5: 0.00000.00D6 × D6: 1.00001.00

Top TF-IDF terms

TermTF-IDFIDFexamplesexamples0.3692.253featuresfeatures0.3692.253imageimage0.3692.253labeledlabeled0.3692.253learnslearns0.3692.253trainingtraining0.3692.253clusteringclustering0.3612.253editoreditor0.3612.253

Documents

Doc IDSnippetTop 3 TF-IDF keywords
D1A browser can run a machine learning model locally without sending customer data to a server.can, customer, data
D2Our search index uses TF-IDF to rank documents against a short text query.against, index, our
D3The browser search demo uses TF-IDF weights to highlight matching words in each result.demo, each, highlight
D4A neural network learns image features from labeled training examples.examples, features, image
D5Clustering groups support documents by similar vocabulary for an editor to review.clustering, editor, groups
D6For edge deployment we compress the neural network to fit the device memory budget.budget, compress, deployment

Top vocabulary IDF weights

TermDoc freqIDF weightPeak TF-IDF
examples12.25280.3690
features12.25280.3690
image12.25280.3690
labeled12.25280.3690
learns12.25280.3690
training12.25280.3690
clustering12.25280.3610
editor12.25280.3610
groups12.25280.3610
review12.25280.3610
similar12.25280.3610
support12.25280.3610
vocabulary12.25280.3610
budget12.25280.3271
compress12.25280.3271
deployment12.25280.3271
device12.25280.3271
edge12.25280.3271
fit12.25280.3271
memory12.25280.3271
import { FeatureExtraction } from '@kanaries/ml';

const docs = [
  "A browser can run a machine learning model locally without sending customer data to a server.",
  "Our search index uses TF-IDF to rank documents against a short text query.",
  "The browser search demo uses TF-IDF weights to highlight matching words in each result.",
  "A neural network learns image features from labeled training examples.",
  "Clustering groups support documents by similar vocabulary for an editor to review.",
  "For edge deployment we compress the neural network to fit the device memory budget."
];
const query = "";
const vectorizer = new FeatureExtraction.TfidfVectorizer({
  "ngramRange": [
    1,
    1
  ],
  "sublinearTf": false,
  "smoothIdf": true,
  "useIdf": true,
  "stopWords": [
    "a",
    "an",
    "and",
    "are",
    "as",
    "at",
    "be",
    "by",
    "for",
    "from",
    "in",
    "is",
    "it",
    "of",
    "on",
    "or",
    "the",
    "to",
    "with"
  ],
  "lowercase": true,
  "norm": "l2"
});
const matrix = vectorizer.fitTransform(docs).toDense();
const dot = (a, b) => a.reduce((sum, x, i) => sum + x * b[i], 0);
console.log(vectorizer.getFeatureNamesOut(), vectorizer.idf, matrix);
console.table(matrix.map(a => matrix.map(b => dot(a, b))));
if (query.trim()) {
  const [q] = vectorizer.transform([query]).toDense();
  console.table(matrix.map((row, i) => ({ doc: i + 1, score: dot(q, row) }))
    .sort((a, b) => b.score - a.score));
}

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.

Frequently asked questions

Questions about tf-idf & cosine similarity calculator

How do I compare just two documents?

Paste each passage on its own line. Read the cell at row D1 and column D2 for their cosine similarity. The Most Similar Pair card identifies the pair, and the document table shows which words carry the most weight in each passage.

Why does my query score zero for every document?

The query needs at least one retained term from the corpus. Check spelling, singular and plural forms, and the stop-word setting. Tokens shorter than two characters are dropped. Try copying a keyword directly from the document table.

Does repeating a word change its IDF?

Within a document, additional occurrences change term frequency. IDF depends on how many distinct documents contain the word. Adding it to a second document changes that count and can shift weights throughout the matrix.

Which CSV should I use for clustering?

Use the TF-IDF matrix for a clustering algorithm that expects document features. The similarity CSV supplies one score per document pair. Check whether your algorithm accepts similarities or expects distances before passing it the square matrix.

Can someone recover the documents from a shared link?

Yes. A shareable state fragment encodes the input documents, query, and settings. Anyone with that link can read the text. When the state exceeds the URL size supported by the tool, the address contains only the page location.

How are ties handled in query results?

Documents with the same computed score retain their original input order. Displayed scores are rounded, so two rows with the same displayed value can still differ slightly at full precision.

Powered by @kanaries/ml — the scikit-learn-style ML library for JavaScriptnpmGitHub