-
Notifications
You must be signed in to change notification settings - Fork 508
/
Copy pathda.py
2633 lines (2117 loc) · 93.6 KB
/
da.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Domain adaptation with optimal transport
"""
# Author: Remi Flamary <[email protected]>
# Nicolas Courty <[email protected]>
# Michael Perrot <[email protected]>
# Nathalie Gayraud <[email protected]>
# Ievgen Redko <[email protected]>
#
# License: MIT License
import numpy as np
from .backend import get_backend
from .bregman import sinkhorn, jcpot_barycenter
from .lp import emd
from .utils import unif, dist, kernel, cost_normalization, label_normalization, laplacian, dots
from .utils import list_to_array, check_params, BaseEstimator, deprecated
from .unbalanced import sinkhorn_unbalanced
from .gaussian import empirical_bures_wasserstein_mapping, empirical_gaussian_gromov_wasserstein_mapping
from .optim import cg
from .optim import gcg
def sinkhorn_lpl1_mm(a, labels_a, b, M, reg, eta=0.1, numItermax=10,
numInnerItermax=200, stopInnerThr=1e-9, verbose=False,
log=False):
r"""
Solve the entropic regularization optimal transport problem with non-convex
group lasso regularization
The function solves the following optimization problem:
.. math::
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
\mathrm{reg} \cdot \Omega_e(\gamma) + \eta \ \Omega_g(\gamma)
s.t. \ \gamma \mathbf{1} = \mathbf{a}
\gamma^T \mathbf{1} = \mathbf{b}
\gamma \geq 0
where :
- :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix
- :math:`\Omega_e` is the entropic regularization term :math:`\Omega_e
(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`\Omega_g` is the group lasso regularization term
:math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^{1/2}_1`
where :math:`\mathcal{I}_c` are the index of samples from class `c`
in the source domain.
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalized conditional
gradient as proposed in :ref:`[5, 7] <references-sinkhorn-lpl1-mm>`.
Parameters
----------
a : array-like (ns,)
samples weights in the source domain
labels_a : array-like (ns,)
labels of samples in the source domain
b : array-like (nt,)
samples weights in the target domain
M : array-like (ns,nt)
loss matrix
reg : float
Regularization term for entropic regularization >0
eta : float, optional
Regularization term for group lasso regularization >0
numItermax : int, optional
Max number of iterations
numInnerItermax : int, optional
Max number of iterations (inner sinkhorn solver)
stopInnerThr : float, optional
Stop threshold on error (inner sinkhorn solver) (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns, nt) array-like
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
.. _references-sinkhorn-lpl1-mm:
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
"Optimal Transport for Domain Adaptation," in IEEE
Transactions on Pattern Analysis and Machine Intelligence ,
vol.PP, no.99, pp.1-1
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
Generalized conditional gradient: analysis of convergence
and applications. arXiv preprint arXiv:1510.06567.
See Also
--------
ot.lp.emd : Unregularized OT
ot.bregman.sinkhorn : Entropic regularized OT
ot.optim.cg : General regularized OT
"""
a, labels_a, b, M = list_to_array(a, labels_a, b, M)
nx = get_backend(a, labels_a, b, M)
p = 0.5
epsilon = 1e-3
indices_labels = []
classes = nx.unique(labels_a)
for c in classes:
idxc, = nx.where(labels_a == c)
indices_labels.append(idxc)
W = nx.zeros(M.shape, type_as=M)
for cpt in range(numItermax):
Mreg = M + eta * W
if log:
transp, log = sinkhorn(a, b, Mreg, reg, numItermax=numInnerItermax,
stopThr=stopInnerThr, log=True)
else:
transp = sinkhorn(a, b, Mreg, reg, numItermax=numInnerItermax,
stopThr=stopInnerThr)
# the transport has been computed. Check if classes are really
# separated
W = nx.ones(M.shape, type_as=M)
for (i, c) in enumerate(classes):
majs = nx.sum(transp[indices_labels[i]], axis=0)
majs = p * ((majs + epsilon) ** (p - 1))
W[indices_labels[i]] = majs
if log:
return transp, log
else:
return transp
def sinkhorn_l1l2_gl(a, labels_a, b, M, reg, eta=0.1, numItermax=10,
numInnerItermax=200, stopInnerThr=1e-9, eps=1e-12,
verbose=False, log=False):
r"""
Solve the entropic regularization optimal transport problem with group
lasso regularization
The function solves the following optimization problem:
.. math::
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
\mathrm{reg} \cdot \Omega_e(\gamma) + \eta \ \Omega_g(\gamma)
s.t. \ \gamma \mathbf{1} = \mathbf{a}
\gamma^T \mathbf{1} = \mathbf{b}
\gamma \geq 0
where :
- :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix
- :math:`\Omega_e` is the entropic regularization term
:math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`\Omega_g` is the group lasso regularization term
:math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^2`
where :math:`\mathcal{I}_c` are the index of samples from class
`c` in the source domain.
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalized conditional
gradient as proposed in :ref:`[5, 7] <references-sinkhorn-l1l2-gl>`.
Parameters
----------
a : array-like (ns,)
samples weights in the source domain
labels_a : array-like (ns,)
labels of samples in the source domain
b : array-like (nt,)
samples in the target domain
M : array-like (ns,nt)
loss matrix
reg : float
Regularization term for entropic regularization >0
eta : float, optional
Regularization term for group lasso regularization >0
numItermax : int, optional
Max number of iterations
numInnerItermax : int, optional
Max number of iterations (inner sinkhorn solver)
stopInnerThr : float, optional
Stop threshold on error (inner sinkhorn solver) (>0)
eps: float, optional (default=1e-12)
Small value to avoid division by zero
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns, nt) array-like
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
.. _references-sinkhorn-l1l2-gl:
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
"Optimal Transport for Domain Adaptation," in IEEE Transactions
on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
Generalized conditional gradient: analysis of convergence and
applications. arXiv preprint arXiv:1510.06567.
See Also
--------
ot.optim.gcg : Generalized conditional gradient for OT problems
"""
a, labels_a, b, M = list_to_array(a, labels_a, b, M)
nx = get_backend(a, labels_a, b, M)
labels_u, labels_idx = nx.unique(labels_a, return_inverse=True)
n_labels = labels_u.shape[0]
unroll_labels_idx = nx.eye(n_labels, type_as=labels_u)[None, labels_idx]
def f(G):
G_split = nx.repeat(G.T[:, :, None], n_labels, axis=2)
return nx.sum(nx.norm(G_split * unroll_labels_idx, axis=1))
def df(G):
G_split = nx.repeat(G.T[:, :, None], n_labels, axis=2) * unroll_labels_idx
W = nx.norm(G_split * unroll_labels_idx, axis=1, keepdims=True)
G_norm = G_split / nx.clip(W, eps, None)
return nx.sum(G_norm, axis=2).T
return gcg(a, b, M, reg, eta, f, df, G0=None, numItermax=numItermax,
numInnerItermax=numInnerItermax, stopThr=stopInnerThr,
verbose=verbose, log=log)
def joint_OT_mapping_linear(xs, xt, mu=1, eta=0.001, bias=False, verbose=False,
verbose2=False, numItermax=100, numInnerItermax=10,
stopInnerThr=1e-6, stopThr=1e-5, log=False,
**kwargs):
r"""Joint OT and linear mapping estimation as proposed in
:ref:`[8] <references-joint-OT-mapping-linear>`.
The function solves the following optimization problem:
.. math::
\min_{\gamma,L}\quad \|L(\mathbf{X_s}) - n_s\gamma \mathbf{X_t} \|^2_F +
\mu \langle \gamma, \mathbf{M} \rangle_F + \eta \|L - \mathbf{I}\|^2_F
s.t. \ \gamma \mathbf{1} = \mathbf{a}
\gamma^T \mathbf{1} = \mathbf{b}
\gamma \geq 0
where :
- :math:`\mathbf{M}` is the (`ns`, `nt`) squared euclidean cost matrix between samples in
:math:`\mathbf{X_s}` and :math:`\mathbf{X_t}` (scaled by :math:`n_s`)
- :math:`L` is a :math:`d\times d` linear operator that approximates the barycentric
mapping
- :math:`\mathbf{I}` is the identity matrix (neutral linear mapping)
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are uniform source and target weights
The problem consist in solving jointly an optimal transport matrix
:math:`\gamma` and a linear mapping that fits the barycentric mapping
:math:`n_s\gamma \mathbf{X_t}`.
One can also estimate a mapping with constant bias (see supplementary
material of :ref:`[8] <references-joint-OT-mapping-linear>`) using the bias optional argument.
The algorithm used for solving the problem is the block coordinate
descent that alternates between updates of :math:`\mathbf{G}` (using conditional gradient)
and the update of :math:`\mathbf{L}` using a classical least square solver.
Parameters
----------
xs : array-like (ns,d)
samples in the source domain
xt : array-like (nt,d)
samples in the target domain
mu : float,optional
Weight for the linear OT loss (>0)
eta : float, optional
Regularization term for the linear mapping L (>0)
bias : bool,optional
Estimate linear mapping with constant bias
numItermax : int, optional
Max number of BCD iterations
stopThr : float, optional
Stop threshold on relative loss decrease (>0)
numInnerItermax : int, optional
Max number of iterations (inner CG solver)
stopInnerThr : float, optional
Stop threshold on error (inner CG solver) (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns, nt) array-like
Optimal transportation matrix for the given parameters
L : (d, d) array-like
Linear mapping matrix ((:math:`d+1`, `d`) if bias)
log : dict
log dictionary return only if log==True in parameters
.. _references-joint-OT-mapping-linear:
References
----------
.. [8] M. Perrot, N. Courty, R. Flamary, A. Habrard,
"Mapping estimation for discrete optimal transport",
Neural Information Processing Systems (NIPS), 2016.
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
"""
xs, xt = list_to_array(xs, xt)
nx = get_backend(xs, xt)
ns, nt, d = xs.shape[0], xt.shape[0], xt.shape[1]
if bias:
xs1 = nx.concatenate((xs, nx.ones((ns, 1), type_as=xs)), axis=1)
xstxs = nx.dot(xs1.T, xs1)
Id = nx.eye(d + 1, type_as=xs)
Id[-1] = 0
I0 = Id[:, :-1]
def sel(x):
return x[:-1, :]
else:
xs1 = xs
xstxs = nx.dot(xs1.T, xs1)
Id = nx.eye(d, type_as=xs)
I0 = Id
def sel(x):
return x
if log:
log = {'err': []}
a = unif(ns, type_as=xs)
b = unif(nt, type_as=xt)
M = dist(xs, xt) * ns
G = emd(a, b, M)
vloss = []
def loss(L, G):
"""Compute full loss"""
return (
nx.sum((nx.dot(xs1, L) - ns * nx.dot(G, xt)) ** 2)
+ mu * nx.sum(G * M)
+ eta * nx.sum(sel(L - I0) ** 2)
)
def solve_L(G):
""" solve L problem with fixed G (least square)"""
xst = ns * nx.dot(G, xt)
return nx.solve(xstxs + eta * Id, nx.dot(xs1.T, xst) + eta * I0)
def solve_G(L, G0):
"""Update G with CG algorithm"""
xsi = nx.dot(xs1, L)
def f(G):
return nx.sum((xsi - ns * nx.dot(G, xt)) ** 2)
def df(G):
return -2 * ns * nx.dot(xsi - ns * nx.dot(G, xt), xt.T)
G = cg(a, b, M, 1.0 / mu, f, df, G0=G0,
numItermax=numInnerItermax, stopThr=stopInnerThr)
return G
L = solve_L(G)
vloss.append(loss(L, G))
if verbose:
print('{:5s}|{:12s}|{:8s}'.format(
'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32)
print('{:5d}|{:8e}|{:8e}'.format(0, vloss[-1], 0))
# init loop
if numItermax > 0:
loop = 1
else:
loop = 0
it = 0
while loop:
it += 1
# update G
G = solve_G(L, G)
# update L
L = solve_L(G)
vloss.append(loss(L, G))
if it >= numItermax:
loop = 0
if abs(vloss[-1] - vloss[-2]) / abs(vloss[-2]) < stopThr:
loop = 0
if verbose:
if it % 20 == 0:
print('{:5s}|{:12s}|{:8s}'.format(
'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32)
print('{:5d}|{:8e}|{:8e}'.format(
it, vloss[-1], (vloss[-1] - vloss[-2]) / abs(vloss[-2])))
if log:
log['loss'] = vloss
return G, L, log
else:
return G, L
def joint_OT_mapping_kernel(xs, xt, mu=1, eta=0.001, kerneltype='gaussian',
sigma=1, bias=False, verbose=False, verbose2=False,
numItermax=100, numInnerItermax=10,
stopInnerThr=1e-6, stopThr=1e-5, log=False,
**kwargs):
r"""Joint OT and nonlinear mapping estimation with kernels as proposed in
:ref:`[8] <references-joint-OT-mapping-kernel>`.
The function solves the following optimization problem:
.. math::
\min_{\gamma, L\in\mathcal{H}}\quad \|L(\mathbf{X_s}) -
n_s\gamma \mathbf{X_t}\|^2_F + \mu \langle \gamma, \mathbf{M} \rangle_F +
\eta \|L\|^2_\mathcal{H}
s.t. \ \gamma \mathbf{1} = \mathbf{a}
\gamma^T \mathbf{1} = \mathbf{b}
\gamma \geq 0
where :
- :math:`\mathbf{M}` is the (`ns`, `nt`) squared euclidean cost matrix between samples in
:math:`\mathbf{X_s}` and :math:`\mathbf{X_t}` (scaled by :math:`n_s`)
- :math:`L` is a :math:`n_s \times d` linear operator on a kernel matrix that
approximates the barycentric mapping
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are uniform source and target weights
The problem consist in solving jointly an optimal transport matrix
:math:`\gamma` and the nonlinear mapping that fits the barycentric mapping
:math:`n_s\gamma \mathbf{X_t}`.
One can also estimate a mapping with constant bias (see supplementary
material of :ref:`[8] <references-joint-OT-mapping-kernel>`) using the bias optional argument.
The algorithm used for solving the problem is the block coordinate
descent that alternates between updates of :math:`\mathbf{G}` (using conditional gradient)
and the update of :math:`\mathbf{L}` using a classical kernel least square solver.
Parameters
----------
xs : array-like (ns,d)
samples in the source domain
xt : array-like (nt,d)
samples in the target domain
mu : float,optional
Weight for the linear OT loss (>0)
eta : float, optional
Regularization term for the linear mapping L (>0)
kerneltype : str,optional
kernel used by calling function :py:func:`ot.utils.kernel` (gaussian by default)
sigma : float, optional
Gaussian kernel bandwidth.
bias : bool,optional
Estimate linear mapping with constant bias
verbose : bool, optional
Print information along iterations
verbose2 : bool, optional
Print information along iterations
numItermax : int, optional
Max number of BCD iterations
numInnerItermax : int, optional
Max number of iterations (inner CG solver)
stopInnerThr : float, optional
Stop threshold on error (inner CG solver) (>0)
stopThr : float, optional
Stop threshold on relative loss decrease (>0)
log : bool, optional
record log if True
Returns
-------
gamma : (ns, nt) array-like
Optimal transportation matrix for the given parameters
L : (ns, d) array-like
Nonlinear mapping matrix ((:math:`n_s+1`, `d`) if bias)
log : dict
log dictionary return only if log==True in parameters
.. _references-joint-OT-mapping-kernel:
References
----------
.. [8] M. Perrot, N. Courty, R. Flamary, A. Habrard,
"Mapping estimation for discrete optimal transport",
Neural Information Processing Systems (NIPS), 2016.
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
"""
xs, xt = list_to_array(xs, xt)
nx = get_backend(xs, xt)
ns, nt = xs.shape[0], xt.shape[0]
K = kernel(xs, xs, method=kerneltype, sigma=sigma)
if bias:
K1 = nx.concatenate((K, nx.ones((ns, 1), type_as=xs)), axis=1)
Id = nx.eye(ns + 1, type_as=xs)
Id[-1] = 0
Kp = nx.eye(ns + 1, type_as=xs)
Kp[:ns, :ns] = K
# ls regu
# K0 = K1.T.dot(K1)+eta*I
# Kreg=I
# RKHS regul
K0 = nx.dot(K1.T, K1) + eta * Kp
Kreg = Kp
else:
K1 = K
Id = nx.eye(ns, type_as=xs)
# ls regul
# K0 = K1.T.dot(K1)+eta*I
# Kreg=I
# proper kernel ridge
K0 = K + eta * Id
Kreg = K
if log:
log = {'err': []}
a = unif(ns, type_as=xs)
b = unif(nt, type_as=xt)
M = dist(xs, xt) * ns
G = emd(a, b, M)
vloss = []
def loss(L, G):
"""Compute full loss"""
return (
nx.sum((nx.dot(K1, L) - ns * nx.dot(G, xt)) ** 2)
+ mu * nx.sum(G * M)
+ eta * nx.trace(dots(L.T, Kreg, L))
)
def solve_L_nobias(G):
""" solve L problem with fixed G (least square)"""
xst = ns * nx.dot(G, xt)
return nx.solve(K0, xst)
def solve_L_bias(G):
""" solve L problem with fixed G (least square)"""
xst = ns * nx.dot(G, xt)
return nx.solve(K0, nx.dot(K1.T, xst))
def solve_G(L, G0):
"""Update G with CG algorithm"""
xsi = nx.dot(K1, L)
def f(G):
return nx.sum((xsi - ns * nx.dot(G, xt)) ** 2)
def df(G):
return -2 * ns * nx.dot(xsi - ns * nx.dot(G, xt), xt.T)
G = cg(a, b, M, 1.0 / mu, f, df, G0=G0,
numItermax=numInnerItermax, stopThr=stopInnerThr)
return G
if bias:
solve_L = solve_L_bias
else:
solve_L = solve_L_nobias
L = solve_L(G)
vloss.append(loss(L, G))
if verbose:
print('{:5s}|{:12s}|{:8s}'.format(
'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32)
print('{:5d}|{:8e}|{:8e}'.format(0, vloss[-1], 0))
# init loop
if numItermax > 0:
loop = 1
else:
loop = 0
it = 0
while loop:
it += 1
# update G
G = solve_G(L, G)
# update L
L = solve_L(G)
vloss.append(loss(L, G))
if it >= numItermax:
loop = 0
if abs(vloss[-1] - vloss[-2]) / abs(vloss[-2]) < stopThr:
loop = 0
if verbose:
if it % 20 == 0:
print('{:5s}|{:12s}|{:8s}'.format(
'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32)
print('{:5d}|{:8e}|{:8e}'.format(
it, vloss[-1], (vloss[-1] - vloss[-2]) / abs(vloss[-2])))
if log:
log['loss'] = vloss
return G, L, log
else:
return G, L
OT_mapping_linear = deprecated(empirical_bures_wasserstein_mapping)
def emd_laplace(a, b, xs, xt, M, sim='knn', sim_param=None, reg='pos', eta=1, alpha=.5,
numItermax=100, stopThr=1e-9, numInnerItermax=100000,
stopInnerThr=1e-9, log=False, verbose=False):
r"""Solve the optimal transport problem (OT) with Laplacian regularization
.. math::
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
\eta \cdot \Omega_\alpha(\gamma)
s.t. \ \gamma \mathbf{1} = \mathbf{a}
\gamma^T \mathbf{1} = \mathbf{b}
\gamma \geq 0
where:
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
- :math:`\mathbf{x_s}` and :math:`\mathbf{x_t}` are source and target samples
- :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix
- :math:`\Omega_\alpha` is the Laplacian regularization term
.. math::
\Omega_\alpha = \frac{1 - \alpha}{n_s^2} \sum_{i,j}
\mathbf{S^s}_{i,j} \|T(\mathbf{x}^s_i) - T(\mathbf{x}^s_j) \|^2 +
\frac{\alpha}{n_t^2} \sum_{i,j}
\mathbf{S^t}_{i,j} \|T(\mathbf{x}^t_i) - T(\mathbf{x}^t_j) \|^2
with :math:`\mathbf{S^s}_{i,j}, \mathbf{S^t}_{i,j}` denoting source and target similarity
matrices and :math:`T(\cdot)` being a barycentric mapping.
The algorithm used for solving the problem is the conditional gradient algorithm as proposed in
:ref:`[5] <references-emd-laplace>`.
Parameters
----------
a : array-like (ns,)
samples weights in the source domain
b : array-like (nt,)
samples weights in the target domain
xs : array-like (ns,d)
samples in the source domain
xt : array-like (nt,d)
samples in the target domain
M : array-like (ns,nt)
loss matrix
sim : string, optional
Type of similarity ('knn' or 'gauss') used to construct the Laplacian.
sim_param : int or float, optional
Parameter (number of the nearest neighbors for sim='knn'
or bandwidth for sim='gauss') used to compute the Laplacian.
reg : string
Type of Laplacian regularization
eta : float
Regularization term for Laplacian regularization
alpha : float
Regularization term for source domain's importance in regularization
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshold on error (inner emd solver) (>0)
numInnerItermax : int, optional
Max number of iterations (inner CG solver)
stopInnerThr : float, optional
Stop threshold on error (inner CG solver) (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns, nt) array-like
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
.. _references-emd-laplace:
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
"Optimal Transport for Domain Adaptation," in IEEE
Transactions on Pattern Analysis and Machine Intelligence,
vol.PP, no.99, pp.1-1
.. [30] R. Flamary, N. Courty, D. Tuia, A. Rakotomamonjy,
"Optimal transport with Laplacian regularization: Applications to domain adaptation and shape matching,"
in NIPS Workshop on Optimal Transport and Machine Learning OTML, 2014.
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
"""
if not isinstance(sim_param, (int, float, type(None))):
raise ValueError(
'Similarity parameter should be an int or a float. Got {type} instead.'.format(type=type(sim_param).__name__))
a, b, xs, xt, M = list_to_array(a, b, xs, xt, M)
nx = get_backend(a, b, xs, xt, M)
if sim == 'gauss':
if sim_param is None:
sim_param = 1 / (2 * (nx.mean(dist(xs, xs, 'sqeuclidean')) ** 2))
sS = kernel(xs, xs, method=sim, sigma=sim_param)
sT = kernel(xt, xt, method=sim, sigma=sim_param)
elif sim == 'knn':
if sim_param is None:
sim_param = 3
from sklearn.neighbors import kneighbors_graph
sS = nx.from_numpy(kneighbors_graph(
X=nx.to_numpy(xs), n_neighbors=int(sim_param)
).toarray(), type_as=xs)
sS = (sS + sS.T) / 2
sT = nx.from_numpy(kneighbors_graph(
X=nx.to_numpy(xt), n_neighbors=int(sim_param)
).toarray(), type_as=xt)
sT = (sT + sT.T) / 2
else:
raise ValueError('Unknown similarity type {sim}. Currently supported similarity types are "knn" and "gauss".'.format(sim=sim))
lS = laplacian(sS)
lT = laplacian(sT)
def f(G):
return (
alpha * nx.trace(dots(xt.T, G.T, lS, G, xt))
+ (1 - alpha) * nx.trace(dots(xs.T, G, lT, G.T, xs))
)
ls2 = lS + lS.T
lt2 = lT + lT.T
xt2 = nx.dot(xt, xt.T)
if reg == 'disp':
Cs = -eta * alpha / xs.shape[0] * dots(ls2, xs, xt.T)
Ct = -eta * (1 - alpha) / xt.shape[0] * dots(xs, xt.T, lt2)
M = M + Cs + Ct
def df(G):
return (
alpha * dots(ls2, G, xt2)
+ (1 - alpha) * dots(xs, xs.T, G, lt2)
)
return cg(a, b, M, reg=eta, f=f, df=df, G0=None, numItermax=numItermax, numItermaxEmd=numInnerItermax,
stopThr=stopThr, stopThr2=stopInnerThr, verbose=verbose, log=log)
def distribution_estimation_uniform(X):
r"""estimates a uniform distribution from an array of samples :math:`\mathbf{X}`
Parameters
----------
X : array-like, shape (n_samples, n_features)
The array of samples
Returns
-------
mu : array-like, shape (n_samples,)
The uniform distribution estimated from :math:`\mathbf{X}`
"""
return unif(X.shape[0], type_as=X)
class BaseTransport(BaseEstimator):
"""Base class for OTDA objects
.. note::
All estimators should specify all the parameters that can be set
at the class level in their ``__init__`` as explicit keyword
arguments (no ``*args`` or ``**kwargs``).
The fit method should:
- estimate a cost matrix and store it in a `cost_` attribute
- estimate a coupling matrix and store it in a `coupling_` attribute
- estimate distributions from source and target data and store them in
`mu_s` and `mu_t` attributes
- store `Xs` and `Xt` in attributes to be used later on in `transform` and
`inverse_transform` methods
`transform` method should always get as input a `Xs` parameter
`inverse_transform` method should always get as input a `Xt` parameter
`transform_labels` method should always get as input a `ys` parameter
`inverse_transform_labels` method should always get as input a `yt` parameter
"""
def fit(self, Xs=None, ys=None, Xt=None, yt=None):
r"""Build a coupling matrix from source and target sets of samples
:math:`(\mathbf{X_s}, \mathbf{y_s})` and :math:`(\mathbf{X_t}, \mathbf{y_t})`
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, shape (n_source_samples,)
The training class labels
Xt : array-like, shape (n_target_samples, n_features)
The training input samples.
yt : array-like, shape (n_target_samples,)
The class labels. If some target samples are unlabelled, fill the
:math:`\mathbf{y_t}`'s elements with -1.
Warning: Note that, due to this convention -1 cannot be used as a
class label
Returns
-------
self : object
Returns self.
"""
nx = self._get_backend(Xs, ys, Xt, yt)
# check the necessary inputs parameters are here
if check_params(Xs=Xs, Xt=Xt):
# pairwise distance
self.cost_ = dist(Xs, Xt, metric=self.metric)
self.cost_ = cost_normalization(self.cost_, self.norm)
if (ys is not None) and (yt is not None):
if self.limit_max != np.infty:
self.limit_max = self.limit_max * nx.max(self.cost_)
# assumes labeled source samples occupy the first rows
# and labeled target samples occupy the first columns
classes = [c for c in nx.unique(ys) if c != -1]
for c in classes:
idx_s = nx.where((ys != c) & (ys != -1))
idx_t = nx.where(yt == c)
# all the coefficients corresponding to a source sample
# and a target sample :
# with different labels get a infinite
for j in idx_t[0]:
self.cost_[idx_s[0], j] = self.limit_max
# distribution estimation
self.mu_s = self.distribution_estimation(Xs)
self.mu_t = self.distribution_estimation(Xt)
# store arrays of samples
self.xs_ = Xs
self.xt_ = Xt
return self
def fit_transform(self, Xs=None, ys=None, Xt=None, yt=None):
r"""Build a coupling matrix from source and target sets of samples
:math:`(\mathbf{X_s}, \mathbf{y_s})` and :math:`(\mathbf{X_t}, \mathbf{y_t})`
and transports source samples :math:`\mathbf{X_s}` onto target ones :math:`\mathbf{X_t}`
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, shape (n_source_samples,)
The class labels for training samples
Xt : array-like, shape (n_target_samples, n_features)
The training input samples.
yt : array-like, shape (n_target_samples,)
The class labels. If some target samples are unlabelled, fill the
:math:`\mathbf{y_t}`'s elements with -1.
Warning: Note that, due to this convention -1 cannot be used as a
class label
Returns
-------
transp_Xs : array-like, shape (n_source_samples, n_features)
The source samples samples.
"""
return self.fit(Xs, ys, Xt, yt).transform(Xs, ys, Xt, yt)
def transform(self, Xs=None, ys=None, Xt=None, yt=None, batch_size=128):
r"""Transports source samples :math:`\mathbf{X_s}` onto target ones :math:`\mathbf{X_t}`
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The source input samples.
ys : array-like, shape (n_source_samples,)
The class labels for source samples
Xt : array-like, shape (n_target_samples, n_features)
The target input samples.
yt : array-like, shape (n_target_samples,)
The class labels for target. If some target samples are unlabelled, fill the
:math:`\mathbf{y_t}`'s elements with -1.
Warning: Note that, due to this convention -1 cannot be used as a
class label
batch_size : int, optional (default=128)
The batch size for out of sample inverse transform
Returns
-------
transp_Xs : array-like, shape (n_source_samples, n_features)
The transport source samples.
"""
nx = self.nx
# check the necessary inputs parameters are here
if check_params(Xs=Xs):
if nx.array_equal(self.xs_, Xs):