Optimal transport domain adaptation methods.

This example illustrates the Optimal Transport deep DA method from on a simple image classification task.

# Author: Théo Gnassounou
#
# License: BSD 3-Clause
# sphinx_gallery_thumbnail_number = 4
from skorch import NeuralNetClassifier
from torch import nn

from skada.datasets import load_mnist_usps
from skada.deep import DeepJDOT
from skada.deep.modules import MNISTtoUSPSNet

Load the image datasets

dataset = load_mnist_usps(n_classes=2, n_samples=0.5, return_dataset=True)
X, y, sample_domain = dataset.pack(
    as_sources=["mnist"], as_targets=["usps"], mask_target_labels=True
)
X_test, y_test, sample_domain_test = dataset.pack(
    as_sources=[], as_targets=["usps"], mask_target_labels=False
)
/home/circleci/project/skada/datasets/_mnist_usps.py:72: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.detach().clone() or sourceTensor.detach().clone().requires_grad_(True), rather than torch.tensor(sourceTensor).
  mnist_target = torch.tensor(mnist_dataset.targets)

Train a classic model

model = NeuralNetClassifier(
    MNISTtoUSPSNet(),
    criterion=nn.CrossEntropyLoss(),
    batch_size=128,
    max_epochs=5,
    train_split=False,
    lr=1e-2,
)
model.fit(X[sample_domain > 0], y[sample_domain > 0])
model.score(X_test, y=y_test)
  epoch    train_loss     dur
-------  ------------  ------
      1        1.4373  4.0998
      2        0.2495  4.2025
      3        0.0963  3.8992
      4        0.0552  4.1050
      5        0.0379  4.0029

0.9453376205787781

Train a DeepJDOT model

model = DeepJDOT(
    MNISTtoUSPSNet(),
    layer_name="fc1",
    batch_size=128,
    max_epochs=5,
    train_split=False,
    reg_dist=0.1,
    reg_cl=0.01,
    lr=1e-2,
)
model.fit(X, y, sample_domain=sample_domain)
model.score(X_test, y_test, sample_domain=sample_domain_test)
  epoch    train_loss     dur
-------  ------------  ------
      1        1.8346  9.2727
      2        0.9986  9.0005
      3        0.6936  8.0017
      4        0.5612  9.1953
      5        0.4975  9.1985

0.9453376205787781

Total running time of the script: (1 minutes 9.070 seconds)

Gallery generated by Sphinx-Gallery