-
Notifications
You must be signed in to change notification settings - Fork 2
/
Train.py
197 lines (155 loc) · 7.26 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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#!/usr/bin/python3
from src.Evaluator import *
from src.Classifier import Classifier
from src.Trainer import Trainer
import settings.DataSettings as dataSettings
import time
class Main:
def __init__(self):
classifier = Classifier()
classifier.Build()
# Trainer, Evaluator
print("Reading Training set...")
self.trainer = Trainer(classifier)
self.trainEvaluator = Evaluator("train", dataSettings.PATH_TO_TRAIN_SET_CATELOG, classifier)
print("\t Done.\n")
print("Reading Validation set...")
self.validationEvaluator = Evaluator("validation", dataSettings.PATH_TO_VAL_SET_CATELOG, classifier)
print("\t Done.\n")
print("Reading Test set...")
self.testEvaluator = Evaluator("test", dataSettings.PATH_TO_TEST_SET_CATELOG, classifier)
print("\t Done.\n")
# Summary
summaryOp = tf.summary.merge_all()
self.trainer.SetMergedSummaryOp(summaryOp)
self.trainEvaluator.SetMergedSummaryOp(summaryOp)
self.validationEvaluator.SetMergedSummaryOp(summaryOp)
self.bestThreshold = None
self.testEvaluator.SetMergedSummaryOp(summaryOp)
# Time
self._startTrainEpochTime = time.time()
self._trainCountInOneEpoch = 0
# Saver
self.modelSaver = tf.train.Saver(max_to_keep=trainSettings.MAX_TRAINING_SAVE_MODEL)
# Session
self.session = tf.Session()
init = tf.global_variables_initializer()
self.session.run(init)
self.trainer.SetGraph(self.session.graph)
self.validationEvaluator.SetGraph(self.session.graph)
def __del__(self):
self.session.close()
def Run(self):
self.recoverFromPretrainModelIfRequired()
self.calculateValidationBeforeTraining()
self.resetTimeMeasureVariables()
print("Path to save mode: ", trainSettings.PATH_TO_SAVE_MODEL)
print("\nStart Training...\n")
while self.trainer.currentEpoch < trainSettings.MAX_TRAINING_EPOCH:
self.trainer.PrepareNewBatchData()
self.trainer.Train(self.session)
self._trainCountInOneEpoch += 1
if self.trainer.isNewEpoch:
print("Epoch:", self.trainer.currentEpoch, "======================================"
+ "======================================"
+ "======================================")
self.printTimeMeasurement()
self.trainer.PauseDataLoading()
self.evaluateValidationSetAndPrint(self.trainer.currentEpoch)
self.evaluateTrainingSetAndPrint(self.trainer.currentEpoch)
if trainSettings.PERFORM_DATA_AUGMENTATION:
# Preload TrainBatch while evaluate the TestSet
self.trainer.ContinueDataLoading()
self.evaluateTestSetAndPrint(self.trainer.currentEpoch)
self.trainer.ContinueDataLoading()
self.resetTimeMeasureVariables()
if self.trainer.currentEpoch >= trainSettings.EPOCHS_TO_START_SAVE_MODEL:
self.saveCheckpoint(self.trainer.currentEpoch)
print("Optimization finished.")
self.trainer.Release()
self.trainEvaluator.Release()
self.validationEvaluator.Release()
self.testEvaluator.Release()
def recoverFromPretrainModelIfRequired(self):
if trainSettings.PRETRAIN_MODEL_PATH_NAME != "":
print("Load Pretrain model from: " + trainSettings.PRETRAIN_MODEL_PATH_NAME)
listOfAllVariables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
variablesToBeRecovered = [ eachVariable for eachVariable in listOfAllVariables \
if eachVariable.name.split('/')[0] not in \
trainSettings.NAME_SCOPES_NOT_TO_RECOVER_FROM_CHECKPOINT ]
modelLoader = tf.train.Saver(variablesToBeRecovered)
modelLoader.restore(self.session, trainSettings.PRETRAIN_MODEL_PATH_NAME)
def evaluateTrainingSetAndPrint(self, currentEpoch_):
'''
Since the BATCH_SIZE may be small (= 4 in my case), its BatchLoss or BatchAccuracy
may be fluctuated. Calculate the whole Training Loss instead.
Note: If one want to calculate the BatchLoss ONLY, use Trainer.EvaluateTrainLoss().
'''
startEvaluateTime = time.time()
loss, frameAccuracy, threshold, videoAccuracy = self.trainEvaluator.Evaluate( self.session,
currentEpoch_=currentEpoch_,
threshold_=self.bestThreshold)
endEvaluateTime = time.time()
self.printCalculationResults(jobType_='train', loss_=loss, frameAccuracy_=frameAccuracy,
isThresholdOptimized_=False,
threshold_=threshold, videoAccuracy_=videoAccuracy,
duration_=(endEvaluateTime-startEvaluateTime) )
def calculateValidationBeforeTraining(self):
if trainSettings.PRETRAIN_MODEL_PATH_NAME != "":
print("Validation before Training ", "============================="
+ "======================================"
+ "======================================")
self.evaluateValidationSetAndPrint(currentEpoch_=0)
def evaluateValidationSetAndPrint(self, currentEpoch_):
startEvaluateTime = time.time()
loss, frameAccuracy, threshold, videoAccuracy = self.validationEvaluator.Evaluate(self.session,
currentEpoch_=currentEpoch_,
threshold_=None)
endEvaluateTime = time.time()
self.bestThreshold = threshold
self.printCalculationResults(jobType_='validation', loss_=loss, frameAccuracy_=frameAccuracy,
isThresholdOptimized_=True,
threshold_=threshold, videoAccuracy_=videoAccuracy,
duration_=(endEvaluateTime-startEvaluateTime) )
def evaluateTestSetAndPrint(self, currentEpoch_):
startEvaluateTime = time.time()
loss, frameAccuracy, threshold, videoAccuracy = self.testEvaluator.Evaluate(self.session,
currentEpoch_=currentEpoch_,
threshold_=self.bestThreshold)
endEvaluateTime = time.time()
self.printCalculationResults(jobType_='test', loss_=loss, frameAccuracy_=frameAccuracy,
isThresholdOptimized_=False,
threshold_=threshold, videoAccuracy_=videoAccuracy,
duration_=(endEvaluateTime-startEvaluateTime) )
def printTimeMeasurement(self):
timeForTrainOneEpoch = time.time() - self._startTrainEpochTime
print("\t Back Propergation time measurement:")
print("\t\t duration: ", "{0:.2f}".format(timeForTrainOneEpoch), "s/epoch")
averagedTrainTime = timeForTrainOneEpoch / self._trainCountInOneEpoch
print("\t\t average: ", "{0:.2f}".format(averagedTrainTime), "s/batch")
print()
def resetTimeMeasureVariables(self):
self._startTrainEpochTime = time.time()
self._trainCountInOneEpoch = 0
def printCalculationResults(self, jobType_, loss_, frameAccuracy_, isThresholdOptimized_, threshold_, videoAccuracy_, duration_):
floatPrecision = "{0:.4f}"
print("\t "+jobType_+":")
if isThresholdOptimized_:
print("\t loss:", floatPrecision.format(loss_),
" frame accuracy:", floatPrecision.format(frameAccuracy_),
" best frame threshold:", threshold_,
" video accuracy:", floatPrecision.format(videoAccuracy_),
" duration:", "{0:.2f}".format(duration_) + "(s)\n" )
else:
print("\t loss:", floatPrecision.format(loss_),
" frame accuracy:", floatPrecision.format(frameAccuracy_),
" given frame threshold:", threshold_,
" video accuracy:", floatPrecision.format(videoAccuracy_),
" duration:", "{0:.2f}".format(duration_) + "(s)\n" )
def saveCheckpoint(self, currentEpoch_):
pathToSaveCheckpoint = os.path.join(trainSettings.PATH_TO_SAVE_MODEL, "save_epoch_" + str(currentEpoch_) )
checkpointPathFileName = os.path.join(pathToSaveCheckpoint, "ViolenceNet.ckpt")
self.modelSaver.save(self.session, checkpointPathFileName)
if __name__ == "__main__":
main = Main()
main.Run()