cosine_similarity() — langchain Function Reference
Architecture documentation for the cosine_similarity() function in vectorstores.py from the langchain codebase.
Entity Profile
Dependency Diagram
graph TD edb939a7_b329_2e7a_29d5_0bf2e63f4460["cosine_similarity()"] 22063c60_48df_f64e_d9d8_9b17dc13659a["vectorstores.py"] edb939a7_b329_2e7a_29d5_0bf2e63f4460 -->|defined in| 22063c60_48df_f64e_d9d8_9b17dc13659a 4b1eec22_ecb8_c99c_8a5f_bbe2249bd26f["maximal_marginal_relevance()"] 4b1eec22_ecb8_c99c_8a5f_bbe2249bd26f -->|calls| edb939a7_b329_2e7a_29d5_0bf2e63f4460 style edb939a7_b329_2e7a_29d5_0bf2e63f4460 fill:#6366f1,stroke:#818cf8,color:#fff
Relationship Graph
Source Code
libs/partners/chroma/langchain_chroma/vectorstores.py lines 79–106
def cosine_similarity(X: Matrix, Y: Matrix) -> np.ndarray: # type: ignore[valid-type]
"""Row-wise cosine similarity between two equal-width matrices.
Raises:
ValueError: If the number of columns in X and Y are not the same.
"""
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]:
msg = (
"Number of columns in X and Y must be the same. X has shape"
f"{X.shape} "
f"and Y has shape {Y.shape}."
)
raise ValueError(
msg,
)
X_norm = np.linalg.norm(X, axis=1)
Y_norm = np.linalg.norm(Y, axis=1)
# Ignore divide by zero errors run time warnings as those are handled below.
with np.errstate(divide="ignore", invalid="ignore"):
similarity = np.dot(X, Y.T) / np.outer(X_norm, Y_norm)
similarity[np.isnan(similarity) | np.isinf(similarity)] = 0.0
return similarity
Domain
Subdomains
Called By
Source
Frequently Asked Questions
What does cosine_similarity() do?
cosine_similarity() is a function in the langchain codebase, defined in libs/partners/chroma/langchain_chroma/vectorstores.py.
Where is cosine_similarity() defined?
cosine_similarity() is defined in libs/partners/chroma/langchain_chroma/vectorstores.py at line 79.
What calls cosine_similarity()?
cosine_similarity() is called by 1 function(s): maximal_marginal_relevance.
Analyze Your Own Codebase
Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.
Try Supermodel Free