Note
Go to the end to download the full example code.
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(
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
)
0%| | 0.00/9.91M [00:00<?, ?B/s]
100%|██████████| 9.91M/9.91M [00:00<00:00, 137MB/s]
0%| | 0.00/28.9k [00:00<?, ?B/s]
100%|██████████| 28.9k/28.9k [00:00<00:00, 63.9MB/s]
0%| | 0.00/1.65M [00:00<?, ?B/s]
100%|██████████| 1.65M/1.65M [00:00<00:00, 193MB/s]
0%| | 0.00/4.54k [00:00<?, ?B/s]
100%|██████████| 4.54k/4.54k [00:00<00:00, 13.8MB/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:10, 178kB/s]
5%|▌ | 98.3k/1.83M [00:00<00:06, 282kB/s]
11%|█ | 197k/1.83M [00:00<00:04, 396kB/s]
14%|█▍ | 262k/1.83M [00:00<00:04, 379kB/s]
23%|██▎ | 426k/1.83M [00:00<00:02, 563kB/s]
43%|████▎ | 786k/1.83M [00:01<00:01, 1.04MB/s]
82%|████████▏ | 1.51M/1.83M [00:01<00:00, 1.97MB/s]
100%|██████████| 1.83M/1.83M [00:01<00:00, 1.41MB/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.3595 4.3022
2 0.2126 3.7985
3 0.0779 3.8986
4 0.0471 4.0007
5 0.0312 4.1982
0.9421221864951769
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.7040 8.7695
2 0.5670 8.5002
3 0.1910 8.2962
4 0.1018 8.5003
5 0.0748 8.3971
0.8810289389067524
Total running time of the script: (1 minutes 10.850 seconds)