-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
156 lines (147 loc) · 4.93 KB
/
train.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
import os
import gc
import argparse
from distutils.util import strtobool
from datetime import datetime
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.data.dataset import Subset
from sklearn.model_selection import train_test_split
from utils import fix_seed
from utils import get_config
from logger import setup_logging
from trainer import Trainer, EarlyStopping
from models import DeepCrysTet
from datasets import Meshdataset, collate_batch
def main(args, save_dirs, cfg):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
is_regression = True if args.task == "regression" else False
mesh_data = np.load(os.path.join(args.data_path))
target_data = pd.read_csv(args.target_path, names=["mpid", "target"])
dataset = Meshdataset(mesh_data, target_data, is_regression)
feature_dim = dataset.feature_dim
model = DeepCrysTet(feature_dim, is_regression).to(device)
del mesh_data
if args.model_path:
model.load_state_dict(torch.load(args.model_path)["model_state_dict"])
batch_size = args.batch_size or cfg["batch_size"]
train_idx, valid_idx = train_test_split(
list(range(len(dataset))), test_size=0.2, random_state=cfg["seed"], shuffle=True
)
train_dataset = Subset(dataset, train_idx)
train_loader = DataLoader(
train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=cfg["num_workers"],
collate_fn=collate_batch,
pin_memory=True,
)
dataset = Subset(dataset, valid_idx)
valid_idx, test_idx = train_test_split(
list(range(len(dataset))), test_size=0.5, random_state=cfg["seed"], shuffle=True
)
valid_dataset = Subset(dataset, valid_idx)
valid_loader = DataLoader(
valid_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=cfg["num_workers"],
collate_fn=collate_batch,
pin_memory=True,
)
test_dataset = Subset(dataset, test_idx)
test_loader = DataLoader(
test_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=cfg["num_workers"],
collate_fn=collate_batch,
pin_memory=True,
)
del dataset
gc.collect()
if is_regression:
criterion = nn.L1Loss()
else:
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.parameters(), lr=cfg["lr"])
patience = args.es_patience or cfg["es_patience"]
es = EarlyStopping(patience=patience, verbose=True)
# Training
trainer = Trainer(
model,
criterion,
optimizer,
device=device,
train_loader=train_loader,
valid_loader=valid_loader,
test_loader=test_loader,
n_epochs=args.epochs,
es=es,
save_dirs=save_dirs,
amp=strtobool(args.amp),
feature_dim=feature_dim,
is_regression=is_regression,
)
trainer.train()
# Evaluation
trainer.test()
if __name__ == "__main__":
cfg = get_config()
fix_seed(cfg["seed"])
parser = argparse.ArgumentParser()
parser.add_argument("--data-path", type=str, required=True, help="Input data path")
parser.add_argument("--target-path", type=str, required=True, help="Target data path")
parser.add_argument(
"--save-dir", default="./saved", type=str, help="Save directory path (default: ./saved)"
)
parser.add_argument("--epochs", default=20, type=int, help="Number of epochs (default: 20)")
parser.add_argument(
"--model-path",
default=None,
type=str,
help="Model path used for retraining (default: None)",
)
parser.add_argument(
"--batch-size", default=0, type=int, help="The size of batch (default in config.yaml)"
)
parser.add_argument(
"--es-patience",
default=0,
type=int,
help="The number of patience epochs for EarlyStoppings (default in config.yaml)",
)
parser.add_argument(
"--amp",
default="False",
type=str,
help="Use Automatic Mixed Precision (default: False)",
)
parser.add_argument(
"--run-id",
default="",
type=str,
help="Run ID for saving results (default: '')",
)
parser.add_argument(
"--task",
choices=["regression", "classification"],
default="regression",
help="Select `regression` or `classification` task (default: regression)",
)
args = parser.parse_args()
save_dir = args.save_dir
run_id = args.run_id or datetime.now().strftime(r"%Y%m%d_%H%M%S")
save_dirs = dict()
save_dirs["model"] = os.path.join(save_dir, run_id, "models")
save_dirs["log"] = os.path.join(save_dir, run_id, "logs")
save_dirs["tensorboard"] = os.path.join(save_dir, run_id, "tensorboard")
for dir in save_dirs.values():
os.makedirs(dir, exist_ok=True)
setup_logging(save_dirs["log"])
main(args, save_dirs, cfg)