Repository navigation
Dev Notes #9
Replies: 2 comments
cosine similarity: Explanation of the doctestsCase 1: Single 1D Vectors
Case 2: Single 1D Vector vs. 2D Array (row-wise broadcast) 1D vector
Result: Case 3: Two 2D Arrays with Different Row Lengths Case 4: Two 2D Arrays with the Same Number of Rows (row-wise) Comparing each row
Result: Case 5: Two 2D Arrays (Same Rows) with In numeric form: |
Cosine similarity: Performance numpy and scipy versionsOutput of: import numpy as np
def cosine_similarity(u, v, *, cartesian_product=False):
"""
Computes the cosine similarity between two vectors or arrays of vectors.
If both inputs are 1D vectors, returns a float.
If one or both inputs are 2D arrays, returns either a 1D array (row-wise)
or a 2D array (cartesian product of rows) depending on the cartesian_product flag.
Behavior for row-wise (cartesian_product=False):
- If both arrays have the same number of rows, compares row i of u to row i of v.
- If one array has only 1 row, it is broadcast against each row of the other array.
(Returns a 1D array of length k, where k is the number of rows in the multi-row array.)
Args:
u (array-like): A single vector (1D) or a 2D array (k1 x n),
where each row is a separate vector.
v (array-like): A single vector (1D) or a 2D array (k2 x n).
cartesian_product (bool, optional):
- If False (default), the function compares rows in a one-to-one fashion (u[i] vs. v[i]),
**except** if one array has exactly 1 row and the other has multiple rows, in which case
that single row is broadcast to all rows of the other array.
- If True, computes the similarity for every combination of rows
(results in a 2D array of shape (k1, k2)).
Returns:
float or np.ndarray:
- A float if both u and v are 1D vectors.
- A 1D numpy array if either u or v is 2D and cartesian_product=False.
- A 2D numpy array if cartesian_product=True.
Raises:
ValueError:
- If the number of columns in u and v do not match.
- If cartesian_product=False, both arrays have multiple rows but differ in row count.
Examples
--------
# --- Case 1: Both are single 1D vectors
>>> u1d = [2, 0]
>>> v1d = [2, 0]
>>> cosine_similarity(u1d, v1d)
1.0
# --- Case 2: Single 1D vector vs. a 2D array (row-wise broadcast)
>>> import numpy as np
>>> M1 = np.array([
... [2, 0],
... [0, 2],
... [2, 2]
... ])
>>> res2 = cosine_similarity(u1d, M1)
>>> res2 # doctest: +ELLIPSIS
array([1. , 0. , 0.70710678...])
# --- Case 3: Two 2D arrays of different row lengths, cartesian_product=False (raises ValueError)
>>> M2_different = np.array([
... [0, 2],
... [2, 2]
... ])
>>> # Expect a ValueError because M1 has 3 rows and M2_different has 2 rows
>>> cosine_similarity(M1, M2_different, cartesian_product=False) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError: For row-wise comparison, u and v must have the same number of rows...
# --- Case 4: Two 2D arrays of the same number of rows, cartesian_product=False
>>> M2 = np.array([
... [0, 2],
... [2, 0],
... [2, 2]
... ])
>>> res4 = cosine_similarity(M1, M2, cartesian_product=False)
>>> res4
array([0., 0., 1.])
# --- Case 5: Two 2D arrays of the same size, cartesian_product=True
# (computes every combination of rows => 3 x 3)
>>> res5 = cosine_similarity(M1, M2, cartesian_product=True)
>>> np.round(res5, 3) # doctest: +NORMALIZE_WHITESPACE
array([[0. , 1. , 0.707],
[1. , 0. , 0.707],
[0.707, 0.707, 1. ]])
"""
# Convert inputs to numpy arrays
u = np.asarray(u)
v = np.asarray(v)
# --------------- CASE 1: Both are single 1D vectors ---------------
if u.ndim == 1 and v.ndim == 1:
if u.shape[0] != v.shape[0]:
raise ValueError("Vectors u and v must have the same dimension.")
dot_uv = np.dot(u, v)
norm_u = np.linalg.norm(u)
norm_v = np.linalg.norm(v)
return dot_uv / (norm_u * norm_v)
# --------------- CASE 2: At least one is 2D; ensure both are 2D ---------------
if u.ndim == 1: # shape (n,) -> (1, n)
u = u[np.newaxis, :]
if v.ndim == 1: # shape (n,) -> (1, n)
v = v[np.newaxis, :]
k1, n1 = u.shape
k2, n2 = v.shape
# Check that columns (vector dimension) match
if n1 != n2:
raise ValueError(
f"Inconsistent dimensions: u has {n1} columns, v has {n2} columns."
)
# --------------- CARTESIAN PRODUCT ---------------
if cartesian_product:
# (k1 x k2) dot products
dot_uv = u @ v.T # shape (k1, k2)
norm_u = np.linalg.norm(u, axis=1) # shape (k1,)
norm_v = np.linalg.norm(v, axis=1) # shape (k2,)
# Outer product of norms => shape (k1, k2)
denom = np.outer(norm_u, norm_v)
return dot_uv / denom
# --------------- ROW-WISE (NOT CARTESIAN) ---------------
# 1) If one array has a single row (k=1), broadcast it against each row of the other
if k1 == 1 and k2 > 1:
# Broadcast u's single row against each row in v
dot_uv = np.sum(u[0] * v, axis=1) # shape (k2,)
norm_u = np.linalg.norm(u[0]) # scalar
norm_v = np.linalg.norm(v, axis=1) # shape (k2,)
return dot_uv / (norm_u * norm_v)
if k2 == 1 and k1 > 1:
# Broadcast v's single row against each row in u
dot_uv = np.sum(u * v[0], axis=1) # shape (k1,)
norm_u = np.linalg.norm(u, axis=1) # shape (k1,)
norm_v = np.linalg.norm(v[0]) # scalar
return dot_uv / (norm_u * norm_v)
# 2) Otherwise, require the same number of rows
if k1 != k2:
raise ValueError(
f"For row-wise comparison, u and v must have the same number of rows. "
f"(u has {k1}, v has {k2})"
)
dot_uv = np.sum(u * v, axis=1) # shape (k1,)
norm_u = np.linalg.norm(u, axis=1)
norm_v = np.linalg.norm(v, axis=1)
return dot_uv / (norm_u * norm_v)
import numpy as np
from scipy.spatial.distance import cosine, cdist
def cosine_similarity_scipy(u, v, *, cartesian_product=False):
"""
Computes the cosine similarity between two vectors or arrays of vectors,
using SciPy's distance functions under the hood.
- If both inputs are 1D vectors, returns a float.
- If one or both inputs are 2D arrays, returns either a 1D array (row-wise)
or a 2D array (cartesian product of rows) depending on the
`cartesian_product` flag.
Behavior for row-wise (cartesian_product=False):
- If both arrays have the same number of rows (k), compares row i of u
with row i of v, resulting in a 1D array of length k.
- If one array has shape (1, d) and the other has shape (k, d), the single
row is broadcast to all k rows of the other array, returning a 1D array
of length k.
- Otherwise, raises a ValueError if row counts are incompatible.
Behavior for cartesian_product=True:
- Computes the similarity for every combination of rows in u and v,
returning a 2D array of shape (k1, k2).
Args:
u (array-like): A single vector (1D) or a 2D array (k1 x d),
where each row is a separate vector.
v (array-like): A single vector (1D) or a 2D array (k2 x d).
cartesian_product (bool, optional):
If True, computes a 2D matrix of size (k1, k2) for all pairs of rows.
If False, performs row-wise comparisons or broadcasting
as described above.
Returns:
float or np.ndarray:
- A float if both u and v are 1D vectors.
- A 1D NumPy array if either u or v is 2D and cartesian_product=False.
- A 2D NumPy array if cartesian_product=True.
Raises:
ValueError:
- If the number of columns (dimensions) in u and v do not match.
- If cartesian_product=False and row counts are incompatible.
Notes:
Internally, uses:
- `scipy.spatial.distance.cosine(u, v)` for single 1D vectors.
- `scipy.spatial.distance.cdist(u, v, metric="cosine")` for multi-row data,
then converts distances to similarity via `1 - distance`.
Examples
--------
>>> # Single 1D vectors
>>> u1d = [2, 0]
>>> v1d = [2, 0]
>>> cosine_similarity_scipy(u1d, v1d)
1.0
>>> # Single 1D vector vs. 2D array (row-wise broadcast)
>>> import numpy as np
>>> M1 = np.array([
... [2, 0],
... [0, 2],
... [2, 2]
... ])
>>> res2 = cosine_similarity_scipy(u1d, M1)
>>> np.round(res2, 3)
array([1. , 0. , 0.707])
>>> # Two 2D arrays of different row lengths, cartesian_product=False
>>> M2_different = np.array([
... [0, 2],
... [2, 2]
... ])
>>> # Expect a ValueError if we try row-wise with mismatched rows
>>> cosine_similarity_scipy(M1, M2_different, cartesian_product=False) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError: ...
>>> # Two 2D arrays of the same row length (row-wise)
>>> M2 = np.array([
... [0, 2],
... [2, 0],
... [2, 2]
... ])
>>> res4 = cosine_similarity_scipy(M1, M2, cartesian_product=False)
>>> res4
array([0., 0., 1.])
>>> # Cartesian product of all row pairs => (3 x 3) matrix
>>> res5 = cosine_similarity_scipy(M1, M2, cartesian_product=True)
>>> np.round(res5, 3)
array([[0. , 1. , 0.707],
[1. , 0. , 0.707],
[0.707, 0.707, 1. ]])
"""
u = np.asarray(u)
v = np.asarray(v)
# ----- CASE 1: Both are single 1D vectors -----
if u.ndim == 1 and v.ndim == 1:
if u.shape[0] != v.shape[0]:
raise ValueError("Vectors u and v must have the same dimension.")
# Cosine distance => 1 - similarity
dist = cosine(u, v)
return 1.0 - dist
# ----- CASE 2: At least one is 2D; ensure both are 2D -----
if u.ndim == 1:
u = u[np.newaxis, :] # (1, d)
if v.ndim == 1:
v = v[np.newaxis, :] # (1, d)
k1, d1 = u.shape
k2, d2 = v.shape
if d1 != d2:
raise ValueError(
f"Inconsistent dimensions: u has {d1} columns, v has {d2} columns."
)
# ----- CARTESIAN PRODUCT -----
if cartesian_product:
# cdist => shape (k1, k2)
dist_matrix = cdist(u, v, metric="cosine")
return 1.0 - dist_matrix
# ----- ROW-WISE (NOT CARTESIAN) -----
# If either array has 1 row, broadcast it against the rows of the other
if k1 == 1 and k2 > 1:
# => shape (1, k2)
dist_matrix = cdist(u, v, metric="cosine")
# flatten => shape (k2,)
return 1.0 - dist_matrix.ravel()
if k2 == 1 and k1 > 1:
# => shape (k1, 1)
dist_matrix = cdist(u, v, metric="cosine")
# flatten => shape (k1,)
return 1.0 - dist_matrix.ravel()
# Otherwise, require that k1 == k2
if k1 != k2:
raise ValueError(
f"For row-wise comparison, u and v must have the same number of rows. "
f"(u has {k1}, v has {k2})"
)
# cdist => shape (k1, k1)
dist_matrix = cdist(u, v, metric="cosine")
# Row-wise => take diagonal => shape (k1,)
diag_distances = np.diag(dist_matrix)
return 1.0 - diag_distances
import numpy as np
import timeit
def test_cosine_similarity_performance(
*,
numpy_func=cosine_similarity,
scipy_func=cosine_similarity_scipy,
repeats=5,
number=5,
verbose=True,
):
"""
Compares the performance of two cosine similarity functions (NumPy and SciPy)
under various scenarios.
Args:
numpy_func (callable): The NumPy-based cosine similarity function.
scipy_func (callable): The SciPy-based cosine similarity function.
repeats (int): How many times to repeat each timing scenario (timeit 'repeat').
number (int): How many times to run the timed operation per repeat (timeit 'number').
verbose (bool): Whether to print a summary of the results.
Returns:
dict: A nested dictionary containing timing results for each test scenario.
Example structure:
{
"single_1d": {"numpy_time": ..., "scipy_time": ...},
"one_row_vs_multi": {...},
"row_wise_equal_rows": {...},
"cartesian_product": {...}
}
"""
# ------------------------------------------------
# Test Data
# ------------------------------------------------
# 1) Single 1D vectors (dimension = 512)
u_1d = np.random.rand(512)
v_1d = np.random.rand(512)
# 2) One-row vs. multi-row (for row-wise broadcast)
# e.g. shape (1, 512) vs. shape (1000, 512)
u_one_row = np.random.rand(1, 512)
v_multi = np.random.rand(1000, 512)
# 3) Row-wise with equal rows
# e.g. shape (2000, 256) each
u_equal = np.random.rand(2000, 256)
v_equal = np.random.rand(2000, 256)
# 4) Cartesian product with moderately sized arrays
# shape (800, 256) each => result is (800 x 800) distance matrix
u_cart = np.random.rand(800, 256)
v_cart = np.random.rand(800, 256)
# ------------------------------------------------
# Helper function to measure a scenario
# ------------------------------------------------
def measure_time(stmt, globals_dict):
"""
Measures execution time of `stmt` using the timeit.repeat function,
returns the best timing out of 'repeats' repeats, each doing 'number' runs.
"""
times = timeit.repeat(stmt, repeat=repeats, number=number, globals=globals_dict)
best_time = min(times) / number # average time per run
return best_time
results = {}
# ------------------------------------------------
# Single 1D vectors
# ------------------------------------------------
globals_single_1d = {
"u": u_1d,
"v": v_1d,
"numpy_func": numpy_func,
"scipy_func": scipy_func,
}
numpy_time = measure_time("numpy_func(u, v)", globals_single_1d)
scipy_time = measure_time("scipy_func(u, v)", globals_single_1d)
results["single_1d"] = {
"numpy_time": numpy_time,
"scipy_time": scipy_time,
}
# ------------------------------------------------
# One-row vs. multi-row
# ------------------------------------------------
globals_one_vs_multi = {
"u": u_one_row,
"v": v_multi,
"numpy_func": numpy_func,
"scipy_func": scipy_func,
}
numpy_time = measure_time(
"numpy_func(u, v, cartesian_product=False)", globals_one_vs_multi
)
scipy_time = measure_time(
"scipy_func(u, v, cartesian_product=False)", globals_one_vs_multi
)
results["one_row_vs_multi"] = {
"numpy_time": numpy_time,
"scipy_time": scipy_time,
}
# ------------------------------------------------
# Row-wise with equal rows
# ------------------------------------------------
globals_equal_rows = {
"u": u_equal,
"v": v_equal,
"numpy_func": numpy_func,
"scipy_func": scipy_func,
}
numpy_time = measure_time(
"numpy_func(u, v, cartesian_product=False)", globals_equal_rows
)
scipy_time = measure_time(
"scipy_func(u, v, cartesian_product=False)", globals_equal_rows
)
results["row_wise_equal_rows"] = {
"numpy_time": numpy_time,
"scipy_time": scipy_time,
}
# ------------------------------------------------
# Cartesian product
# ------------------------------------------------
globals_cart = {
"u": u_cart,
"v": v_cart,
"numpy_func": numpy_func,
"scipy_func": scipy_func,
}
numpy_time = measure_time("numpy_func(u, v, cartesian_product=True)", globals_cart)
scipy_time = measure_time("scipy_func(u, v, cartesian_product=True)", globals_cart)
results["cartesian_product"] = {
"numpy_time": numpy_time,
"scipy_time": scipy_time,
}
if verbose:
print("\n=== Performance Comparison: NumPy vs. SciPy ===")
for scenario, times in results.items():
print(f"\nScenario: {scenario}")
print(
f" NumPy time: {times['numpy_time']:.5f} seconds/run (best of {repeats})"
)
print(
f" SciPy time: {times['scipy_time']:.5f} seconds/run (best of {repeats})"
)
return results
test_cosine_similarity_performance() |
Uh oh!
There was an error while loading. Please reload this page.
Here's to record and discuss dev notes: Design choices, performance tests, etc.
All reactions