-
Notifications
You must be signed in to change notification settings - Fork 0
/
digitviz.py
150 lines (119 loc) · 5.62 KB
/
digitviz.py
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
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
import umap
import datasets
import models
import utils
from pathlib import Path
from PIL import Image
def plot_mnist_and_mnistm(dataset, save_dir: Path):
fig, axes = plt.subplots(nrows=2, ncols=10, figsize=(20, 4))
for i in range(10):
axes[0, i].set_title(f"Class {i}")
axes[0, 0].set_ylabel("MNIST", rotation=90, size="large")
axes[1, 0].set_ylabel("MNISTM", rotation=90, size="large")
master_df: pd.DataFrame = dataset.master_df
for i in range(10):
mnist_sample = master_df.query(
f"source == 'mnist' & label == {i}").sample(1).reset_index(drop=True)
mnistm_sample = master_df.query(
f"source == 'mnistm' & label == {i}").sample(1).reset_index(drop=True)
mnist_img_idx = int(mnist_sample.loc[0, "image"].replace(".png", ""))
mnist_image = dataset.mnist_images[mnist_img_idx]
axes[0, i].imshow(mnist_image, cmap="gray")
mnistm_img_path = dataset.mnistm_images_dir / mnistm_sample.loc[0, "image"]
image = Image.open(mnistm_img_path).convert("RGB")
axes[1, i].imshow(image)
axes[0, i].tick_params(labelbottom=False, labelleft=False, bottom=False, left=False)
axes[1, i].tick_params(labelbottom=False, labelleft=False, bottom=False, left=False)
plt.tight_layout()
plt.savefig(save_dir / "mnist_and_mnistm.png")
def load_dann_model_and_device(path: str):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if not torch.cuda.is_available():
weights = torch.load(path, map_location="cpu")
else:
weights = torch.load(path)
model = models.DomainAdversarialCNN()
model.load_state_dict(weights["model_state_dict"])
model.to(device)
model.eval()
return model, device
def load_naive_model_and_device():
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if not torch.cuda.is_available():
weights = torch.load("output/002_digits_naive/fold0/checkpoints/best.pth", map_location="cpu")
else:
weights = torch.load("output/002_digits_naive/fold0/checkpoints/best.pth")
model = models.NaiveClassificationCNN()
model.load_state_dict(weights["model_state_dict"])
model.to(device)
model.eval()
return model, device
def get_representation(loader, model, device):
model.eval()
representations = []
labels = []
domain_labels = []
for image, label, domain_label in loader:
image = image.to(device)
labels.append(label.cpu().numpy().reshape(-1))
domain_labels.append(domain_label.cpu().numpy().reshape(-1))
with torch.no_grad():
batch_size = image.size(0)
output = model.feature_extractor(image).view(batch_size, -1)
representations.append(output.detach().cpu().numpy())
representations = np.concatenate(representations, axis=0)
labels = np.concatenate(labels, axis=0)
domain_labels = np.concatenate(domain_labels, axis=0)
return representations, labels, domain_labels
def umap_plot(representations: np.ndarray, groups: np.ndarray, save_dir: Path, name: str):
transformer = umap.UMAP(
n_components=2,
n_neighbors=5,
random_state=42).fit(representations)
fig = plt.figure(figsize=(11, 11))
ax = fig.add_subplot(111)
ax.tick_params(labelbottom=False, labelleft=False, left=False, bottom=False)
emb0 = transformer.embedding_[:, 0]
emb1 = transformer.embedding_[:, 1]
colors = [
"red", "green", "blue", "orange", "purple", "brown", "fuchsia", "grey",
"olive", "lightblue"
]
unique_groups = np.unique(groups)
for i, group in enumerate(unique_groups):
group_mask = groups == group
group_emb0 = emb0[group_mask]
group_emb1 = emb1[group_mask]
ax.scatter(group_emb0, group_emb1, c=colors[i], label=str(group), alpha=0.5)
ax.legend(loc="upper left", bbox_to_anchor=(1, 1))
plt.tight_layout()
plt.savefig(save_dir / name)
if __name__ == "__main__":
SAVE_DIR = Path("assets/digits")
SAVE_DIR.mkdir(parents=True, exist_ok=True)
utils.set_seed(2019)
dataset = datasets.DigitsDataset(mode="test")
loader = torch.utils.data.DataLoader(dataset, batch_size=32)
plot_mnist_and_mnistm(dataset, SAVE_DIR)
model, device = load_dann_model_and_device("output/000_digits/fold0/checkpoints/best.pth")
representations, labels, domain_labels = get_representation(
loader, model, device)
domain_labels = np.array(["mnist" if i == 0 else "mnistm" for i in domain_labels])
umap_plot(representations, domain_labels, save_dir=SAVE_DIR, name="umap_domain.png")
umap_plot(representations, labels, save_dir=SAVE_DIR, name="umap_classes.png")
model, device = load_dann_model_and_device("output/003_digits_no_warmup/fold0/checkpoints/best.pth")
representations, labels, domain_labels = get_representation(
loader, model, device)
domain_labels = np.array(["mnist" if i == 0 else "mnistm" for i in domain_labels])
umap_plot(representations, domain_labels, save_dir=SAVE_DIR, name="umap_domain_no_warmup.png")
umap_plot(representations, labels, save_dir=SAVE_DIR, name="umap_classes_no_warmup.png")
naive_model, device = load_naive_model_and_device()
representations, labels, domain_labels = get_representation(
loader, naive_model, device)
domain_labels = np.array(["mnist" if i == 0 else "mnistm" for i in domain_labels])
umap_plot(representations, domain_labels, save_dir=SAVE_DIR, name="umap_domain_naive.png")
umap_plot(representations, labels, save_dir=SAVE_DIR, name="umap_classes_naive.png")