---
# System prepended metadata

title: Optimal Transport and Image Classification

---

# Optimal Transport and Image Classification

## February 3, 2023

https://hackmd.io/@ubcs3

```
import numpy as np
import scipy.linalg as la
import matplotlib.pyplot as plt
import cvxpy as cp
from sklearn.datasets import load_digits
```


outside in a terminal:
```
pip install --user cvxpy
```
(I think you can also `!pip install --user cvxpy` from inside the notebook)


```
plt.imshow(images[123])
plt.show()

targets = digits.target
print(type(targets))
targets.shape

from sklearn.neighbors import KNeighborsClassifier as KNN
from sklearn.model_selection import train_test_split as tts

X_train,X_test,y_train,y_test = tts(data,targets,test_size=0.5)

d = 8
C = np.zeros((d,d,d,d))
for i in range(d):
    for j in range(d):
        for k in range(d):
            for l in range(d):
                C[i,j,k,l] = la.norm([i-k,j-l])
```

1-dimensional code:
Building C:
```
d = 8
C = np.zeros((d*d, d*d))
for i in range(d):
    for j in range(d):
        for k in range(d):
            for l in range(d):
                C[i*d + j,k*d + l] = la.norm([i - k, j - l])
```

Building problem:
```
s = images[0]/images[0].sum()
t = images[1]/images[1].sum()
X = cp.Variable((d*d,d*d))
obj = cp.Minimize(cp.sum(cp.multiply(C,X)))
constraints = [X >= 0]
for k in range(d):
    for l in range(d):
        constraints += [cp.sum(X[:,k*d+l]) == t[k,l]]
for i in range(d):
    for j in range(d):
        constraints += [cp.sum(X[i*d+j,:]) == s[i,j]]
prob = cp.Problem(obj, constraints)
prob.solve()

s = images[0]/images[0].sum()
for n in range(20):
    t = images[n]/images[n].sum()
    print(distanceOT(s,t),la.norm(s-t),targets[n])
```

### Notes
