forked from ej0cl6/deep-active-learning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nets.py
160 lines (142 loc) · 5.63 KB
/
nets.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
151
152
153
154
155
156
157
158
159
160
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from tqdm import tqdm
class Net:
def __init__(self, net, params, device):
self.net = net
self.params = params
self.device = device
def train(self, data):
n_epoch = self.params['n_epoch']
self.clf = self.net().to(self.device)
self.clf.train()
optimizer = optim.SGD(self.clf.parameters(), **self.params['optimizer_args'])
loader = DataLoader(data, shuffle=True, **self.params['train_args'])
for epoch in tqdm(range(1, n_epoch+1), ncols=100):
for batch_idx, (x, y, idxs) in enumerate(loader):
x, y = x.to(self.device), y.to(self.device)
optimizer.zero_grad()
out, e1 = self.clf(x)
loss = F.cross_entropy(out, y)
loss.backward()
optimizer.step()
def predict(self, data):
self.clf.eval()
preds = torch.zeros(len(data), dtype=data.Y.dtype)
loader = DataLoader(data, shuffle=False, **self.params['test_args'])
with torch.no_grad():
for x, y, idxs in loader:
x, y = x.to(self.device), y.to(self.device)
out, e1 = self.clf(x)
pred = out.max(1)[1]
preds[idxs] = pred.cpu()
return preds
def predict_prob(self, data):
self.clf.eval()
probs = torch.zeros([len(data), len(np.unique(data.Y))])
loader = DataLoader(data, shuffle=False, **self.params['test_args'])
with torch.no_grad():
for x, y, idxs in loader:
x, y = x.to(self.device), y.to(self.device)
out, e1 = self.clf(x)
prob = F.softmax(out, dim=1)
probs[idxs] = prob.cpu()
return probs
def predict_prob_dropout(self, data, n_drop=10):
self.clf.train()
probs = torch.zeros([len(data), len(np.unique(data.Y))])
loader = DataLoader(data, shuffle=False, **self.params['test_args'])
for i in range(n_drop):
with torch.no_grad():
for x, y, idxs in loader:
x, y = x.to(self.device), y.to(self.device)
out, e1 = self.clf(x)
prob = F.softmax(out, dim=1)
probs[idxs] += prob.cpu()
probs /= n_drop
return probs
def predict_prob_dropout_split(self, data, n_drop=10):
self.clf.train()
probs = torch.zeros([n_drop, len(data), len(np.unique(data.Y))])
loader = DataLoader(data, shuffle=False, **self.params['test_args'])
for i in range(n_drop):
with torch.no_grad():
for x, y, idxs in loader:
x, y = x.to(self.device), y.to(self.device)
out, e1 = self.clf(x)
prob = F.softmax(out, dim=1)
probs[i][idxs] += F.softmax(out, dim=1).cpu()
return probs
def get_embeddings(self, data):
self.clf.eval()
embeddings = torch.zeros([len(data), self.clf.get_embedding_dim()])
loader = DataLoader(data, shuffle=False, **self.params['test_args'])
with torch.no_grad():
for x, y, idxs in loader:
x, y = x.to(self.device), y.to(self.device)
out, e1 = self.clf(x)
embeddings[idxs] = e1.cpu()
return embeddings
class MNIST_Net(nn.Module):
def __init__(self):
super(MNIST_Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
e1 = F.relu(self.fc1(x))
x = F.dropout(e1, training=self.training)
x = self.fc2(x)
return x, e1
def get_embedding_dim(self):
return 50
class SVHN_Net(nn.Module):
def __init__(self):
super(SVHN_Net, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3)
self.conv2 = nn.Conv2d(32, 32, kernel_size=3)
self.conv3 = nn.Conv2d(32, 32, kernel_size=3)
self.conv3_drop = nn.Dropout2d()
self.fc1 = nn.Linear(1152, 400)
self.fc2 = nn.Linear(400, 50)
self.fc3 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(F.max_pool2d(self.conv2(x), 2))
x = F.relu(F.max_pool2d(self.conv3_drop(self.conv3(x)), 2))
x = x.view(-1, 1152)
x = F.relu(self.fc1(x))
e1 = F.relu(self.fc2(x))
x = F.dropout(e1, training=self.training)
x = self.fc3(x)
return x, e1
def get_embedding_dim(self):
return 50
class CIFAR10_Net(nn.Module):
def __init__(self):
super(CIFAR10_Net, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 32, kernel_size=5)
self.conv3 = nn.Conv2d(32, 64, kernel_size=5)
self.fc1 = nn.Linear(1024, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(F.max_pool2d(self.conv2(x), 2))
x = F.relu(F.max_pool2d(self.conv3(x), 2))
x = x.view(-1, 1024)
e1 = F.relu(self.fc1(x))
x = F.dropout(e1, training=self.training)
x = self.fc2(x)
return x, e1
def get_embedding_dim(self):
return 50