-
Notifications
You must be signed in to change notification settings - Fork 9
/
oad_experiments.py
188 lines (161 loc) · 6.26 KB
/
oad_experiments.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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
from pathlib import Path
import argparse
import pytorch_lightning as pl
from pytorch_lightning import loggers as pl_loggers
from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor
from utils.settings.config import RANDOM_SEED
from utils.OAD_datamodule import OADDataModule
from model.OAD_LSTM import LSTM
from model.OAD_Transformer import Transformer
from model.OAD_TempCNN import TempCNN
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
# Set seed for everything
pl.seed_everything(RANDOM_SEED)
def main():
args = parse_args()
print(args)
# Create folders for saving and/or retrieving useful files for dataloaders
log_path = Path('logs')
log_path.mkdir(exist_ok=True, parents=True)
# Trainer callbacks
callbacks = []
monitor = 'val_loss'
mode = 'min'
run_path = log_path / args.model / f'{args.prefix}'
run_path.mkdir(exist_ok=True, parents=True)
min_epochs = 1
max_epochs = args.num_epochs + 1
check_val_every_n_epoch = 1
tb_logger = pl_loggers.TensorBoardLogger(run_path / 'tensorboard')
selected_classes = {
110: 'Wheat',
120: 'Maize',
140: 'Sorghum',
150: 'Barley',
160: 'Rye',
170: 'Oats',
330: 'Grapes',
435: 'Rapeseed',
438: 'Sunflower',
510: 'Potatoes',
770: 'Peas'
}
linear_encoder = {key: i for i, key in enumerate(sorted(selected_classes.keys()))}
name_decoder = {str(i): str(selected_classes[key]) for i, key in enumerate(sorted(selected_classes.keys()))}
id_decoder = {str(i): str(key) for i, key in enumerate(sorted(selected_classes.keys()))}
# Load models
if args.model.lower() == 'lstm':
model = LSTM(
num_classes=len(linear_encoder),
name_decoder=name_decoder,
id_decoder=id_decoder,
lr=args.lr,
input_size=26,
hidden_size=args.hidden_size,
num_layers=args.num_layers,
batch_size=args.batch_size,
bidirectional=args.bidirectional
)
elif args.model.lower() == 'transformer':
model = Transformer(
d_model=26,
name_decoder=name_decoder,
id_decoder=id_decoder,
num_layers=args.num_layers,
dim_feedforward=args.hidden_size,
nhead=2,
dropout=0.1,
batch_size=args.batch_size,
batch_first=True,
norm_first=False,
num_classes=len(linear_encoder)
)
elif args.model.lower() == 'tempcnn':
model = TempCNN(
input_size=26,
sequencelength=7,
hidden_size=128,
kernel_size=7,
name_decoder=name_decoder,
id_decoder=id_decoder,
batch_size=args.batch_size,
num_classes=len(linear_encoder),
lr=args.lr,
dropout=0.2
)
else:
print('Invalid model!')
exit(1)
if args.train:
callbacks.append(
LearningRateMonitor(logging_interval='step')
)
callbacks.append(
EarlyStopping(
monitor=monitor,
mode=mode
)
)
callbacks.append(
ModelCheckpoint(
dirpath=run_path / 'checkpoints',
monitor=monitor,
filename='model_best',
mode=mode,
save_top_k=1
)
)
dm = OADDataModule(
file=Path(args.file),
batch_size=args.batch_size,
num_workers=args.num_workers,
linear_encoder=linear_encoder
)
trainer = pl.Trainer(gpus=[args.num_gpus],
num_nodes=args.num_nodes,
min_epochs=min_epochs,
max_epochs=max_epochs,
check_val_every_n_epoch=check_val_every_n_epoch,
callbacks=callbacks,
logger=tb_logger,
enable_checkpointing=True,
resume_from_checkpoint=args.checkpoint if args.checkpoint is not None else None,
fast_dev_run=args.fast_dev_run
)
# Train model
trainer.fit(model, datamodule=dm)
else:
dm = OADDataModule(
file=Path(args.file),
batch_size=args.batch_size,
num_workers=args.num_workers,
linear_encoder=linear_encoder
)
trainer = pl.Trainer(gpus=[args.num_gpus],
num_nodes=args.num_nodes,
logger=tb_logger
)
# Load weights from checkpoint
model = model.load_from_checkpoint(args.checkpoint)
model.eval()
trainer.test(model, datamodule=dm)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--train', action='store_true', default=True, required=False)
parser.add_argument('--checkpoint', type=str, default=None, required=False)
parser.add_argument('--model', type=str, required=False, choices=['lstm', 'transformer', 'tempcnn'], default='tempcnn')
parser.add_argument('--prefix', type=str, required=False, default='exp1')
parser.add_argument('--file', type=str, required=False, default='dataset/oad/exp1_patches2000_strat_coco')
parser.add_argument('--num_epochs', type=int, default=10, required=False)
parser.add_argument('--batch_size', type=int, default=512, required=False)
parser.add_argument('--lr', type=float, default=1e-3, required=False)
parser.add_argument('--num_workers', type=int, default=6, required=False)
parser.add_argument('--num_gpus', type=int, default=0, required=False)
parser.add_argument('--num_nodes', type=int, default=1, required=False)
parser.add_argument('--fast_dev_run', action='store_true', default=False, required=False)
parser.add_argument('--hidden_size', type=int, default=512, required=False)
parser.add_argument('--num_layers', type=int, default=3, required=False)
parser.add_argument('--bidirectional', action='store_true', default=False, required=False)
return parser.parse_args()
if __name__ == '__main__':
main()