Datalens.ai
← All algorithms

DISTANCE

hamming

Compute the Hamming distance between two 1-D arrays.

Example of usage

Compare two named customer profiles and assert the computed score.

Domains of usage

Customer segmentation · Behavioural analytics · Similarity search

Usage / limitations

+Use when: Compare customer profiles using the hamming metric; choose it when its assumptions fit your features.

−Limitations: Feature scales, missing values and data types influence the result. Boolean metrics require binary attributes.

Mathematical formula

d(x,y) = proportion of unequal features

This metric returns a distance or similarity computed from aligned feature vectors. Interpret its scale according to the metric definition.

Sample dataShow
"{'variable': 'customer_signals', 'domain': 'Retail customer purchase behaviour', 'feature_names': ['purchased_grocery', 'purchased_electronics', 'purchased_clothing', 'purchased_furniture'], 'customer_A': {'purchased_grocery': 1, 'purchased_electronics': 0, 'purchased_clothing': 1, 'purchased_furniture': 0}, 'customer_B': {'purchased_grocery': 1, 'purchased_electronics': 1, 'purchased_clothing': 0, 'purchased_furniture': 0}}"

Code example (Python)

# DataLens.ai example
# Domain: Retail customer purchase behaviour
# Compare two labelled customer profiles using hamming.
import numpy as np

# Read the feature values in a consistent order.
left = np.array([customer_signals["customer_A"][name] for name in feature_names], dtype=bool)
right = np.array([customer_signals["customer_B"][name] for name in feature_names], dtype=bool)

# Calculate the requested distance or similarity.
from scipy.spatial.distance import hamming
result = hamming(left, right)

# Regression check against the expected result for this dataset.
observed = float(np.asarray(result).ravel()[0])
assert np.isclose(observed, 0.5, rtol=1e-8, atol=1e-9), (observed, 0.5)
print("Expected output verified")