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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520
|
# -*- coding: utf-8 -*-
"""
Domain adaptation with optimal transport
"""
# Author: Remi Flamary <remi.flamary@unice.fr>
# Nicolas Courty <ncourty@irisa.fr>
# Michael Perrot <michael.perrot@univ-st-etienne.fr>
# Nathalie Gayraud <nat.gayraud@gmail.com>
# Ievgen Redko <ievgen.redko@univ-st-etienne.fr>
#
# License: MIT License
import numpy as np
import scipy.linalg as linalg
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 check_params, BaseEstimator
from .unbalanced import sinkhorn_unbalanced
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):
"""
Solve the entropic regularization optimal transport problem with nonconvex
group lasso regularization
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)
+ \eta \Omega_g(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- 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.
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalized conditional
gradient as proposed in [5]_ [7]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
labels_a : np.ndarray (ns,)
labels of samples in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
M : np.ndarray (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 x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
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
"""
p = 0.5
epsilon = 1e-3
indices_labels = []
classes = np.unique(labels_a)
for c in classes:
idxc, = np.where(labels_a == c)
indices_labels.append(idxc)
W = np.zeros(M.shape)
for cpt in range(numItermax):
Mreg = M + eta * W
transp = sinkhorn(a, b, Mreg, reg, numItermax=numInnerItermax,
stopThr=stopInnerThr)
# the transport has been computed. Check if classes are really
# separated
W = np.ones(M.shape)
for (i, c) in enumerate(classes):
majs = np.sum(transp[indices_labels[i]], axis=0)
majs = p * ((majs + epsilon) ** (p - 1))
W[indices_labels[i]] = majs
return transp
def sinkhorn_l1l2_gl(a, labels_a, b, M, reg, eta=0.1, numItermax=10,
numInnerItermax=200, stopInnerThr=1e-9, verbose=False,
log=False):
"""
Solve the entropic regularization optimal transport problem with group
lasso regularization
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)+
\eta \Omega_g(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- 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 regulaization 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.
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalised conditional
gradient as proposed in [5]_ [7]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
labels_a : np.ndarray (ns,)
labels of samples in the source domain
b : np.ndarray (nt,)
samples in the target domain
M : np.ndarray (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 x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
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
"""
lstlab = np.unique(labels_a)
def f(G):
res = 0
for i in range(G.shape[1]):
for lab in lstlab:
temp = G[labels_a == lab, i]
res += np.linalg.norm(temp)
return res
def df(G):
W = np.zeros(G.shape)
for i in range(G.shape[1]):
for lab in lstlab:
temp = G[labels_a == lab, i]
n = np.linalg.norm(temp)
if n:
W[labels_a == lab, i] = temp / n
return W
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):
"""Joint OT and linear mapping estimation as proposed in [8]
The function solves the following optimization problem:
.. math::
\min_{\gamma,L}\quad \|L(X_s) -n_s\gamma X_t\|^2_F +
\mu<\gamma,M>_F + \eta \|L -I\|^2_F
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) squared euclidean cost matrix between samples in
Xs and Xt (scaled by ns)
- :math:`L` is a dxd linear operator that approximates the barycentric
mapping
- :math:`I` is the identity matrix (neutral linear mapping)
- a and 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 X_t`.
One can also estimate a mapping with constant bias (see supplementary
material of [8]) using the bias optional argument.
The algorithm used for solving the problem is the block coordinate
descent that alternates between updates of G (using conditionnal gradient)
and the update of L using a classical least square solver.
Parameters
----------
xs : np.ndarray (ns,d)
samples in the source domain
xt : np.ndarray (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 x nt) ndarray
Optimal transportation matrix for the given parameters
L : (d x d) ndarray
Linear mapping matrix (d+1 x d if bias)
log : dict
log dictionary return only if log==True in parameters
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
"""
ns, nt, d = xs.shape[0], xt.shape[0], xt.shape[1]
if bias:
xs1 = np.hstack((xs, np.ones((ns, 1))))
xstxs = xs1.T.dot(xs1)
Id = np.eye(d + 1)
Id[-1] = 0
I0 = Id[:, :-1]
def sel(x):
return x[:-1, :]
else:
xs1 = xs
xstxs = xs1.T.dot(xs1)
Id = np.eye(d)
I0 = Id
def sel(x):
return x
if log:
log = {'err': []}
a, b = unif(ns), unif(nt)
M = dist(xs, xt) * ns
G = emd(a, b, M)
vloss = []
def loss(L, G):
"""Compute full loss"""
return np.sum((xs1.dot(L) - ns * G.dot(xt)) ** 2) + mu * \
np.sum(G * M) + eta * np.sum(sel(L - I0) ** 2)
def solve_L(G):
""" solve L problem with fixed G (least square)"""
xst = ns * G.dot(xt)
return np.linalg.solve(xstxs + eta * Id, xs1.T.dot(xst) + eta * I0)
def solve_G(L, G0):
"""Update G with CG algorithm"""
xsi = xs1.dot(L)
def f(G):
return np.sum((xsi - ns * G.dot(xt)) ** 2)
def df(G):
return -2 * ns * (xsi - ns * G.dot(xt)).dot(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):
"""Joint OT and nonlinear mapping estimation with kernels as proposed in [8]
The function solves the following optimization problem:
.. math::
\min_{\gamma,L\in\mathcal{H}}\quad \|L(X_s) -
n_s\gamma X_t\|^2_F + \mu<\gamma,M>_F + \eta \|L\|^2_\mathcal{H}
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) squared euclidean cost matrix between samples in
Xs and Xt (scaled by ns)
- :math:`L` is a ns x d linear operator on a kernel matrix that
approximates the barycentric mapping
- a and 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 X_t`.
One can also estimate a mapping with constant bias (see supplementary
material of [8]) using the bias optional argument.
The algorithm used for solving the problem is the block coordinate
descent that alternates between updates of G (using conditionnal gradient)
and the update of L using a classical kernel least square solver.
Parameters
----------
xs : np.ndarray (ns,d)
samples in the source domain
xt : np.ndarray (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 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 x nt) ndarray
Optimal transportation matrix for the given parameters
L : (ns x d) ndarray
Nonlinear mapping matrix (ns+1 x d if bias)
log : dict
log dictionary return only if log==True in parameters
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
"""
ns, nt = xs.shape[0], xt.shape[0]
K = kernel(xs, xs, method=kerneltype, sigma=sigma)
if bias:
K1 = np.hstack((K, np.ones((ns, 1))))
Id = np.eye(ns + 1)
Id[-1] = 0
Kp = np.eye(ns + 1)
Kp[:ns, :ns] = K
# ls regu
# K0 = K1.T.dot(K1)+eta*I
# Kreg=I
# RKHS regul
K0 = K1.T.dot(K1) + eta * Kp
Kreg = Kp
else:
K1 = K
Id = np.eye(ns)
# 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, b = unif(ns), unif(nt)
M = dist(xs, xt) * ns
G = emd(a, b, M)
vloss = []
def loss(L, G):
"""Compute full loss"""
return np.sum((K1.dot(L) - ns * G.dot(xt)) ** 2) + mu * \
np.sum(G * M) + eta * np.trace(L.T.dot(Kreg).dot(L))
def solve_L_nobias(G):
""" solve L problem with fixed G (least square)"""
xst = ns * G.dot(xt)
return np.linalg.solve(K0, xst)
def solve_L_bias(G):
""" solve L problem with fixed G (least square)"""
xst = ns * G.dot(xt)
return np.linalg.solve(K0, K1.T.dot(xst))
def solve_G(L, G0):
"""Update G with CG algorithm"""
xsi = K1.dot(L)
def f(G):
return np.sum((xsi - ns * G.dot(xt)) ** 2)
def df(G):
return -2 * ns * (xsi - ns * G.dot(xt)).dot(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
def OT_mapping_linear(xs, xt, reg=1e-6, ws=None,
wt=None, bias=True, log=False):
""" return OT linear operator between samples
The function estimates the optimal linear operator that aligns the two
empirical distributions. This is equivalent to estimating the closed
form mapping between two Gaussian distributions :math:`N(\mu_s,\Sigma_s)`
and :math:`N(\mu_t,\Sigma_t)` as proposed in [14] and discussed in remark
2.29 in [15].
The linear operator from source to target :math:`M`
.. math::
M(x)=Ax+b
where :
.. math::
A=\Sigma_s^{-1/2}(\Sigma_s^{1/2}\Sigma_t\Sigma_s^{1/2})^{1/2}
\Sigma_s^{-1/2}
.. math::
b=\mu_t-A\mu_s
Parameters
----------
xs : np.ndarray (ns,d)
samples in the source domain
xt : np.ndarray (nt,d)
samples in the target domain
reg : float,optional
regularization added to the diagonals of convariances (>0)
ws : np.ndarray (ns,1), optional
weights for the source samples
wt : np.ndarray (ns,1), optional
weights for the target samples
bias: boolean, optional
estimate bias b else b=0 (default:True)
log : bool, optional
record log if True
Returns
-------
A : (d x d) ndarray
Linear operator
b : (1 x d) ndarray
bias
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [14] Knott, M. and Smith, C. S. "On the optimal mapping of
distributions", Journal of Optimization Theory and Applications
Vol 43, 1984
.. [15] Peyré, G., & Cuturi, M. (2017). "Computational Optimal
Transport", 2018.
"""
d = xs.shape[1]
if bias:
mxs = xs.mean(0, keepdims=True)
mxt = xt.mean(0, keepdims=True)
xs = xs - mxs
xt = xt - mxt
else:
mxs = np.zeros((1, d))
mxt = np.zeros((1, d))
if ws is None:
ws = np.ones((xs.shape[0], 1)) / xs.shape[0]
if wt is None:
wt = np.ones((xt.shape[0], 1)) / xt.shape[0]
Cs = (xs * ws).T.dot(xs) / ws.sum() + reg * np.eye(d)
Ct = (xt * wt).T.dot(xt) / wt.sum() + reg * np.eye(d)
Cs12 = linalg.sqrtm(Cs)
Cs_12 = linalg.inv(Cs12)
M0 = linalg.sqrtm(Cs12.dot(Ct.dot(Cs12)))
A = Cs_12.dot(M0.dot(Cs_12))
b = mxt - mxs.dot(A)
if log:
log = {}
log['Cs'] = Cs
log['Ct'] = Ct
log['Cs12'] = Cs12
log['Cs_12'] = Cs_12
return A, b, log
else:
return A, b
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 = arg\min_\gamma <\gamma,M>_F + eta\Omega_\alpha(\gamma)
s.t.\ \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where:
- a and b are source and target weights (sum to 1)
- xs and xt are source and target samples
- M is the (ns,nt) metric cost matrix
- :math:`\Omega_\alpha` is the Laplacian regularization term
:math:`\Omega_\alpha = (1-\alpha)/n_s^2\sum_{i,j}S^s_{i,j}\|T(\mathbf{x}^s_i)-T(\mathbf{x}^s_j)\|^2+\alpha/n_t^2\sum_{i,j}S^t_{i,j}^'\|T(\mathbf{x}^t_i)-T(\mathbf{x}^t_j)\|^2`
with :math:`S^s_{i,j}, 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 [5].
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
xs : np.ndarray (ns,d)
samples in the source domain
xt : np.ndarray (nt,d)
samples in the target domain
M : np.ndarray (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 x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
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__))
if sim == 'gauss':
if sim_param is None:
sim_param = 1 / (2 * (np.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 = kneighbors_graph(X=xs, n_neighbors=int(sim_param)).toarray()
sS = (sS + sS.T) / 2
sT = kneighbors_graph(xt, n_neighbors=int(sim_param)).toarray()
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 * np.trace(np.dot(xt.T, np.dot(G.T, np.dot(lS, np.dot(G, xt))))) \
+ (1 - alpha) * np.trace(np.dot(xs.T, np.dot(G, np.dot(lT, np.dot(G.T, xs)))))
ls2 = lS + lS.T
lt2 = lT + lT.T
xt2 = np.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 * np.dot(ls2, np.dot(G, xt2))\
+ (1 - alpha) * np.dot(xs, np.dot(xs.T, np.dot(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):
"""estimates a uniform distribution from an array of samples 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 X
"""
return unif(X.shape[0])
class BaseTransport(BaseEstimator):
"""Base class for OTDA objects
Notes
-----
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):
"""Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt)
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 unlabeled, fill the
yt's elements with -1.
Warning: Note that, due to this convention -1 cannot be used as a
class label
Returns
-------
self : object
Returns self.
"""
# 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 * np.max(self.cost_)
# assumes labeled source samples occupy the first rows
# and labeled target samples occupy the first columns
classes = [c for c in np.unique(ys) if c != -1]
for c in classes:
idx_s = np.where((ys != c) & (ys != -1))
idx_t = np.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):
"""Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt) and transports source samples Xs onto target
ones Xt
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 unlabeled, fill the
yt'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):
"""Transports source samples Xs onto target ones Xt
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 unlabeled, fill the
yt'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.
"""
# check the necessary inputs parameters are here
if check_params(Xs=Xs):
if np.array_equal(self.xs_, Xs):
# perform standard barycentric mapping
transp = self.coupling_ / np.sum(self.coupling_, 1)[:, None]
# set nans to 0
transp[~ np.isfinite(transp)] = 0
# compute transported samples
transp_Xs = np.dot(transp, self.xt_)
else:
# perform out of sample mapping
indices = np.arange(Xs.shape[0])
batch_ind = [
indices[i:i + batch_size]
for i in range(0, len(indices), batch_size)]
transp_Xs = []
for bi in batch_ind:
# get the nearest neighbor in the source domain
D0 = dist(Xs[bi], self.xs_)
idx = np.argmin(D0, axis=1)
# transport the source samples
transp = self.coupling_ / np.sum(
self.coupling_, 1)[:, None]
transp[~ np.isfinite(transp)] = 0
transp_Xs_ = np.dot(transp, self.xt_)
# define the transported points
transp_Xs_ = transp_Xs_[idx, :] + Xs[bi] - self.xs_[idx, :]
transp_Xs.append(transp_Xs_)
transp_Xs = np.concatenate(transp_Xs, axis=0)
return transp_Xs
def transform_labels(self, ys=None):
"""Propagate source labels ys to obtain estimated target labels as in [27]
Parameters
----------
ys : array-like, shape (n_source_samples,)
The source class labels
Returns
-------
transp_ys : array-like, shape (n_target_samples, nb_classes)
Estimated soft target labels.
References
----------
.. [27] Ievgen Redko, Nicolas Courty, Rémi Flamary, Devis Tuia
"Optimal transport for multi-source domain adaptation under target shift",
International Conference on Artificial Intelligence and Statistics (AISTATS), 2019.
"""
# check the necessary inputs parameters are here
if check_params(ys=ys):
ysTemp = label_normalization(np.copy(ys))
classes = np.unique(ysTemp)
n = len(classes)
D1 = np.zeros((n, len(ysTemp)))
# perform label propagation
transp = self.coupling_ / np.sum(self.coupling_, 1)[:, None]
# set nans to 0
transp[~ np.isfinite(transp)] = 0
for c in classes:
D1[int(c), ysTemp == c] = 1
# compute propagated labels
transp_ys = np.dot(D1, transp)
return transp_ys.T
def inverse_transform(self, Xs=None, ys=None, Xt=None, yt=None,
batch_size=128):
"""Transports target samples Xt onto source samples Xs
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The source input samples.
ys : array-like, shape (n_source_samples,)
The source class labels
Xt : array-like, shape (n_target_samples, n_features)
The target input samples.
yt : array-like, shape (n_target_samples,)
The target class labels. If some target samples are unlabeled, fill the
yt'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_Xt : array-like, shape (n_source_samples, n_features)
The transported target samples.
"""
# check the necessary inputs parameters are here
if check_params(Xt=Xt):
if np.array_equal(self.xt_, Xt):
# perform standard barycentric mapping
transp_ = self.coupling_.T / np.sum(self.coupling_, 0)[:, None]
# set nans to 0
transp_[~ np.isfinite(transp_)] = 0
# compute transported samples
transp_Xt = np.dot(transp_, self.xs_)
else:
# perform out of sample mapping
indices = np.arange(Xt.shape[0])
batch_ind = [
indices[i:i + batch_size]
for i in range(0, len(indices), batch_size)]
transp_Xt = []
for bi in batch_ind:
D0 = dist(Xt[bi], self.xt_)
idx = np.argmin(D0, axis=1)
# transport the target samples
transp_ = self.coupling_.T / np.sum(
self.coupling_, 0)[:, None]
transp_[~ np.isfinite(transp_)] = 0
transp_Xt_ = np.dot(transp_, self.xs_)
# define the transported points
transp_Xt_ = transp_Xt_[idx, :] + Xt[bi] - self.xt_[idx, :]
transp_Xt.append(transp_Xt_)
transp_Xt = np.concatenate(transp_Xt, axis=0)
return transp_Xt
def inverse_transform_labels(self, yt=None):
"""Propagate target labels yt to obtain estimated source labels ys
Parameters
----------
yt : array-like, shape (n_target_samples,)
Returns
-------
transp_ys : array-like, shape (n_source_samples, nb_classes)
Estimated soft source labels.
"""
# check the necessary inputs parameters are here
if check_params(yt=yt):
ytTemp = label_normalization(np.copy(yt))
classes = np.unique(ytTemp)
n = len(classes)
D1 = np.zeros((n, len(ytTemp)))
# perform label propagation
transp = self.coupling_ / np.sum(self.coupling_, 1)[:, None]
# set nans to 0
transp[~ np.isfinite(transp)] = 0
for c in classes:
D1[int(c), ytTemp == c] = 1
# compute propagated samples
transp_ys = np.dot(D1, transp.T)
return transp_ys.T
class LinearTransport(BaseTransport):
""" OT linear operator between empirical distributions
The function estimates the optimal linear operator that aligns the two
empirical distributions. This is equivalent to estimating the closed
form mapping between two Gaussian distributions :math:`N(\mu_s,\Sigma_s)`
and :math:`N(\mu_t,\Sigma_t)` as proposed in [14] and discussed in
remark 2.29 in [15].
The linear operator from source to target :math:`M`
.. math::
M(x)=Ax+b
where :
.. math::
A=\Sigma_s^{-1/2}(\Sigma_s^{1/2}\Sigma_t\Sigma_s^{1/2})^{1/2}
\Sigma_s^{-1/2}
.. math::
b=\mu_t-A\mu_s
Parameters
----------
reg : float,optional
regularization added to the daigonals of convariances (>0)
bias: boolean, optional
estimate bias b else b=0 (default:True)
log : bool, optional
record log if True
References
----------
.. [14] Knott, M. and Smith, C. S. "On the optimal mapping of
distributions", Journal of Optimization Theory and Applications
Vol 43, 1984
.. [15] Peyré, G., & Cuturi, M. (2017). "Computational Optimal
Transport", 2018.
"""
def __init__(self, reg=1e-8, bias=True, log=False,
distribution_estimation=distribution_estimation_uniform):
self.bias = bias
self.log = log
self.reg = reg
self.distribution_estimation = distribution_estimation
def fit(self, Xs=None, ys=None, Xt=None, yt=None):
"""Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt)
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, shape (n_source_samples,)
The 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 unlabeled, fill the
yt's elements with -1.
Warning: Note that, due to this convention -1 cannot be used as a
class label
Returns
-------
self : object
Returns self.
"""
self.mu_s = self.distribution_estimation(Xs)
self.mu_t = self.distribution_estimation(Xt)
# coupling estimation
returned_ = OT_mapping_linear(Xs, Xt, reg=self.reg,
ws=self.mu_s.reshape((-1, 1)),
wt=self.mu_t.reshape((-1, 1)),
bias=self.bias, log=self.log)
# deal with the value of log
if self.log:
self.A_, self.B_, self.log_ = returned_
else:
self.A_, self.B_, = returned_
self.log_ = dict()
# re compute inverse mapping
self.A1_ = linalg.inv(self.A_)
self.B1_ = -self.B_.dot(self.A1_)
return self
def transform(self, Xs=None, ys=None, Xt=None, yt=None, batch_size=128):
"""Transports source samples Xs onto target ones Xt
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, shape (n_source_samples,)
The 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 unlabeled, fill the
yt'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.
"""
# check the necessary inputs parameters are here
if check_params(Xs=Xs):
transp_Xs = Xs.dot(self.A_) + self.B_
return transp_Xs
def inverse_transform(self, Xs=None, ys=None, Xt=None, yt=None,
batch_size=128):
"""Transports target samples Xt onto target samples Xs
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, shape (n_source_samples,)
The 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 unlabeled, fill the
yt'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_Xt : array-like, shape (n_source_samples, n_features)
The transported target samples.
"""
# check the necessary inputs parameters are here
if check_params(Xt=Xt):
transp_Xt = Xt.dot(self.A1_) + self.B1_
return transp_Xt
class SinkhornTransport(BaseTransport):
"""Domain Adapatation OT method based on Sinkhorn Algorithm
Parameters
----------
reg_e : float, optional (default=1)
Entropic regularization parameter
max_iter : int, float, optional (default=1000)
The minimum number of iteration before stopping the optimization
algorithm if no it has not converged
tol : float, optional (default=10e-9)
The precision required to stop the optimization algorithm.
verbose : bool, optional (default=False)
Controls the verbosity of the optimization algorithm
log : int, optional (default=False)
Controls the logs of the optimization algorithm
metric : string, optional (default="sqeuclidean")
The ground metric for the Wasserstein problem
norm : string, optional (default=None)
If given, normalize the ground metric to avoid numerical errors that
can occur with large metric values.
distribution_estimation : callable, optional (defaults to the uniform)
The kind of distribution estimation to employ
out_of_sample_map : string, optional (default="ferradans")
The kind of out of sample mapping to apply to transport samples
from a domain into another one. Currently the only possible option is
"ferradans" which uses the method proposed in [6].
limit_max: float, optional (defaul=np.infty)
Controls the semi supervised mode. Transport between labeled source
and target samples of different classes will exhibit an cost defined
by this variable
Attributes
----------
coupling_ : array-like, shape (n_source_samples, n_target_samples)
The optimal coupling
log_ : dictionary
The dictionary of log, empty dic if parameter log is not True
References
----------
.. [1] 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
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal
Transport, Advances in Neural Information Processing Systems (NIPS)
26, 2013
.. [6] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014).
Regularized discrete optimal transport. SIAM Journal on Imaging
Sciences, 7(3), 1853-1882.
"""
def __init__(self, reg_e=1., max_iter=1000,
tol=10e-9, verbose=False, log=False,
metric="sqeuclidean", norm=None,
distribution_estimation=distribution_estimation_uniform,
out_of_sample_map='ferradans', limit_max=np.infty):
self.reg_e = reg_e
self.max_iter = max_iter
self.tol = tol
self.verbose = verbose
self.log = log
self.metric = metric
self.norm = norm
self.limit_max = limit_max
self.distribution_estimation = distribution_estimation
self.out_of_sample_map = out_of_sample_map
def fit(self, Xs=None, ys=None, Xt=None, yt=None):
"""Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt)
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, shape (n_source_samples,)
The 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 unlabeled, fill the
yt's elements with -1.
Warning: Note that, due to this convention -1 cannot be used as a
class label
Returns
-------
self : object
Returns self.
"""
super(SinkhornTransport, self).fit(Xs, ys, Xt, yt)
# coupling estimation
returned_ = sinkhorn(
a=self.mu_s, b=self.mu_t, M=self.cost_, reg=self.reg_e,
numItermax=self.max_iter, stopThr=self.tol,
verbose=self.verbose, log=self.log)
# deal with the value of log
if self.log:
self.coupling_, self.log_ = returned_
else:
self.coupling_ = returned_
self.log_ = dict()
return self
class EMDTransport(BaseTransport):
"""Domain Adapatation OT method based on Earth Mover's Distance
Parameters
----------
metric : string, optional (default="sqeuclidean")
The ground metric for the Wasserstein problem
norm : string, optional (default=None)
If given, normalize the ground metric to avoid numerical errors that
can occur with large metric values.
log : int, optional (default=False)
Controls the logs of the optimization algorithm
distribution_estimation : callable, optional (defaults to the uniform)
The kind of distribution estimation to employ
out_of_sample_map : string, optional (default="ferradans")
The kind of out of sample mapping to apply to transport samples
from a domain into another one. Currently the only possible option is
"ferradans" which uses the method proposed in [6].
limit_max: float, optional (default=10)
Controls the semi supervised mode. Transport between labeled source
and target samples of different classes will exhibit an infinite cost
(10 times the maximum value of the cost matrix)
max_iter : int, optional (default=100000)
The maximum number of iterations before stopping the optimization
algorithm if it has not converged.
Attributes
----------
coupling_ : array-like, shape (n_source_samples, n_target_samples)
The optimal coupling
References
----------
.. [1] 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
.. [6] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014).
Regularized discrete optimal transport. SIAM Journal on Imaging
Sciences, 7(3), 1853-1882.
"""
def __init__(self, metric="sqeuclidean", norm=None, log=False,
distribution_estimation=distribution_estimation_uniform,
out_of_sample_map='ferradans', limit_max=10,
max_iter=100000):
self.metric = metric
self.norm = norm
self.log = log
self.limit_max = limit_max
self.distribution_estimation = distribution_estimation
self.out_of_sample_map = out_of_sample_map
self.max_iter = max_iter
def fit(self, Xs, ys=None, Xt=None, yt=None):
"""Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt)
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, shape (n_source_samples,)
The 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 unlabeled, fill the
yt's elements with -1.
Warning: Note that, due to this convention -1 cannot be used as a
class label
Returns
-------
self : object
Returns self.
"""
super(EMDTransport, self).fit(Xs, ys, Xt, yt)
returned_ = emd(
a=self.mu_s, b=self.mu_t, M=self.cost_, numItermax=self.max_iter,
log=self.log)
# coupling estimation
if self.log:
self.coupling_, self.log_ = returned_
else:
self.coupling_ = returned_
self.log_ = dict()
return self
class SinkhornLpl1Transport(BaseTransport):
"""Domain Adapatation OT method based on sinkhorn algorithm +
LpL1 class regularization.
Parameters
----------
reg_e : float, optional (default=1)
Entropic regularization parameter
reg_cl : float, optional (default=0.1)
Class regularization parameter
max_iter : int, float, optional (default=10)
The minimum number of iteration before stopping the optimization
algorithm if no it has not converged
max_inner_iter : int, float, optional (default=200)
The number of iteration in the inner loop
log : bool, optional (default=False)
Controls the logs of the optimization algorithm
tol : float, optional (default=10e-9)
Stop threshold on error (inner sinkhorn solver) (>0)
verbose : bool, optional (default=False)
Controls the verbosity of the optimization algorithm
metric : string, optional (default="sqeuclidean")
The ground metric for the Wasserstein problem
norm : string, optional (default=None)
If given, normalize the ground metric to avoid numerical errors that
can occur with large metric values.
distribution_estimation : callable, optional (defaults to the uniform)
The kind of distribution estimation to employ
out_of_sample_map : string, optional (default="ferradans")
The kind of out of sample mapping to apply to transport samples
from a domain into another one. Currently the only possible option is
"ferradans" which uses the method proposed in [6].
limit_max: float, optional (defaul=np.infty)
Controls the semi supervised mode. Transport between labeled source
and target samples of different classes will exhibit a cost defined by
limit_max.
Attributes
----------
coupling_ : array-like, shape (n_source_samples, n_target_samples)
The optimal coupling
References
----------
.. [1] 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
.. [2] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
Generalized conditional gradient: analysis of convergence
and applications. arXiv preprint arXiv:1510.06567.
.. [6] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014).
Regularized discrete optimal transport. SIAM Journal on Imaging
Sciences, 7(3), 1853-1882.
"""
def __init__(self, reg_e=1., reg_cl=0.1,
max_iter=10, max_inner_iter=200, log=False,
tol=10e-9, verbose=False,
metric="sqeuclidean", norm=None,
distribution_estimation=distribution_estimation_uniform,
out_of_sample_map='ferradans', limit_max=np.infty):
self.reg_e = reg_e
self.reg_cl = reg_cl
self.max_iter = max_iter
self.max_inner_iter = max_inner_iter
self.tol = tol
self.log = log
self.verbose = verbose
self.metric = metric
self.norm = norm
self.distribution_estimation = distribution_estimation
self.out_of_sample_map = out_of_sample_map
self.limit_max = limit_max
def fit(self, Xs, ys=None, Xt=None, yt=None):
"""Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt)
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, shape (n_source_samples,)
The 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 unlabeled, fill the
yt's elements with -1.
Warning: Note that, due to this convention -1 cannot be used as a
class label
Returns
-------
self : object
Returns self.
"""
# check the necessary inputs parameters are here
if check_params(Xs=Xs, Xt=Xt, ys=ys):
super(SinkhornLpl1Transport, self).fit(Xs, ys, Xt, yt)
returned_ = sinkhorn_lpl1_mm(
a=self.mu_s, labels_a=ys, b=self.mu_t, M=self.cost_,
reg=self.reg_e, eta=self.reg_cl, numItermax=self.max_iter,
numInnerItermax=self.max_inner_iter, stopInnerThr=self.tol,
verbose=self.verbose, log=self.log)
# deal with the value of log
if self.log:
self.coupling_, self.log_ = returned_
else:
self.coupling_ = returned_
self.log_ = dict()
return self
class EMDLaplaceTransport(BaseTransport):
"""Domain Adapatation OT method based on Earth Mover's Distance with Laplacian regularization
Parameters
----------
reg_type : string optional (default='pos')
Type of the regularization term: 'pos' and 'disp' for
regularization term defined in [2] and [6], respectively.
reg_lap : float, optional (default=1)
Laplacian regularization parameter
reg_src : float, optional (default=0.5)
Source relative importance in regularization
metric : string, optional (default="sqeuclidean")
The ground metric for the Wasserstein problem
norm : string, optional (default=None)
If given, normalize the ground metric to avoid numerical errors that
can occur with large metric values.
similarity : string, optional (default="knn")
The similarity to use either knn or gaussian
similarity_param : int or float, optional (default=None)
Parameter for the similarity: number of nearest neighbors or bandwidth
if similarity="knn" or "gaussian", respectively. If None is provided,
it is set to 3 or the average pairwise squared Euclidean distance, respectively.
max_iter : int, optional (default=100)
Max number of BCD iterations
tol : float, optional (default=1e-5)
Stop threshold on relative loss decrease (>0)
max_inner_iter : int, optional (default=10)
Max number of iterations (inner CG solver)
inner_tol : float, optional (default=1e-6)
Stop threshold on error (inner CG solver) (>0)
log : int, optional (default=False)
Controls the logs of the optimization algorithm
distribution_estimation : callable, optional (defaults to the uniform)
The kind of distribution estimation to employ
out_of_sample_map : string, optional (default="ferradans")
The kind of out of sample mapping to apply to transport samples
from a domain into another one. Currently the only possible option is
"ferradans" which uses the method proposed in [6].
Attributes
----------
coupling_ : array-like, shape (n_source_samples, n_target_samples)
The optimal coupling
References
----------
.. [1] 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
.. [2] 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.
.. [6] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014).
Regularized discrete optimal transport. SIAM Journal on Imaging
Sciences, 7(3), 1853-1882.
"""
def __init__(self, reg_type='pos', reg_lap=1., reg_src=1., metric="sqeuclidean",
norm=None, similarity="knn", similarity_param=None, max_iter=100, tol=1e-9,
max_inner_iter=100000, inner_tol=1e-9, log=False, verbose=False,
distribution_estimation=distribution_estimation_uniform,
out_of_sample_map='ferradans'):
self.reg = reg_type
self.reg_lap = reg_lap
self.reg_src = reg_src
self.metric = metric
self.norm = norm
self.similarity = similarity
self.sim_param = similarity_param
self.max_iter = max_iter
self.tol = tol
self.max_inner_iter = max_inner_iter
self.inner_tol = inner_tol
self.log = log
self.verbose = verbose
self.distribution_estimation = distribution_estimation
self.out_of_sample_map = out_of_sample_map
def fit(self, Xs, ys=None, Xt=None, yt=None):
"""Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt)
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, shape (n_source_samples,)
The 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 unlabeled, fill the
yt's elements with -1.
Warning: Note that, due to this convention -1 cannot be used as a
class label
Returns
-------
self : object
Returns self.
"""
super(EMDLaplaceTransport, self).fit(Xs, ys, Xt, yt)
returned_ = emd_laplace(a=self.mu_s, b=self.mu_t, xs=self.xs_,
xt=self.xt_, M=self.cost_, sim=self.similarity, sim_param=self.sim_param, reg=self.reg, eta=self.reg_lap,
alpha=self.reg_src, numItermax=self.max_iter, stopThr=self.tol, numInnerItermax=self.max_inner_iter,
stopInnerThr=self.inner_tol, log=self.log, verbose=self.verbose)
# coupling estimation
if self.log:
self.coupling_, self.log_ = returned_
else:
self.coupling_ = returned_
self.log_ = dict()
return self
class SinkhornL1l2Transport(BaseTransport):
"""Domain Adapatation OT method based on sinkhorn algorithm +
l1l2 class regularization.
Parameters
----------
reg_e : float, optional (default=1)
Entropic regularization parameter
reg_cl : float, optional (default=0.1)
Class regularization parameter
max_iter : int, float, optional (default=10)
The minimum number of iteration before stopping the optimization
algorithm if no it has not converged
max_inner_iter : int, float, optional (default=200)
The number of iteration in the inner loop
tol : float, optional (default=10e-9)
Stop threshold on error (inner sinkhorn solver) (>0)
verbose : bool, optional (default=False)
Controls the verbosity of the optimization algorithm
log : bool, optional (default=False)
Controls the logs of the optimization algorithm
metric : string, optional (default="sqeuclidean")
The ground metric for the Wasserstein problem
norm : string, optional (default=None)
If given, normalize the ground metric to avoid numerical errors that
can occur with large metric values.
distribution_estimation : callable, optional (defaults to the uniform)
The kind of distribution estimation to employ
out_of_sample_map : string, optional (default="ferradans")
The kind of out of sample mapping to apply to transport samples
from a domain into another one. Currently the only possible option is
"ferradans" which uses the method proposed in [6].
limit_max: float, optional (default=10)
Controls the semi supervised mode. Transport between labeled source
and target samples of different classes will exhibit an infinite cost
(10 times the maximum value of the cost matrix)
Attributes
----------
coupling_ : array-like, shape (n_source_samples, n_target_samples)
The optimal coupling
log_ : dictionary
The dictionary of log, empty dic if parameter log is not True
References
----------
.. [1] 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
.. [2] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
Generalized conditional gradient: analysis of convergence
and applications. arXiv preprint arXiv:1510.06567.
.. [6] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014).
Regularized discrete optimal transport. SIAM Journal on Imaging
Sciences, 7(3), 1853-1882.
"""
def __init__(self, reg_e=1., reg_cl=0.1,
max_iter=10, max_inner_iter=200,
tol=10e-9, verbose=False, log=False,
metric="sqeuclidean", norm=None,
distribution_estimation=distribution_estimation_uniform,
out_of_sample_map='ferradans', limit_max=10):
self.reg_e = reg_e
self.reg_cl = reg_cl
self.max_iter = max_iter
self.max_inner_iter = max_inner_iter
self.tol = tol
self.verbose = verbose
self.log = log
self.metric = metric
self.norm = norm
self.distribution_estimation = distribution_estimation
self.out_of_sample_map = out_of_sample_map
self.limit_max = limit_max
def fit(self, Xs, ys=None, Xt=None, yt=None):
"""Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt)
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, shape (n_source_samples,)
The 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 unlabeled, fill the
yt's elements with -1.
Warning: Note that, due to this convention -1 cannot be used as a
class label
Returns
-------
self : object
Returns self.
"""
# check the necessary inputs parameters are here
if check_params(Xs=Xs, Xt=Xt, ys=ys):
super(SinkhornL1l2Transport, self).fit(Xs, ys, Xt, yt)
returned_ = sinkhorn_l1l2_gl(
a=self.mu_s, labels_a=ys, b=self.mu_t, M=self.cost_,
reg=self.reg_e, eta=self.reg_cl, numItermax=self.max_iter,
numInnerItermax=self.max_inner_iter, stopInnerThr=self.tol,
verbose=self.verbose, log=self.log)
# deal with the value of log
if self.log:
self.coupling_, self.log_ = returned_
else:
self.coupling_ = returned_
self.log_ = dict()
return self
class MappingTransport(BaseEstimator):
"""MappingTransport: DA methods that aims at jointly estimating a optimal
transport coupling and the associated mapping
Parameters
----------
mu : float, optional (default=1)
Weight for the linear OT loss (>0)
eta : float, optional (default=0.001)
Regularization term for the linear mapping L (>0)
bias : bool, optional (default=False)
Estimate linear mapping with constant bias
metric : string, optional (default="sqeuclidean")
The ground metric for the Wasserstein problem
norm : string, optional (default=None)
If given, normalize the ground metric to avoid numerical errors that
can occur with large metric values.
kernel : string, optional (default="linear")
The kernel to use either linear or gaussian
sigma : float, optional (default=1)
The gaussian kernel parameter
max_iter : int, optional (default=100)
Max number of BCD iterations
tol : float, optional (default=1e-5)
Stop threshold on relative loss decrease (>0)
max_inner_iter : int, optional (default=10)
Max number of iterations (inner CG solver)
inner_tol : float, optional (default=1e-6)
Stop threshold on error (inner CG solver) (>0)
log : bool, optional (default=False)
record log if True
verbose : bool, optional (default=False)
Print information along iterations
verbose2 : bool, optional (default=False)
Print information along iterations
Attributes
----------
coupling_ : array-like, shape (n_source_samples, n_target_samples)
The optimal coupling
mapping_ : array-like, shape (n_features (+ 1), n_features)
(if bias) for kernel == linear
The associated mapping
array-like, shape (n_source_samples (+ 1), n_features)
(if bias) for kernel == gaussian
log_ : dictionary
The dictionary of log, empty dic if parameter log is not True
References
----------
.. [8] M. Perrot, N. Courty, R. Flamary, A. Habrard,
"Mapping estimation for discrete optimal transport",
Neural Information Processing Systems (NIPS), 2016.
"""
def __init__(self, mu=1, eta=0.001, bias=False, metric="sqeuclidean",
norm=None, kernel="linear", sigma=1, max_iter=100, tol=1e-5,
max_inner_iter=10, inner_tol=1e-6, log=False, verbose=False,
verbose2=False):
self.metric = metric
self.norm = norm
self.mu = mu
self.eta = eta
self.bias = bias
self.kernel = kernel
self.sigma = sigma
self.max_iter = max_iter
self.tol = tol
self.max_inner_iter = max_inner_iter
self.inner_tol = inner_tol
self.log = log
self.verbose = verbose
self.verbose2 = verbose2
def fit(self, Xs=None, ys=None, Xt=None, yt=None):
"""Builds an optimal coupling and estimates the associated mapping
from source and target sets of samples (Xs, ys) and (Xt, yt)
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, shape (n_source_samples,)
The 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 unlabeled, fill the
yt's elements with -1.
Warning: Note that, due to this convention -1 cannot be used as a
class label
Returns
-------
self : object
Returns self
"""
# check the necessary inputs parameters are here
if check_params(Xs=Xs, Xt=Xt):
self.xs_ = Xs
self.xt_ = Xt
if self.kernel == "linear":
returned_ = joint_OT_mapping_linear(
Xs, Xt, mu=self.mu, eta=self.eta, bias=self.bias,
verbose=self.verbose, verbose2=self.verbose2,
numItermax=self.max_iter,
numInnerItermax=self.max_inner_iter, stopThr=self.tol,
stopInnerThr=self.inner_tol, log=self.log)
elif self.kernel == "gaussian":
returned_ = joint_OT_mapping_kernel(
Xs, Xt, mu=self.mu, eta=self.eta, bias=self.bias,
sigma=self.sigma, verbose=self.verbose,
verbose2=self.verbose, numItermax=self.max_iter,
numInnerItermax=self.max_inner_iter,
stopInnerThr=self.inner_tol, stopThr=self.tol,
log=self.log)
# deal with the value of log
if self.log:
self.coupling_, self.mapping_, self.log_ = returned_
else:
self.coupling_, self.mapping_ = returned_
self.log_ = dict()
return self
def transform(self, Xs):
"""Transports source samples Xs onto target ones Xt
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
Returns
-------
transp_Xs : array-like, shape (n_source_samples, n_features)
The transport source samples.
"""
# check the necessary inputs parameters are here
if check_params(Xs=Xs):
if np.array_equal(self.xs_, Xs):
# perform standard barycentric mapping
transp = self.coupling_ / np.sum(self.coupling_, 1)[:, None]
# set nans to 0
transp[~ np.isfinite(transp)] = 0
# compute transported samples
transp_Xs = np.dot(transp, self.xt_)
else:
if self.kernel == "gaussian":
K = kernel(Xs, self.xs_, method=self.kernel,
sigma=self.sigma)
elif self.kernel == "linear":
K = Xs
if self.bias:
K = np.hstack((K, np.ones((Xs.shape[0], 1))))
transp_Xs = K.dot(self.mapping_)
return transp_Xs
class UnbalancedSinkhornTransport(BaseTransport):
"""Domain Adapatation unbalanced OT method based on sinkhorn algorithm
Parameters
----------
reg_e : float, optional (default=1)
Entropic regularization parameter
reg_m : float, optional (default=0.1)
Mass regularization parameter
method : str
method used for the solver either 'sinkhorn', 'sinkhorn_stabilized' or
'sinkhorn_epsilon_scaling', see those function for specific parameters
max_iter : int, float, optional (default=10)
The minimum number of iteration before stopping the optimization
algorithm if no it has not converged
tol : float, optional (default=10e-9)
Stop threshold on error (inner sinkhorn solver) (>0)
verbose : bool, optional (default=False)
Controls the verbosity of the optimization algorithm
log : bool, optional (default=False)
Controls the logs of the optimization algorithm
metric : string, optional (default="sqeuclidean")
The ground metric for the Wasserstein problem
norm : string, optional (default=None)
If given, normalize the ground metric to avoid numerical errors that
can occur with large metric values.
distribution_estimation : callable, optional (defaults to the uniform)
The kind of distribution estimation to employ
out_of_sample_map : string, optional (default="ferradans")
The kind of out of sample mapping to apply to transport samples
from a domain into another one. Currently the only possible option is
"ferradans" which uses the method proposed in [6].
limit_max: float, optional (default=10)
Controls the semi supervised mode. Transport between labeled source
and target samples of different classes will exhibit an infinite cost
(10 times the maximum value of the cost matrix)
Attributes
----------
coupling_ : array-like, shape (n_source_samples, n_target_samples)
The optimal coupling
log_ : dictionary
The dictionary of log, empty dic if parameter log is not True
References
----------
.. [1] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
Scaling algorithms for unbalanced transport problems. arXiv preprint
arXiv:1607.05816.
.. [6] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014).
Regularized discrete optimal transport. SIAM Journal on Imaging
Sciences, 7(3), 1853-1882.
"""
def __init__(self, reg_e=1., reg_m=0.1, method='sinkhorn',
max_iter=10, tol=1e-9, verbose=False, log=False,
metric="sqeuclidean", norm=None,
distribution_estimation=distribution_estimation_uniform,
out_of_sample_map='ferradans', limit_max=10):
self.reg_e = reg_e
self.reg_m = reg_m
self.method = method
self.max_iter = max_iter
self.tol = tol
self.verbose = verbose
self.log = log
self.metric = metric
self.norm = norm
self.distribution_estimation = distribution_estimation
self.out_of_sample_map = out_of_sample_map
self.limit_max = limit_max
def fit(self, Xs, ys=None, Xt=None, yt=None):
"""Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt)
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, shape (n_source_samples,)
The 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 unlabeled, fill the
yt's elements with -1.
Warning: Note that, due to this convention -1 cannot be used as a
class label
Returns
-------
self : object
Returns self.
"""
# check the necessary inputs parameters are here
if check_params(Xs=Xs, Xt=Xt):
super(UnbalancedSinkhornTransport, self).fit(Xs, ys, Xt, yt)
returned_ = sinkhorn_unbalanced(
a=self.mu_s, b=self.mu_t, M=self.cost_,
reg=self.reg_e, reg_m=self.reg_m, method=self.method,
numItermax=self.max_iter, stopThr=self.tol,
verbose=self.verbose, log=self.log)
# deal with the value of log
if self.log:
self.coupling_, self.log_ = returned_
else:
self.coupling_ = returned_
self.log_ = dict()
return self
class JCPOTTransport(BaseTransport):
"""Domain Adapatation OT method for multi-source target shift based on Wasserstein barycenter algorithm.
Parameters
----------
reg_e : float, optional (default=1)
Entropic regularization parameter
max_iter : int, float, optional (default=10)
The minimum number of iteration before stopping the optimization
algorithm if no it has not converged
tol : float, optional (default=10e-9)
Stop threshold on error (inner sinkhorn solver) (>0)
verbose : bool, optional (default=False)
Controls the verbosity of the optimization algorithm
log : bool, optional (default=False)
Controls the logs of the optimization algorithm
metric : string, optional (default="sqeuclidean")
The ground metric for the Wasserstein problem
norm : string, optional (default=None)
If given, normalize the ground metric to avoid numerical errors that
can occur with large metric values.
distribution_estimation : callable, optional (defaults to the uniform)
The kind of distribution estimation to employ
out_of_sample_map : string, optional (default="ferradans")
The kind of out of sample mapping to apply to transport samples
from a domain into another one. Currently the only possible option is
"ferradans" which uses the method proposed in [6].
Attributes
----------
coupling_ : list of array-like objects, shape K x (n_source_samples, n_target_samples)
A set of optimal couplings between each source domain and the target domain
proportions_ : array-like, shape (n_classes,)
Estimated class proportions in the target domain
log_ : dictionary
The dictionary of log, empty dic if parameter log is not True
References
----------
.. [1] Ievgen Redko, Nicolas Courty, Rémi Flamary, Devis Tuia
"Optimal transport for multi-source domain adaptation under target shift",
International Conference on Artificial Intelligence and Statistics (AISTATS),
vol. 89, p.849-858, 2019.
.. [6] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014).
Regularized discrete optimal transport. SIAM Journal on Imaging
Sciences, 7(3), 1853-1882.
"""
def __init__(self, reg_e=.1, max_iter=10,
tol=10e-9, verbose=False, log=False,
metric="sqeuclidean",
out_of_sample_map='ferradans'):
self.reg_e = reg_e
self.max_iter = max_iter
self.tol = tol
self.verbose = verbose
self.log = log
self.metric = metric
self.out_of_sample_map = out_of_sample_map
def fit(self, Xs, ys=None, Xt=None, yt=None):
"""Building coupling matrices from a list of source and target sets of samples
(Xs, ys) and (Xt, yt)
Parameters
----------
Xs : list of K array-like objects, shape K x (nk_source_samples, n_features)
A list of the training input samples.
ys : list of K array-like objects, shape K x (nk_source_samples,)
A list of the 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 unlabeled, fill the
yt's elements with -1.
Warning: Note that, due to this convention -1 cannot be used as a
class label
Returns
-------
self : object
Returns self.
"""
# check the necessary inputs parameters are here
if check_params(Xs=Xs, Xt=Xt, ys=ys):
self.xs_ = Xs
self.xt_ = Xt
returned_ = jcpot_barycenter(Xs=Xs, Ys=ys, Xt=Xt, reg=self.reg_e,
metric=self.metric, distrinumItermax=self.max_iter, stopThr=self.tol,
verbose=self.verbose, log=True)
self.coupling_ = returned_[1]['gamma']
# deal with the value of log
if self.log:
self.proportions_, self.log_ = returned_
else:
self.proportions_ = returned_
self.log_ = dict()
return self
def transform(self, Xs=None, ys=None, Xt=None, yt=None, batch_size=128):
"""Transports source samples Xs onto target ones Xt
Parameters
----------
Xs : list of K array-like objects, shape K x (nk_source_samples, n_features)
A list of the training input samples.
ys : list of K array-like objects, shape K x (nk_source_samples,)
A list of the 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 unlabeled, fill the
yt'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
"""
transp_Xs = []
# check the necessary inputs parameters are here
if check_params(Xs=Xs):
if all([np.allclose(x, y) for x, y in zip(self.xs_, Xs)]):
# perform standard barycentric mapping for each source domain
for coupling in self.coupling_:
transp = coupling / np.sum(coupling, 1)[:, None]
# set nans to 0
transp[~ np.isfinite(transp)] = 0
# compute transported samples
transp_Xs.append(np.dot(transp, self.xt_))
else:
# perform out of sample mapping
indices = np.arange(Xs.shape[0])
batch_ind = [
indices[i:i + batch_size]
for i in range(0, len(indices), batch_size)]
transp_Xs = []
for bi in batch_ind:
transp_Xs_ = []
# get the nearest neighbor in the sources domains
xs = np.concatenate(self.xs_, axis=0)
idx = np.argmin(dist(Xs[bi], xs), axis=1)
# transport the source samples
for coupling in self.coupling_:
transp = coupling / np.sum(
coupling, 1)[:, None]
transp[~ np.isfinite(transp)] = 0
transp_Xs_.append(np.dot(transp, self.xt_))
transp_Xs_ = np.concatenate(transp_Xs_, axis=0)
# define the transported points
transp_Xs_ = transp_Xs_[idx, :] + Xs[bi] - xs[idx, :]
transp_Xs.append(transp_Xs_)
transp_Xs = np.concatenate(transp_Xs, axis=0)
return transp_Xs
def transform_labels(self, ys=None):
"""Propagate source labels ys to obtain target labels as in [27]
Parameters
----------
ys : list of K array-like objects, shape K x (nk_source_samples,)
A list of the class labels
Returns
-------
yt : array-like, shape (n_target_samples, nb_classes)
Estimated soft target labels.
"""
# check the necessary inputs parameters are here
if check_params(ys=ys):
yt = np.zeros((len(np.unique(np.concatenate(ys))), self.xt_.shape[0]))
for i in range(len(ys)):
ysTemp = label_normalization(np.copy(ys[i]))
classes = np.unique(ysTemp)
n = len(classes)
ns = len(ysTemp)
# perform label propagation
transp = self.coupling_[i] / np.sum(self.coupling_[i], 1)[:, None]
# set nans to 0
transp[~ np.isfinite(transp)] = 0
if self.log:
D1 = self.log_['D1'][i]
else:
D1 = np.zeros((n, ns))
for c in classes:
D1[int(c), ysTemp == c] = 1
# compute propagated labels
yt = yt + np.dot(D1, transp) / len(ys)
return yt.T
def inverse_transform_labels(self, yt=None):
"""Propagate source labels ys to obtain target labels
Parameters
----------
yt : array-like, shape (n_source_samples,)
The target class labels
Returns
-------
transp_ys : list of K array-like objects, shape K x (nk_source_samples, nb_classes)
A list of estimated soft source labels
"""
# check the necessary inputs parameters are here
if check_params(yt=yt):
transp_ys = []
ytTemp = label_normalization(np.copy(yt))
classes = np.unique(ytTemp)
n = len(classes)
D1 = np.zeros((n, len(ytTemp)))
for c in classes:
D1[int(c), ytTemp == c] = 1
for i in range(len(self.xs_)):
# perform label propagation
transp = self.coupling_[i] / np.sum(self.coupling_[i], 1)[:, None]
# set nans to 0
transp[~ np.isfinite(transp)] = 0
# compute propagated labels
transp_ys.append(np.dot(D1, transp.T).T)
return transp_ys
|