# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: dev
#     language: python
#     name: dev
# ---

import numpy as np
from sklearn.datasets import load_iris
from sklearn.metrics.pairwise import euclidean_distances as skeuclidean_distances


def euclidean_distances(X, Y=None):
    XX = np.sum(np.square(X), axis=1)[:, np.newaxis]
    if Y is None:
        YY = XX.T
        XY = np.dot(X, X.T)
    else:
        YY = np.sum(np.square(Y), axis=1)[np.newaxis, :]
        XY = np.dot(X, Y.T)
    dist = -2 * XY + XX + YY
    dist[dist < 0] = 0
    return np.sqrt(dist)


X, _ = load_iris(return_X_y=True)
ans1 = euclidean_distances(X)
ans2 = skeuclidean_distances(X)
assert np.allclose(ans1, ans2, atol=1e-6)
ans1 = euclidean_distances(X[:100], X[100:])
ans2 = skeuclidean_distances(X[:100], X[100:], squared=False)
assert np.allclose(ans1, ans2)

StarcoderdataJupyterScriptsDedupFiltered