Divergence domain adaptation methods.

This example illustrates the DeepCoral method from [1] 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 DeepCoral
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_train(as_sources=["mnist"], as_targets=["usps"])
X_test, y_test, sample_domain_test = dataset.pack_test(as_targets=["usps"])
  0%|          | 0.00/9.91M [00:00<?, ?B/s]
100%|██████████| 9.91M/9.91M [00:00<00:00, 138MB/s]

  0%|          | 0.00/28.9k [00:00<?, ?B/s]
100%|██████████| 28.9k/28.9k [00:00<00:00, 83.8MB/s]

  0%|          | 0.00/1.65M [00:00<?, ?B/s]
100%|██████████| 1.65M/1.65M [00:00<00:00, 138MB/s]

  0%|          | 0.00/4.54k [00:00<?, ?B/s]
100%|██████████| 4.54k/4.54k [00:00<00:00, 15.4MB/s]
/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)

  0%|          | 0.00/1.83M [00:00<?, ?B/s]
  2%|▏         | 32.8k/1.83M [00:00<00:11, 160kB/s]
  4%|▎         | 65.5k/1.83M [00:00<00:11, 161kB/s]
  5%|▌         | 98.3k/1.83M [00:00<00:10, 161kB/s]
 13%|█▎        | 229k/1.83M [00:00<00:04, 350kB/s]
 25%|██▌       | 459k/1.83M [00:01<00:02, 629kB/s]
 48%|████▊     | 885k/1.83M [00:01<00:00, 1.12MB/s]
 97%|█████████▋| 1.77M/1.83M [00:01<00:00, 2.17MB/s]
100%|██████████| 1.83M/1.83M [00:01<00:00, 1.28MB/s]

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.3754  4.6986
      2        0.2157  4.8998
      3        0.0850  4.9961
      4        0.0488  4.6022
      5        0.0339  4.3946

0.8842443729903537

Train a DeepCoral model

model = DeepCoral(
    MNISTtoUSPSNet(),
    layer_name="fc1",
    batch_size=128,
    max_epochs=5,
    train_split=False,
    reg=1,
    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.6878  9.0908
      2        0.5023  8.5998
      3        0.1864  9.4966
      4        0.1014  9.9046
      5        0.0771  9.5024

0.8938906752411575

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

Gallery generated by Sphinx-Gallery