# Jaccard Similarity: Formula, and Applications

> Learn what Jaccard similarity is, understand its formula, calculate similarity with examples, and explore its applications in machine learning, NLP, and data science.

- Canonical URL: https://www.puppygraph.com/learn/jaccard-similarity
- Published: 2026-12-04
- Author: Hao Wu

Two incidents can affect some of the same services without sharing a cause. Two documents can reuse words without making the same argument. Jaccard similarity measures that overlap, giving you a reproducible starting point for comparing records, evaluating predictions, or selecting evidence for further investigation.

For an AI agent investigating recurring checkout failures, the score can help identify related incidents. The agent still needs to test explanations against dependencies and deployment history. This guide covers the formula, a worked Python calculation, machine-learning and text applications, and weighted variants, then explains how similarity can support that broader investigation.

## What is Jaccard similarity?

Jaccard similarity, also called the Jaccard index or intersection over union, measures the proportion of distinct elements shared by two sets relative to all distinct elements present in either set. For a nonempty union, its value lies between 0 and 1: 0 means no shared elements, and 1 means identical sets. This is the set comparison underlying [scikit-learn's Jaccard score](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.jaccard_score.html).

The unit of comparison depends on the task. A set might contain purchased products, document tokens, predicted labels, or services affected by an incident. Each element contributes once, regardless of how often it appears in the original records.

Consider two hypothetical incidents. Both affect checkout and payments, while each also affects a different service. Their overlap makes them candidates for comparison. It does not establish that the same deployment caused both outages, or that one incident caused the other. Jaccard describes membership overlap; interpreting that overlap requires domain evidence.

## How does Jaccard similarity work?

Start by defining what belongs in each set. In the incident example, use unique service IDs marked as affected during each incident's observation window. Keep the inclusion rule consistent: comparing confirmed failures in one incident with every warning in another changes the question before the calculation starts.

Normalize identifiers before deduplicating. If `payments-api` and `payments` name the same service, a documented mapping can reconcile them. If they are different services, merging them creates false overlap. Repeated alerts for one service still count as one member in ordinary Jaccard.

Next, form the intersection, containing members present in both sets, and the union, containing members present in either. Divide the intersection's size by the union's size. Services unaffected in both incidents contribute nothing, even if the organization operates many of them.

![Half of the services affected in either incident are shared, so Jaccard similarity is 0.5.](https://o6xswp5m6ilbks2z.public.blob.vercel-storage.com/uploads/ab8e18ef4ebebeddc0b3152c/9fc8f5ff-5072-4b58-b9e1-9aad0b122509/jaccard-similarity-figure-1-7d6b9a6555.png)

Figure: Half of the services affected in either incident are shared, so Jaccard similarity is 0.5.

Two empty sets produce a zero denominator, so software needs a convention. A set-comparison function can assign similarity 1 because the sets match; [SciPy's Jaccard distance](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.jaccard.html) assigns distance 0 to two all-zero vectors. Missing telemetry is a different condition. Preserve it as unknown instead of interpreting two failed data collections as matching empty incidents.

## Jaccard similarity formula

For finite sets (A) and (B) with a nonempty union:

\[ J(A,B)=\\frac{|A\\cap B|}{|A\\cup B|} =\\frac{|A\\cap B|}{|A|+|B|-|A\\cap B|} \]

Here, (|A|) means the number of distinct elements in (A). The second denominator subtracts the intersection because adding the two set sizes counts shared elements twice. The score is symmetric: swapping the sets leaves the answer unchanged.

Jaccard distance expresses dissimilarity:

\[ d\_J(A,B)=1-J(A,B) \]

A similarity of 0.75 therefore corresponds to a distance of 0.25. Check which quantity an API returns before sorting results: nearest matches have high similarity but low distance. SciPy's `distance.jaccard` returns the latter.

For binary features, count coordinates present in both vectors as (n\_{11}), present only in the first as (n\_{10}), and present only in the second as (n\_{01}):

\[ J=\\frac{n\_{11}}{n\_{11}+n\_{10}+n\_{01}} \]

Coordinates absent from both, (n\_{00}), are excluded. In classification language, the equivalent expression is (TP/(TP+FP+FN)). This explains why a large number of correctly absent labels cannot inflate Jaccard in the way they can inflate overall accuracy.

## How to calculate Jaccard similarity

Use these affected-service sets:

-   **Incident 17:** `checkout`, `payments`, `search`.
-   **Incident 42:** `checkout`, `payments`, `inventory`.

**Find the intersection.** Both incidents contain `checkout` and `payments`, giving two shared services.

**Find the union.** Together they contain `checkout`, `payments`, `search`, and `inventory`, giving four distinct services.

**Divide.** The result is (2/4=0.5), or 50%. Half the services appearing in either footprint appear in both. That is different from saying half of each incident's services match: each individual incident shares two of its three services.

Python's [set operations](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset) implement the calculation directly:

```python
def jaccard_similarity(left, right):
    a, b = set(left), set(right)
    union = a | b
    if not union:
        return 1.0  # Explicit convention for two empty sets.
    return len(a & b) / len(union)

incident_17 = {"checkout", "payments", "search"}
incident_42 = {"checkout", "payments", "inventory"}

print(jaccard_similarity(incident_17, incident_42))
# 0.5
```

The conversion to sets removes duplicates. Pass collections of normalized IDs; passing one raw string would compare its characters.

Boundary cases help interpret a result:

| **Comparison** | **Similarity** | **Meaning** |
| --- | --- | --- |
| `{checkout}` and `{checkout}` | 1.0 | Identical membership |
| `{checkout}` and `{inventory}` | 0.0 | No overlap |
| `{checkout}` and `{checkout, payments, search, inventory}` | 0.25 | Full containment can still produce a low score |
| Empty set and `{checkout}` | 0.0 | Only one set contains members |

There is no universal threshold for a meaningful match. Choose a threshold against reviewed examples from the intended task, and retain the shared members so someone can inspect why a pair was selected.

## Jaccard similarity in machine learning

Jaccard can serve as an input feature, a neighbor-selection rule, or an evaluation metric. These roles answer different questions.

**Recommendation and retrieval.** Represent each user by the products they interacted with, then compare those sets to find users with overlapping interests. This is a baseline for implicit-feedback data. It treats one interaction and many interactions alike, and its score alone cannot distinguish exposure, popularity, or preference.

**Multilabel evaluation.** Compare predicted and actual label sets. If the true labels are `{checkout, payments}` and the prediction is `{checkout, search}`, the score is (1/3). In scikit-learn, `average="samples"` averages per-example scores; `average="micro"` pools label decisions before calculating the score. Its `zero_division` setting controls undefined cases. Select these options deliberately when using [jaccard\_score](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.jaccard_score.html).

**Clustering and candidate generation.** Jaccard distance can group records by shared membership when the clustering method accepts that distance. Comparing every pair among (n) records requires (n(n-1)/2) comparisons. MinHash signatures and locality-sensitive hashing can reduce candidate-search work; [Spark's MinHash implementation](https://spark.apache.org/docs/latest/ml-features.html#minhash-for-jaccard-distance) operates on binary set membership. Approximate candidate selection can miss matches, so measure recall and calculate exact scores for retained pairs when needed.

For an investigating agent, finding similar incidents is one step. Given the task of explaining recurring checkout failures, it might compare service footprints, inspect a shared dependency, then reject a deployment hypothesis if the timing does not fit. Each result determines the next evidence request.

That workflow needs more than fast pairwise arithmetic. The agent needs to discover relevant relationships across the available data without copying the investigation's inputs into another store. Set retrieval latency targets according to the investigation's time budget and expected query workload. Evaluate how discovery and retrieval perform as data sources, historical coverage, and concurrent investigations grow. The expensive work can be assembling and following the evidence, even when the similarity calculation is small.

## Jaccard similarity for text similarity

Text becomes comparable only after choosing a representation. Word sets measure vocabulary overlap; character fragments can expose partial spelling overlap; word sequences preserve some local order. The resulting scores describe different kinds of similarity.

Take two short incident reports:

-   `checkout timeout after deployment`
-   `payments timeout after deployment`

Splitting on spaces gives four tokens in each set. The shared tokens are `timeout`, `after`, and `deployment`; the union adds `checkout` and `payments`. Their word-set Jaccard similarity is (3/5=0.6).

This is lexical overlap, not evidence that both reports identify the same cause. Template wording can dominate the shared tokens. Conversely, reports describing the same failure with different vocabulary can score poorly.

For near-duplicate detection, compare sets of shingles, consecutive sequences of a fixed number of tokens. [Broder and colleagues' 1997 paper](https://www.cse.iitb.ac.in/~soumen/readings/papers/BroderGMZ1997shingle2.pdf) describes this approach. Using two-word shingles here gives `{checkout timeout, timeout after, after deployment}` and `{payments timeout, timeout after, after deployment}`. Their similarity is (2/4=0.5).

Apply the same case normalization, punctuation handling, and tokenization to both inputs. Decide whether service names, error codes, and version identifiers should remain intact. Removing common words may help a particular corpus, but removing negation can destroy a meaningful distinction.

An agent can use lexical overlap to shortlist reports, then examine affected services and timestamps. Where the task requires matching paraphrases, evaluate a semantic representation as well; Jaccard over literal tokens cannot recover meaning that the representation discarded.

## Weighted Jaccard similarity explained

Ordinary Jaccard discards frequency. If repeated observations carry useful information, represent each record as a nonnegative vector with the same feature order.

A common weighted formulation replaces set intersection and union with coordinate-wise minima and maxima:

\[ J\_w(x,y)=\\frac{\\sum\_i\\min(x\_i,y\_i)}{\\sum\_i\\max(x\_i,y\_i)} \]

This is the weighted Jaccard definition used in [Sergey Ioffe's consistent sampling paper](https://storage.googleapis.com/gweb-research2023-media/pubtools/pdf/36928.pdf). It reduces to ordinary Jaccard for binary vectors. The denominator must be positive, or an explicit empty-vector policy is required.

Suppose two incident windows have alert counts across three services:

| **Service** | **Window X** | **Window Y** | **Minimum** | **Maximum** |
| --- | --- | --- | --- | --- |
| checkout | 3   | 1   | 1   | 3   |
| payments | 1   | 2   | 1   | 2   |
| search | 0   | 1   | 0   | 1   |
| **Total** | **4** | **4** | **2** | **6** |

Weighted similarity is (2/6\\approx0.333). Binary membership would give (2/3), because both windows include checkout and payments. The lower weighted score captures the different distribution of alert counts. Counts may also reflect retry behavior or monitoring configuration, so validate what the weights represent.

Another approach assigns a fixed importance weight to each feature and sums weights over the intersection and union. [SciPy's](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.jaccard.html) [`w`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.jaccard.html) [parameter](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.jaccard.html) supports this form for Boolean vectors; it does not turn arbitrary count vectors into the min/max formulation. Likewise, [scikit-learn's](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.jaccard_score.html) [`average="weighted"`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.jaccard_score.html) averages classification scores by label support. These are different operations despite sharing the word “weighted.”

## Advantages of Jaccard similarity

**Inspectable evidence.** A score can be explained by listing the shared members and the union. In the incident example, an engineer or agent can inspect checkout and payments instead of relying on a number alone.

**No reward for shared absence.** Adding unaffected services to the organization's catalog leaves the incident score unchanged. This makes Jaccard useful when observed membership matters more than the much larger universe of absent features.

**A reproducible baseline.** The calculation requires no trained model. Once identifiers, inclusion rules, and empty-set handling are fixed, the same inputs produce the same score. That makes it useful for evaluating whether a more elaborate method improves the actual task.

Its limits follow from those strengths. Membership ignores order, ordinary Jaccard ignores frequency, and a small set contained in a much larger set can receive a low score. Most importantly for investigation, overlap identifies a relationship worth examining without explaining it.

For the recurring-outage scenario, [PuppyGraph](https://www.puppygraph.com/) lets an agent follow the shared services into dependency and deployment evidence. PuppyGraph is a data engine for building AI agents across 3,000 tables and petabytes of enterprise data. It [maps existing tables](https://www.puppygraph.com/how-it-works) to a graph of entities and relationships, querying SQL databases, warehouses, and lakehouses, including direct reads of Iceberg and Delta Lake, with no data movement into a separate graph store. Its distributed engine supports [subsecond multi-hop traversal](https://www.puppygraph.com/benchmarks) on supported workloads, helping agents test successive hypotheses through openCypher and Gremlin while the same tables remain available to SQL.

![PuppyGraph queries the existing tables in place, so graph and SQL queries share one copy of the data and no pipeline keeps a graph copy in sync.](https://o6xswp5m6ilbks2z.public.blob.vercel-storage.com/uploads/ab8e18ef4ebebeddc0b3152c/313070bd-86a6-4ce7-a4f2-4bdef5d15413/ontology-vs-semantic-layer-figure-2-cdf5c9701d.png)

Figure: PuppyGraph queries the existing tables in place, so graph and SQL queries share one copy of the data and no pipeline keeps a graph copy in sync.

The built-in [AI assistant](https://docs.puppygraph.com/ai/puppygraph-ai/) proposes a model from connected tables for review and can explore related queries. Customer-built agents can inspect that model and retrieve evidence through the [MCP server](https://docs.puppygraph.com/ai/ai-integrations/), choosing which service dependencies or deployments to investigate next. With [strict schema validation](https://docs.puppygraph.com/querying/querying-using-opencypher/#strict-schema-validation) enabled, openCypher rejects queries referencing undefined entities or relationships before execution, returning feedback an agent can use to correct them.

For example, if checkout and payments converge on a recently changed dependency, the agent could test whether failures began after that change and whether unchanged services remained healthy. If those comparisons weaken the hypothesis, it could investigate another dependency or earlier incident. Jaccard supplies the initial lead; the investigation works toward a supported explanation and identifies unresolved questions.

![PuppyGraph customer logos under the heading Trusted by.](https://o6xswp5m6ilbks2z.public.blob.vercel-storage.com/uploads/ab8e18ef4ebebeddc0b3152c/0161e6d5-fefc-4a56-b64d-fa850cc35967/ontology-vs-semantic-layer-figure-5-489b45d27c.png)

![PuppyGraph customer testimonials from Trend Micro, Palo Alto Networks, Sola Security, Netskope, Coinbase, and Baker Hughes.](https://o6xswp5m6ilbks2z.public.blob.vercel-storage.com/uploads/ab8e18ef4ebebeddc0b3152c/b32dcbc5-b52c-4a2f-91f0-eb49365d9138/ontology-vs-semantic-layer-figure-6-8e4524f497.png)

## Conclusion

Jaccard similarity answers a precise question: how much of the combined membership is shared? Use it when presence and overlap match the task, define preprocessing and empty-set behavior, and choose weighted variants when magnitudes carry meaning. For agents investigating operational problems, the score helps select evidence; dependencies, timing, and counterexamples determine what that evidence supports.

Try the forever-free [PuppyGraph Developer Edition](https://www.puppygraph.com/download-confirmation) and [book a demo](https://www.puppygraph.com/book-demo) with the team to see how openCypher and Gremlin queries connect warehouse and lakehouse tables, with no graph-specific ETL, so agents can investigate the relationships behind recurring incidents.
