Frechet distance距离计算原理及python实现

Frechet distance概念

在这里插入图片描述

弗雷彻距离(Frechet distance)定义了一种考虑位置和点的次序的计算两条曲线相似度的方法,常用于时间序列相似度度量和轨迹序列相似度度量。该指标的算法可用the walking dog problem来描述:想象一个人用牵引带遛狗的同时,穿过一条有限弯曲的路径,而狗则穿过一条单独的有限弯曲路径。每个人都可以改变自己的速度来放松牵引带,但都不能向后移动。则两条路径之间的Fréchet距离是牵引带的最短长度,足以让两条弯路从头到尾穿过各自的路径。
严格的数学定义为:
曲线A,B为度量空间S内的两条曲线,即 A : [ 0 , 1 ] → S A:[0,1]\rightarrow S A:[0,1]S, B : [ 0 , 1 ] → S B:[0,1]\rightarrow S B:[0,1]S α \alpha α β \beta β是单位区间的两个重采样函数, α : [ 0 , 1 ] → [ 0 , 1 ] \alpha:[0,1]\rightarrow [0,1] α[0,1][0,1]。弗雷彻距离为: F ( A , B ) = inf ⁡ α , β max ⁡ t ∈ [ 0 , 1 ] ( d ( A ( α ( t ) ) , B ( β ( t ) ) ) ) F(A,B)=\inf_{\alpha,\beta}\max_{t\in[0,1]}(d(A(\alpha(t)),B(\beta(t)))) F(A,B)=α,βinft[0,1]max(d(A(α(t)),B(β(t))))
通俗的数学定义可以简化为:
在这里插入图片描述

代码实现

基于动态规划,求两条轨迹的弗雷彻距离,具体的,将轨迹A和B每步分为三类可能的路径状态,1)A和B都向前移动一步;2)A停留原地,B向前移动一步;3)A向前移动一步,B停留原地;

import numpy as np
from scipy.spatial import distance
from scipy.spatial import minkowski_distance
from scipy.spatial.distance import euclidean
import seaborn as sns
def Frechet_distance(exp_data,num_data):
    """
    cal fs by dynamic programming
    :param exp_data: array_like, (M,N) shape represents (data points, dimensions)
    :param num_data: array_like, (M,N) shape represents (data points, dimensions)
    # e.g. P = [[2,1] , [3,1], [4,2], [5,1]]
    # Q = [[2,0] , [3,0], [4,0]]
    :return:
    """
    P=exp_data
    Q=num_data
    p_length = len(P)
    q_length = len(Q)
    distance_matrix = np.ones((p_length, q_length)) * -1

    # fill the first value with the distance between
    # the first two points in P and Q
    distance_matrix[0, 0] = euclidean(P[0], Q[0])

    # load the first column and first row with distances (memorize)
    for i in range(1, p_length):
        distance_matrix[i, 0] = max(distance_matrix[i - 1, 0], euclidean(P[i], Q[0]))
    for j in range(1, q_length):
        distance_matrix[0, j] = max(distance_matrix[0, j - 1], euclidean(P[0], Q[j]))

    for i in range(1, p_length):
        for j in range(1, q_length):
            distance_matrix[i, j] = max(
                min(distance_matrix[i - 1, j], distance_matrix[i, j - 1], distance_matrix[i - 1, j - 1]),
                euclidean(P[i], Q[j]))
    # distance_matrix[p_length - 1, q_length - 1]
    sns.heatmap(distance_matrix, annot=True)
    return distance_matrix[p_length-1,q_length-1] # 最后一步即为弗雷彻距离

在这里插入图片描述

参考资料

[1] Thomas Eiter and Heikki Mannila. Computing discrete Frechet distance. Technical report, 1994. http://www.kr.tuwien.ac.at/staff/eiter/et-archive/cdtr9464.pdf http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.90.937&rep=rep1&type=pdf
[2] similarity_measures python package
[3] https://en.wikipedia.org/wiki/Fr%C3%A9chet_distance
[4] 通俗的数学描述及动态规划求解

### 计算Fréchet Inception Distance (FID) 为了在Python实现FID的计算,通常会采用预训练好的Inception V3模型来提取图像特征向量。这些特征向量随后用于估计两组数据的真实分布和生成分布之间的差异。 #### 使用TensorFlow/Keras库加载并准备InceptionV3模型 ```python from tensorflow.keras.applications.inception_v3 import InceptionV3, preprocess_input import numpy as np def load_inception_model(): model = InceptionV3(include_top=False, pooling='avg', weights='imagenet') return model ``` 此部分代码定义了一个辅助函数`load_inception_model()`,它返回一个不带顶部全连接层且带有全局平均池化的InceptionV3实例[^2]。 #### 提取特征向量 一旦拥有了上述模型,就可以利用其处理输入图像集,并获取对应的激活值作为特征表示: ```python def get_activations(images, model): images = preprocess_input(images) preds = model.predict(images) return preds ``` 这里实现了另一个名为`get_activations()`的方法,负责接收一批标准化后的图片以及之前创建的网络结构对象,最终输出由该批次产生的预测结果——即每张图对应的一个高维实数数组。 #### 实现FID核心逻辑 最后一步涉及统计学上的操作,具体来说就是求解两个多变量正态分布间的Fréchet距离: ```python from scipy.linalg import sqrtm def calculate_fid(act1, act2): mu1, sigma1 = act1.mean(axis=0), np.cov(act1, rowvar=False) mu2, sigma2 = act2.mean(axis=0), np.cov(act2, rowvar=False) ssdiff = np.sum((mu1 - mu2)**2.0) covmean = sqrtm(sigma1.dot(sigma2)) if np.iscomplexobj(covmean): covmean = covmean.real fid_score = ssdiff + np.trace(sigma1 + sigma2 - 2.0 * covmean) return fid_score ``` 这段程序片段展示了完整的FID评分算法实现方式。给定两批样本各自的特征矩阵(act1 和 act2),先分别计算均值向量与协方差矩阵;接着基于这两个参数按照公式\[ FID=\left\| \mu _{r}-\mu _{g}\right\| ^{2}+\text {Tr }\left(\Sigma_{r}+\Sigma_{g}-2\sqrt{\Sigma_r\Sigma_g}\right)\][^1]得出两者间的确切差距得分。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值