-
Notifications
You must be signed in to change notification settings - Fork 177
/
pytorch_simple.py
128 lines (98 loc) · 4.02 KB
/
pytorch_simple.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
"""
Optuna multi-objective optimization example that optimizes multi-layer perceptrons using PyTorch.
In this example, we optimize the neural network architecture as well as the optimizer configuration
by considering the validation accuracy of fashion product recognition (FashionMNIST dataset) and
the FLOPS of the PyTorch model. As it is too time consuming to use the whole FashionMNIST dataset,
we here use a small subset of it.
"""
import os
from fvcore.nn import FlopCountAnalysis
import optuna
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
from torchvision import datasets
from torchvision import transforms
DEVICE = torch.device("cpu")
BATCHSIZE = 128
CLASSES = 10
DIR = os.getcwd()
EPOCHS = 10
LOG_INTERVAL = 10
N_TRAIN_EXAMPLES = BATCHSIZE * 30
N_VAL_EXAMPLES = BATCHSIZE * 10
def define_model(trial):
# We optimize the number of layers, hidden untis and dropout ratio in each layer.
n_layers = trial.suggest_int("n_layers", 1, 3)
layers = []
in_features = 28 * 28
for i in range(n_layers):
out_features = trial.suggest_int("n_units_l{}".format(i), 4, 128)
layers.append(nn.Linear(in_features, out_features))
layers.append(nn.ReLU())
p = trial.suggest_float("dropout_l{}".format(i), 0.2, 0.5)
layers.append(nn.Dropout(p))
in_features = out_features
layers.append(nn.Linear(in_features, CLASSES))
layers.append(nn.LogSoftmax(dim=1))
return nn.Sequential(*layers)
def get_mnist():
# Load FashionMNIST dataset.
train_dataset = datasets.FashionMNIST(
DIR, train=True, download=True, transform=transforms.ToTensor()
)
train_loader = torch.utils.data.DataLoader(
torch.utils.data.Subset(train_dataset, list(range(N_TRAIN_EXAMPLES))),
batch_size=BATCHSIZE,
shuffle=True,
)
val_dataset = datasets.FashionMNIST(DIR, train=False, transform=transforms.ToTensor())
val_loader = torch.utils.data.DataLoader(
torch.utils.data.Subset(val_dataset, list(range(N_VAL_EXAMPLES))),
batch_size=BATCHSIZE,
shuffle=True,
)
return train_loader, val_loader
def objective(trial):
# Generate the model.
model = define_model(trial).to(DEVICE)
# Generate the optimizers.
optimizer_name = trial.suggest_categorical("optimizer", ["Adam", "RMSprop", "SGD"])
lr = trial.suggest_float("lr", 1e-5, 1e-1)
optimizer = getattr(optim, optimizer_name)(model.parameters(), lr=lr)
# Get the FashionMNIST dataset.
train_loader, val_loader = get_mnist()
# Training of the model.
model.train()
for epoch in range(EPOCHS):
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.view(-1, 28 * 28).to(DEVICE), target.to(DEVICE)
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
# Validation of the model.
model.eval()
correct = 0
with torch.no_grad():
for batch_idx, (data, target) in enumerate(val_loader):
data, target = data.view(-1, 28 * 28).to(DEVICE), target.to(DEVICE)
output = model(data)
pred = output.argmax(dim=1, keepdim=True) # Get the index of the max log-probability.
correct += pred.eq(target.view_as(pred)).sum().item()
accuracy = correct / N_VAL_EXAMPLES
flops = FlopCountAnalysis(model, inputs=(torch.randn(1, 28 * 28).to(DEVICE),)).total()
return flops, accuracy
if __name__ == "__main__":
study = optuna.create_study(directions=["minimize", "maximize"])
study.optimize(objective, n_trials=100)
print("Number of finished trials: ", len(study.trials))
print("Pareto front:")
trials = sorted(study.best_trials, key=lambda t: t.values)
for trial in trials:
print(" Trial#{}".format(trial.number))
print(" Values: FLOPS={}, accuracy={}".format(trial.values[0], trial.values[1]))
print(" Params: {}".format(trial.params))