def _cosine_similarity()

in elasticsearch/helpers/vectorstore/_utils.py [0:0]


def _cosine_similarity(X: Matrix, Y: Matrix) -> "npt.NDArray[np.float64]":
    """Row-wise cosine similarity between two equal-width matrices."""

    try:
        import numpy as np
        import simsimd as simd
    except ModuleNotFoundError as e:
        _raise_missing_mmr_deps_error(e)

    if len(X) == 0 or len(Y) == 0:
        return np.array([])

    X = np.array(X)
    Y = np.array(Y)
    if X.shape[1] != Y.shape[1]:
        raise ValueError(
            f"Number of columns in X and Y must be the same. X has shape {X.shape} "
            f"and Y has shape {Y.shape}."
        )

    X = np.array(X, dtype=np.float32)
    Y = np.array(Y, dtype=np.float32)
    Z = 1 - np.array(simd.cdist(X, Y, metric="cosine"))
    if isinstance(Z, float):
        return np.array([Z])
    return np.array(Z)