代码实现sinkhorn算法

sinkhorn算法有很多的应用,可以计算深度学习任务中一些分布之间的距离,也可以计算最优运输问题。本篇文章的侧重点在于利用sinkhorn算法求解最优运输问题,类似于以下这个问题:有 m m m个供应商, n n n个需求商,并且已知任意两个供应商与需求商之间的运输代价 M i j M_{ij} Mij,求解运输矩阵 T T T,如果读者的需求就是这个,那么看完本文绝对能实现读者的需求,如果是处理深度学习任务中的一些度量问题,看“调用已有库部分”也能有所收获。

本文从两个路径来分享思路,第一个就是靠自己实现代码;第二个就是笔者在探索的过程中,发现了专门解决最优传输问题的库POT(Python Optimal Transport),那么第二个就是如何使用这个库来解决此问题

手写实现

整体能跑的代码如下:

import numpy as np
import matplotlib.pyplot as plt


source = np.array([0.4, 0.6])
target = np.array([0.3, 0.3, 0.4])
m = source.shape[0]
n =target.shape[0]
source = source.reshape((source.shape[0], 1))
target = target.reshape((target.shape[0], 1))


cost = np.array([[1,1,1],[2,3,4]])
gamma = 0.01
maxiters = 1000
M = np.exp(-cost / gamma)

mu = np.ones((m, 1))
nu = np.ones((n, 1))

thresh = 10 ** (-1)  # stopping criterion
last_mu = np.ones((m, 1)) * -1

for k in range(maxiters):
    mu = np.divide(source, np.dot(M, nu))
    nu = np.divide(target, np.dot(M.T, mu))
    pi = np.dot(
        np.dot(
            np.diag(mu.reshape(-1)),
            M),
        np.diag(nu.reshape(-1))
    )

    sinkhorn_distance = np.sqrt(sum(sum(np.multiply(pi, cost))))
    print(sinkhorn_distance)


print("sinkhorn distance: ", sinkhorn_distance)
print("transport matrix: ", pi)

代码分析:

source = np.array([0.4, 0.6])
target = np.array([0.3, 0.3, 0.4])
m = source.shape[0]
n =target.shape[0]
source = source.reshape((source.shape[0], 1))
target = target.reshape((target.shape[0], 1))


cost = np.array([[1,1,1],[2,3,4]])
gamma = 0.01
maxiters = 1000

这部分代码就是简单创建一下需要解决的问题,供应商向量为 [ 0.4 , 0.6 ] [0.4, 0.6] [0.4,0.6],需求商向量为 [ 0.3 , 0.3 , 0.4 ] [0.3, 0.3, 0.4] [0.3,0.3,0.4],然后分别将其转换成 m ∗ 1 m*1 m1 n ∗ 1 n*1 n1的向量。 c o s t cost cost是声明的代价矩阵, g a m m a gamma gamma是sinkhorn算法中的正则化系数, m a x i t e r s maxiters maxiters是最大的迭代次数。

然后sinkhorn算法核心就是进行迭代,具体推导细节在本文中就不进行叙述,迭代的核心就是:设 r r r为供应商向量, c c c为需求商向量,一开始将 u u u v v v初始化,然后每次按照 u = r . / K v u = r./Kv u=r./Kv, v = c . / K u v=c./Ku v=c./Ku进行迭代即可,其中 K K K是指数化处理后的代价矩阵,那核心代码如下所示:

for k in range(maxiters):
    mu = np.divide(source, np.dot(M, nu))
    nu = np.divide(target, np.dot(M.T, mu))
    pi = np.dot(
        np.dot(
            np.diag(mu.reshape(-1)),
            M),
        np.diag(nu.reshape(-1))
    )

    sinkhorn_distance = np.sqrt(sum(sum(np.multiply(pi, cost))))
    print(sinkhorn_distance)

最后运行结果如下所示:

在这里插入图片描述

调用已有库

笔者在GitHub上找各种实现的时候,找到了专门处理OT问题的python库,链接如下:

Github地址

文档地址

调用此python库来解决上面相同的问题,代码如下:

import ot
import numpy as np

a = np.array([0.4, 0.6])
b = np.array([0.3, 0.3, 0.4])

M = np.array([[1,1,1],[2,3,4]])
reg = 0.1

T = ot.emd(a, b, M) # exact linear program
T_reg = ot.sinkhorn(a, b, M, reg) # entropic regularized OT

print("T: ", T)
print("T_reg: ", T_reg)
print(np.sqrt(sum(sum(np.multiply(M, T_reg)))))

运行结果如下所示:
在这里插入图片描述

可以看到调用此库非常简单,读者对着上述代码即可知道各个参数的含义,如果读者想详细了解此库的用法,可以进行查阅。

笔者后续应该有用调用GPU来实现sinkhorn的需求,目前有两种思路,第一种就是将自己写的那部分代码改为由pytorch实现,进而调用GPU;另一种就是将库中的sinkhorn代码复制出来,将其改为由pytorch进而调用GPU实现,因为笔者暂时没看到怎么利用此库来利用GPU进行求解,并且查看库中的代码,发现代码之间的耦合性不强,实现较为简单,复制出来进行改写难度也不大。如果读者知道现成的调用GPU的方法,可以评论分享方法。笔者找到解决方案之后也会过来进行补充!

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
抱歉,作为AI语言模型,我无法直接生成代码。不过,以下是Python中使用sinkhorn算法的示例代码,供您参考: ```python import numpy as np def sinkhorn(K, r, c, reg, numItermax=1000, stopThr=1e-9): &quot;&quot;&quot; Solves the entropic regularization optimal transport problem and returns the OT matrix The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,K>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = \alpha \gamma^T 1= \beta \gamma\geq 0 where : - K: loss matrix NxM - r: row margins (sums) len(N) - c: column margins (sums) len(M) - reg: regularization term >0 - gamma: transport plan NxM - <.,.>_F : Frobenius dot product, ie <A,B>_F = \sum_i\sum_j A_{i,j}B_{i,j} - \Omega : entropy, ie \Omega(\gamma)=\sum_{i,j} \gamma_{i,j}(\log(\gamma_{i,j})-1) The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_ Parameters ---------- K : ndarray, shape (n_samples, n_features) Ground distance matrix between the two point sets. r : ndarray, shape (n_samples,) Marginal of the first point set. c : ndarray, shape (n_samples,) Marginal of the second point set. reg : float Regularization term. The higher reg, the more sparse the solution. numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) Returns ------- gamma : ndarray, shape (n_samples, n_features) Optimal transportation matrix for the given parameters &quot;&quot;&quot; assert len(r) == K.shape[0], &quot;nb of rows in K and len(r) do not match&quot; assert len(c) == K.shape[1], &quot;nb of cols in K and len(c) do not match&quot; r = np.asarray(r, dtype=np.float64) c = np.asarray(c, dtype=np.float64) K = np.asarray(K, dtype=np.float64) # init data Nini = len(r) Nfin = len(c) u = np.ones(Nini) / Nini v = np.ones(Nfin) / Nfin # print(reg) Kp = (np.exp(-reg * K)) Ktransposepy = np.dot(Kp.transpose(), y) cpt = 0 err = 1 while (err > stopThr and cpt < numItermax): uprev = u vprev = v KtransposeU = np.dot(Kp, u) v = c / KtransposeU u = r / Ktransposepy if (np.abs(u).max() > 1e9 or np.abs(v).max() > 1e9): # to avoid numerical problem # (we need to homogenize the matrix), # better to restart print('Warning: numerically unstable') reg = reg * 10 u = np.ones(Nini) / Nini v = np.ones(Nfin) / Nfin Kp = (np.exp(-reg * K)) if cpt % 10 == 0: # we can speed up the process by checking for the error only all # the 10th iterations transp = u.reshape((Nini, 1)) * Kp * v.reshape((1, Nfin)) err = np.linalg.norm(np.sum(transp, axis=1) - r) + \ np.linalg.norm(np.sum(transp, axis=0) - c) # print(&quot;err=&quot;, err, &quot;stab. coef=&quot;, np.sum(Kp * np.log(Kp / K))) cpt += 1 return u.reshape((Nini, 1)) * Kp * v.reshape((1, Nfin)) ``` 这里使用了numpy库和一些数学运算符和函数,包括矩阵乘法和范数计算。具体实现可根据您的需求进行修改。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

INEVGVUP

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值