python 实现 pairwise_l2_distances

本文介绍了一种快速、矢量化的方法来计算两个矩阵X和Y中每一行之间的L2距离,使用numpy库实现,避免了循环,提高了计算效率。

问题:
X=[—x1—⋮—xM—]M×C,Y=[—y1—⋮—yN—]N×C X = \left[\begin{array}{c} —x_1— \\ \vdots \\ —x_M— \end{array}\right]_{M\times C}, \quad Y = \left[\begin{array}{c} —y_1— \\ \vdots \\ —y_N— \end{array}\right]_{N\times C} X=x1xMM×C,Y=y1yNN×C
其中 xi,yi∈RCx_i, y_i \in R^Cxi,yiRC.
要求X,YX,YX,Y每一行之间的距离, 即S=[Sij]M×N=[∣∣xi−yj∣∣22]M×NS =\left[S_{ij}\right]_{M\times N}= \left[||x_i-y_j||_2^2\right]_{M\times N}S=[Sij]M×N=[xiyj22]M×N.


易知
Sij=∣∣xi−yj∣∣22=(xi−yj)⊤(xi−yj)=xi⊤xi−2xi⊤yj+yj⊤yj S_{ij} = ||x_i-y_j||_2^2 = (x_i-y_j)^\top(x_i-y_j) = x_i^\top x_i - 2x_i^\top y_j + y_j^\top y_j Sij=xiyj22=(xiyj)(xiyj)=xixi2xiyj+yjyj

def pairwise_l2_distances(X, Y):
    """
    A fast, vectorized way to compute pairwise l2 distances between rows in `X`
    and `Y`.
    Notes
    -----
    An entry of the pairwise Euclidean distance matrix for two vectors is
    .. math::
        d[i, j]  &=  \sqrt{(x_i - y_i) @ (x_i - y_i)} \\\\
                 &=  \sqrt{sum (x_i - y_j)^2} \\\\
                 &=  \sqrt{sum (x_i)^2 - 2 x_i y_j + (y_j)^2}
    The code below computes the the third line using numpy broadcasting
    fanciness to avoid any for loops.
    Parameters
    ----------
    X : :py:class:`ndarray <numpy.ndarray>` of shape `(N, C)`
        Collection of `N` input vectors
    Y : :py:class:`ndarray <numpy.ndarray>` of shape `(M, C)`
        Collection of `M` input vectors. If None, assume `Y` = `X`. Default is
        None.
    Returns
    -------
    dists : :py:class:`ndarray <numpy.ndarray>` of shape `(N, M)`
        Pairwise distance matrix. Entry (i, j) contains the `L2` distance between
        :math:`x_i` and :math:`y_j`.
    """
    D = -2 * X @ Y.T + np.sum(Y ** 2, axis=1) + np.sum(X ** 2, axis=1)[:, np.newaxis]
    D[D < 0] = 0  # clip any value less than 0 (a result of numerical imprecision)
    return np.sqrt(D)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颹蕭蕭

白嫖?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值