-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodels.py
More file actions
88 lines (78 loc) · 2.64 KB
/
models.py
File metadata and controls
88 lines (78 loc) · 2.64 KB
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
import torch
import torch.nn as nn
import numpy as np
class Ann(nn.Module):
def __init__(self, input_size):
super(Ann, self).__init__()
self.model = nn.Sequential(
nn.Linear(input_size, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 1),
nn.Sigmoid()
)
def forward(self, X):
return self.model(X)
class Classifier(nn.Module):
def __init__(self, input_size, num_classes):
super(Classifier, self).__init__()
# self.model = nn.Sequential(
# nn.Linear(input_size, 128),
# nn.ReLU(),
# nn.Linear(128, 64),
# nn.ReLU(),
# nn.Linear(64, num_classes)
# )
self.model = nn.Sequential(
nn.Linear(input_size, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, num_classes)
)
def forward(self, X):
return self.model(X)
def fit(self, X_train, y_train, batch_size=64, num_epochs=20):
n, d = X_train.shape
optim = torch.optim.Adam(self.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()
print(np.bincount(y_train))
ind = np.arange(n)
num_splits = int(n/batch_size) + 1
ind_splits = np.array_split(ind, num_splits)
for epoch in range(num_epochs):
for it in range(len(ind_splits)):
i = ind_splits[it]
currX = torch.FloatTensor(X_train[i])
curry = torch.LongTensor(y_train[i])
optim.zero_grad()
output = self(currX)
loss = criterion(output, curry)
loss.backward()
optim.step()
def predict(self, X):
with torch.no_grad():
X = torch.FloatTensor(X)
output = torch.argmax(self(X).detach(), dim=1).numpy()
return output
class Generator(nn.Module):
def __init__(self, input_size, data_length, output_size):
super(Generator, self).__init__()
# self.model = nn.Sequential(
# nn.Linear(data_length+input_size, 128),
# nn.LeakyReLU(0.1),
# nn.Linear(128, output_size),
# nn.Sigmoid()
# )
self.model = nn.Sequential(
nn.Linear(data_length+input_size, 128),
nn.LeakyReLU(0.1),
# nn.Linear(128, 64),
# nn.LeakyReLU(0.1),
nn.Linear(128, output_size),
nn.Sigmoid()
)
def forward(self, x1, x2):
inp = torch.cat([x1, x2], dim=1)
return self.model(inp)