-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathtrain.py
173 lines (159 loc) · 5.45 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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
"""
Describe the training.
"""
import argparse
import os
import json
import numpy as np
import tensorflow as tf
from pathlib import Path
from model.vgg import vgg_model_fn
from model.inception import inception_model_fn
from model.input_fn import input_fn
tf.logging.set_verbosity(tf.logging.INFO)
parser = argparse.ArgumentParser()
parser.add_argument(
'--data_dir',
default='',
help="Directory with processed dataset"
)
parser.add_argument(
'--model_fn',
default="vgg",
help="Model function (vgg or inception)"
)
parser.add_argument(
'--params_file',
default="",
help="Path to the .json file containing the parameters"
)
parser.add_argument(
'--n_steps',
default=0,
help="Number of steps"
)
parser.add_argument(
'--n_epochs',
default=0,
help="Number of epochs"
)
parser.add_argument(
'--debugging',
default=False,
help="Enable the debugging mode (infinite epochs)"
)
if __name__ == '__main__' :
# Parse arguments
args = parser.parse_args()
# Useful variables
if args.model_fn == "vgg":
model_fn = vgg_model_fn
elif args.model_fn == "inception":
model_fn = inception_model_fn
if args.debugging == "True" :
debugging = True
model_dir = None
else :
debugging = False
model_dir = os.path.join("experiments", args.params_file)
n_steps = int(args.n_steps)
n_epochs = int(args.n_epochs)
# Check if .json file exists, then read it
params_file = os.path.join("hyperparameters", args.params_file + ".json")
assert os.path.isfile(params_file), "No .json file found"
with open(params_file) as json_file:
params = json.load(json_file)
print("Parameters used :\n{}".format(params))
# Check if dataset exists
print("Loading dataset from "+args.data_dir)
train_dir = os.path.join(args.data_dir, "train")
assert os.path.isdir(train_dir), "No training directory found"
val_dir = os.path.join(args.data_dir, "val")
assert os.path.isdir(val_dir), "No validation directory found"
# Training data
train_pathlist = Path(train_dir).glob("*.jpg")
train_filenames = [str(path) for path in train_pathlist]
train_filenames = [s for s in train_filenames if int(s.split("_")[1].split('/')[2]) < params["num_classes"]]
train_labels = [int(s.split("_")[1].split('/')[2]) for s in train_filenames]
# Validation data
val_pathlist = Path(val_dir).glob("*.jpg")
val_filenames = [str(path) for path in val_pathlist]
val_filenames = [s for s in val_filenames if int(s.split("_")[1].split('/')[2]) < params["num_classes"]]
val_labels = [int(s.split("_")[1].split('/')[2]) for s in val_filenames]
# Data summary after loading
print("Done loading data")
print("Data summary :\n* Training set size {}\n* Validation set size {}".format(
len(train_filenames),
len(val_filenames))
)
# Create the estimator
print("Creating the custom estimator")
cnn_classifier = tf.estimator.Estimator(
model_fn=model_fn,
model_dir=model_dir,
params=params
)
if debugging :
print("DEBUGGING MODE ENABLED")
print("Training classifier for {} steps".format(n_steps))
cnn_classifier.train(
input_fn=lambda:input_fn(
is_training=True,
num_epochs=-1,
filenames=train_filenames[:10],
labels=train_labels[:10],
batch_size=32
),
steps=n_steps
)
else :
# If the number of epochs is not defined (= 0), then train on number of
# steps and evaluate at the end of the training ...
if (n_epochs == 0) :
print("Training classifier for {} steps".format(n_steps))
cnn_classifier.train(
input_fn=lambda:input_fn(
is_training=True,
num_epochs=1,
filenames=train_filenames,
labels=train_labels,
batch_size=32
),
steps=n_steps
)
val_results = cnn_classifier.evaluate(
input_fn=lambda:input_fn(
is_training=False,
filenames=val_filenames,
labels=val_labels
)
)
# else train on multiple epochs and evaluate every epoch
else :
for i in range(n_epochs) :
cnn_classifier.train(
input_fn=lambda:input_fn(
is_training=True,
num_epochs=1,
filenames=train_filenames,
labels=train_labels,
batch_size=32
)
)
val_results = cnn_classifier.evaluate(
input_fn=lambda:input_fn(
is_training=False,
filenames=val_filenames,
labels=val_labels
)
)
print("Results : \n{}".format(val_results))
print("Done training")
if not debugging :
# Save results to .json file
# But first convert values from float32 to string
for key in val_results :
val_results[key] = str(val_results[key])
with open(os.path.join(model_dir, "results.json"), 'w') as outfile:
json.dump(val_results, outfile)
print("Results saved to {}".format(model_dir))