forked from tensorlayer/TensorLayer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
683 lines (568 loc) · 24.9 KB
/
utils.py
File metadata and controls
683 lines (568 loc) · 24.9 KB
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
#! /usr/bin/python
# -*- coding: utf-8 -*-
import os
import random
import subprocess
import sys
import time
from collections import Counter
from sys import exit as _exit
from sys import platform as _platform
import numpy as np
from sklearn.metrics import accuracy_score, confusion_matrix, f1_score
import tensorflow as tf
import tensorlayer as tl
__all__ = [
'fit', 'test', 'predict', 'evaluation', 'dict_to_one', 'flatten_list', 'class_balancing_oversample',
'get_random_int', 'list_string_to_dict', 'exit_tensorflow', 'open_tensorboard', 'clear_all_placeholder_variables',
'set_gpu_fraction', 'train_epoch', 'run_epoch'
]
def fit(
network, train_op, cost, X_train, y_train, acc=None, batch_size=100, n_epoch=100, print_freq=5, X_val=None,
y_val=None, eval_train=True, tensorboard_dir=None, tensorboard_epoch_freq=5, tensorboard_weight_histograms=True,
tensorboard_graph_vis=True
):
"""Training a given non time-series network by the given cost function, training data, batch_size, n_epoch etc.
- MNIST example click `here <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_mnist_simple.py>`_.
- In order to control the training details, the authors HIGHLY recommend ``tl.iterate`` see two MNIST examples `1 <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_mlp_dropout1.py>`_, `2 <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_mlp_dropout1.py>`_.
Parameters
----------
network : TensorLayer Model
the network to be trained.
train_op : TensorFlow optimizer
The optimizer for training e.g. tf.optimizers.Adam().
cost : TensorLayer or TensorFlow loss function
Metric for loss function, e.g tl.cost.cross_entropy.
X_train : numpy.array
The input of training data
y_train : numpy.array
The target of training data
acc : TensorFlow/numpy expression or None
Metric for accuracy or others. If None, would not print the information.
batch_size : int
The batch size for training and evaluating.
n_epoch : int
The number of training epochs.
print_freq : int
Print the training information every ``print_freq`` epochs.
X_val : numpy.array or None
The input of validation data. If None, would not perform validation.
y_val : numpy.array or None
The target of validation data. If None, would not perform validation.
eval_train : boolean
Whether to evaluate the model during training.
If X_val and y_val are not None, it reflects whether to evaluate the model on training data.
tensorboard_dir : string
path to log dir, if set, summary data will be stored to the tensorboard_dir/ directory for visualization with tensorboard. (default None)
tensorboard_epoch_freq : int
How many epochs between storing tensorboard checkpoint for visualization to log/ directory (default 5).
tensorboard_weight_histograms : boolean
If True updates tensorboard data in the logs/ directory for visualization
of the weight histograms every tensorboard_epoch_freq epoch (default True).
tensorboard_graph_vis : boolean
If True stores the graph in the tensorboard summaries saved to log/ (default True).
Examples
--------
See `tutorial_mnist_simple.py <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_mnist_simple.py>`_
>>> tl.utils.fit(network, train_op=tf.optimizers.Adam(learning_rate=0.0001),
... cost=tl.cost.cross_entropy, X_train=X_train, y_train=y_train, acc=acc,
... batch_size=64, n_epoch=20, _val=X_val, y_val=y_val, eval_train=True)
>>> tl.utils.fit(network, train_op, cost, X_train, y_train,
... acc=acc, batch_size=500, n_epoch=200, print_freq=5,
... X_val=X_val, y_val=y_val, eval_train=False, tensorboard=True)
Notes
--------
'tensorboard_weight_histograms' and 'tensorboard_weight_histograms' are not supported now.
"""
if X_train.shape[0] < batch_size:
raise AssertionError("Number of training examples should be bigger than the batch size")
if tensorboard_dir is not None:
tl.logging.info("Setting up tensorboard ...")
#Set up tensorboard summaries and saver
tl.files.exists_or_mkdir(tensorboard_dir)
#Only write summaries for more recent TensorFlow versions
if hasattr(tf, 'summary') and hasattr(tf.summary, 'create_file_writer'):
train_writer = tf.summary.create_file_writer(tensorboard_dir + '/train')
val_writer = tf.summary.create_file_writer(tensorboard_dir + '/validation')
if tensorboard_graph_vis:
# FIXME : not sure how to add tl network graph
pass
else:
train_writer = None
val_writer = None
tl.logging.info("Finished! use `tensorboard --logdir=%s/` to start tensorboard" % tensorboard_dir)
tl.logging.info("Start training the network ...")
start_time_begin = time.time()
for epoch in range(n_epoch):
start_time = time.time()
loss_ep, _, __ = train_epoch(network, X_train, y_train, cost=cost, train_op=train_op, batch_size=batch_size)
train_loss, train_acc = None, None
val_loss, val_acc = None, None
if tensorboard_dir is not None and hasattr(tf, 'summary'):
if epoch + 1 == 1 or (epoch + 1) % tensorboard_epoch_freq == 0:
if eval_train is True:
train_loss, train_acc, _ = run_epoch(
network, X_train, y_train, cost=cost, acc=acc, batch_size=batch_size
)
with train_writer.as_default():
tf.compat.v2.summary.scalar('loss', train_loss, step=epoch)
if acc is not None:
tf.summary.scalar('acc', train_acc, step=epoch)
# FIXME : there seems to be an internal error in Tensorboard (misuse of tf.name_scope)
# if tensorboard_weight_histograms is not None:
# for param in network.all_weights:
# tf.summary.histogram(param.name, param, step=epoch)
if (X_val is not None) and (y_val is not None):
val_loss, val_acc, _ = run_epoch(network, X_val, y_val, cost=cost, acc=acc, batch_size=batch_size)
with val_writer.as_default():
tf.summary.scalar('loss', val_loss, step=epoch)
if acc is not None:
tf.summary.scalar('acc', val_acc, step=epoch)
# FIXME : there seems to be an internal error in Tensorboard (misuse of tf.name_scope)
# if tensorboard_weight_histograms is not None:
# for param in network.all_weights:
# tf.summary.histogram(param.name, param, step=epoch)
if epoch + 1 == 1 or (epoch + 1) % print_freq == 0:
if (X_val is not None) and (y_val is not None):
tl.logging.info("Epoch %d of %d took %fs" % (epoch + 1, n_epoch, time.time() - start_time))
if eval_train is True:
if train_loss is None:
train_loss, train_acc, _ = run_epoch(
network, X_train, y_train, cost=cost, acc=acc, batch_size=batch_size
)
tl.logging.info(" train loss: %f" % train_loss)
if acc is not None:
tl.logging.info(" train acc: %f" % train_acc)
if val_loss is None:
val_loss, val_acc, _ = run_epoch(network, X_val, y_val, cost=cost, acc=acc, batch_size=batch_size)
# tl.logging.info(" val loss: %f" % val_loss)
if acc is not None:
pass
# tl.logging.info(" val acc: %f" % val_acc)
else:
tl.logging.info(
"Epoch %d of %d took %fs, loss %f" % (epoch + 1, n_epoch, time.time() - start_time, loss_ep)
)
tl.logging.info("Total training time: %fs" % (time.time() - start_time_begin))
def test(network, acc, X_test, y_test, batch_size, cost=None):
"""
Test a given non time-series network by the given test data and metric.
Parameters
----------
network : TensorLayer Model
The network.
acc : TensorFlow/numpy expression or None
Metric for accuracy or others.
- If None, would not print the information.
X_test : numpy.array
The input of testing data.
y_test : numpy array
The target of testing data
batch_size : int or None
The batch size for testing, when dataset is large, we should use minibatche for testing;
if dataset is small, we can set it to None.
cost : TensorLayer or TensorFlow loss function
Metric for loss function, e.g tl.cost.cross_entropy. If None, would not print the information.
Examples
--------
See `tutorial_mnist_simple.py <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_mnist_simple.py>`_
>>> def acc(_logits, y_batch):
... return np.mean(np.equal(np.argmax(_logits, 1), y_batch))
>>> tl.utils.test(network, acc, X_test, y_test, batch_size=None, cost=tl.cost.cross_entropy)
"""
tl.logging.info('Start testing the network ...')
network.eval()
if batch_size is None:
y_pred = network(X_test)
if cost is not None:
test_loss = cost(y_pred, y_test)
# tl.logging.info(" test loss: %f" % test_loss)
test_acc = acc(y_pred, y_test)
# tl.logging.info(" test acc: %f" % (test_acc / test_acc))
return test_acc
else:
test_loss, test_acc, n_batch = run_epoch(
network, X_test, y_test, cost=cost, acc=acc, batch_size=batch_size, shuffle=False
)
if cost is not None:
tl.logging.info(" test loss: %f" % test_loss)
tl.logging.info(" test acc: %f" % test_acc)
return test_acc
def predict(network, X, batch_size=None):
"""
Return the predict results of given non time-series network.
Parameters
----------
network : TensorLayer Model
The network.
X : numpy.array
The inputs.
batch_size : int or None
The batch size for prediction, when dataset is large, we should use minibatche for prediction;
if dataset is small, we can set it to None.
Examples
--------
See `tutorial_mnist_simple.py <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_mnist_simple.py>`_
>>> _logits = tl.utils.predict(network, X_test)
>>> y_pred = np.argmax(_logits, 1)
"""
network.eval()
if batch_size is None:
y_pred = network(X)
return y_pred
else:
result = None
for X_a, _ in tl.iterate.minibatches(X, X, batch_size, shuffle=False):
result_a = network(X_a)
if result is None:
result = result_a
else:
result = np.concatenate((result, result_a))
if result is None:
if len(X) % batch_size == 0:
result_a = network(X[-(len(X) % batch_size):, :])
result = result_a
else:
if len(X) != len(result) and len(X) % batch_size != 0:
result_a = network(X[-(len(X) % batch_size):, :])
result = np.concatenate((result, result_a))
return result
## Evaluation
def evaluation(y_test=None, y_predict=None, n_classes=None):
"""
Input the predicted results, targets results and
the number of class, return the confusion matrix, F1-score of each class,
accuracy and macro F1-score.
Parameters
----------
y_test : list
The target results
y_predict : list
The predicted results
n_classes : int
The number of classes
Examples
--------
>>> c_mat, f1, acc, f1_macro = tl.utils.evaluation(y_test, y_predict, n_classes)
"""
c_mat = confusion_matrix(y_test, y_predict, labels=[x for x in range(n_classes)])
f1 = f1_score(y_test, y_predict, average=None, labels=[x for x in range(n_classes)])
f1_macro = f1_score(y_test, y_predict, average='macro')
acc = accuracy_score(y_test, y_predict)
tl.logging.info('confusion matrix: \n%s' % c_mat)
tl.logging.info('f1-score : %s' % f1)
tl.logging.info('f1-score(macro) : %f' % f1_macro) # same output with > f1_score(y_true, y_pred, average='macro')
tl.logging.info('accuracy-score : %f' % acc)
return c_mat, f1, acc, f1_macro
def dict_to_one(dp_dict):
"""Input a dictionary, return a dictionary that all items are set to one.
Used for disable dropout, dropconnect layer and so on.
Parameters
----------
dp_dict : dictionary
The dictionary contains key and number, e.g. keeping probabilities.
"""
return {x: 1 for x in dp_dict}
def flatten_list(list_of_list):
"""Input a list of list, return a list that all items are in a list.
Parameters
----------
list_of_list : a list of list
Examples
--------
>>> tl.utils.flatten_list([[1, 2, 3],[4, 5],[6]])
[1, 2, 3, 4, 5, 6]
"""
return sum(list_of_list, [])
def class_balancing_oversample(X_train=None, y_train=None, printable=True):
"""Input the features and labels, return the features and labels after oversampling.
Parameters
----------
X_train : numpy.array
The inputs.
y_train : numpy.array
The targets.
Examples
--------
One X
>>> X_train, y_train = class_balancing_oversample(X_train, y_train, printable=True)
Two X
>>> X, y = tl.utils.class_balancing_oversample(X_train=np.hstack((X1, X2)), y_train=y, printable=False)
>>> X1 = X[:, 0:5]
>>> X2 = X[:, 5:]
"""
# ======== Classes balancing
if printable:
tl.logging.info("Classes balancing for training examples...")
c = Counter(y_train)
if printable:
tl.logging.info('the occurrence number of each stage: %s' % c.most_common())
tl.logging.info('the least stage is Label %s have %s instances' % c.most_common()[-1])
tl.logging.info('the most stage is Label %s have %s instances' % c.most_common(1)[0])
most_num = c.most_common(1)[0][1]
if printable:
tl.logging.info('most num is %d, all classes tend to be this num' % most_num)
locations = {}
number = {}
for lab, num in c.most_common(): # find the index from y_train
number[lab] = num
locations[lab] = np.where(np.array(y_train) == lab)[0]
if printable:
tl.logging.info('convert list(np.array) to dict format')
X = {} # convert list to dict
for lab, num in number.items():
X[lab] = X_train[locations[lab]]
# oversampling
if printable:
tl.logging.info('start oversampling')
for key in X:
temp = X[key]
while True:
if len(X[key]) >= most_num:
break
X[key] = np.vstack((X[key], temp))
if printable:
tl.logging.info('first features of label 0 > %d' % len(X[0][0]))
tl.logging.info('the occurrence num of each stage after oversampling')
for key in X:
tl.logging.info("%s %d" % (key, len(X[key])))
if printable:
tl.logging.info('make each stage have same num of instances')
for key in X:
X[key] = X[key][0:most_num, :]
tl.logging.info("%s %d" % (key, len(X[key])))
# convert dict to list
if printable:
tl.logging.info('convert from dict to list format')
y_train = []
X_train = np.empty(shape=(0, len(X[0][0])))
for key in X:
X_train = np.vstack((X_train, X[key]))
y_train.extend([key for i in range(len(X[key]))])
# tl.logging.info(len(X_train), len(y_train))
c = Counter(y_train)
if printable:
tl.logging.info('the occurrence number of each stage after oversampling: %s' % c.most_common())
# ================ End of Classes balancing
return X_train, y_train
## Random
def get_random_int(min_v=0, max_v=10, number=5, seed=None):
"""Return a list of random integer by the given range and quantity.
Parameters
-----------
min_v : number
The minimum value.
max_v : number
The maximum value.
number : int
Number of value.
seed : int or None
The seed for random.
Examples
---------
>>> r = get_random_int(min_v=0, max_v=10, number=5)
[10, 2, 3, 3, 7]
"""
rnd = random.Random()
if seed:
rnd = random.Random(seed)
# return [random.randint(min,max) for p in range(0, number)]
return [rnd.randint(min_v, max_v) for p in range(0, number)]
def list_string_to_dict(string):
"""Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``."""
dictionary = {}
for idx, c in enumerate(string):
dictionary.update({c: idx})
return dictionary
def exit_tensorflow(port=6006):
"""Close TensorBoard and Nvidia-process if available.
Parameters
----------
port : int
TensorBoard port you want to close, `6006` as default.
"""
text = "[TL] Close tensorboard and nvidia-process if available"
text2 = "[TL] Close tensorboard and nvidia-process not yet supported by this function (tl.ops.exit_tf) on "
if _platform == "linux" or _platform == "linux2":
tl.logging.info('linux: %s' % text)
os.system('nvidia-smi')
os.system('fuser ' + str(port) + '/tcp -k') # kill tensorboard 6006
os.system("nvidia-smi | grep python |awk '{print $3}'|xargs kill") # kill all nvidia-smi python process
_exit()
elif _platform == "darwin":
tl.logging.info('OS X: %s' % text)
subprocess.Popen(
"lsof -i tcp:" + str(port) + " | grep -v PID | awk '{print $2}' | xargs kill", shell=True
) # kill tensorboard
elif _platform == "win32":
raise NotImplementedError("this function is not supported on the Windows platform")
else:
tl.logging.info(text2 + _platform)
def open_tensorboard(log_dir='/tmp/tensorflow', port=6006):
"""Open Tensorboard.
Parameters
----------
log_dir : str
Directory where your tensorboard logs are saved
port : int
TensorBoard port you want to open, 6006 is tensorboard default
"""
text = "[TL] Open tensorboard, go to localhost:" + str(port) + " to access"
text2 = " not yet supported by this function (tl.ops.open_tb)"
if not tl.files.exists_or_mkdir(log_dir, verbose=False):
tl.logging.info("[TL] Log reportory was created at %s" % log_dir)
if _platform == "linux" or _platform == "linux2":
tl.logging.info('linux: %s' % text)
subprocess.Popen(
sys.prefix + " | python -m tensorflow.tensorboard --logdir=" + log_dir + " --port=" + str(port), shell=True
) # open tensorboard in localhost:6006/ or whatever port you chose
elif _platform == "darwin":
tl.logging.info('OS X: %s' % text)
subprocess.Popen(
sys.prefix + " | python -m tensorflow.tensorboard --logdir=" + log_dir + " --port=" + str(port), shell=True
) # open tensorboard in localhost:6006/ or whatever port you chose
elif _platform == "win32":
raise NotImplementedError("this function is not supported on the Windows platform")
else:
tl.logging.info(_platform + text2)
def clear_all_placeholder_variables(printable=True):
"""Clears all the placeholder variables of keep prob,
including keeping probabilities of all dropout, denoising, dropconnect etc.
Parameters
----------
printable : boolean
If True, print all deleted variables.
"""
tl.logging.info('clear all .....................................')
gl = globals().copy()
for var in gl:
if var[0] == '_': continue
if 'func' in str(globals()[var]): continue
if 'module' in str(globals()[var]): continue
if 'class' in str(globals()[var]): continue
if printable:
tl.logging.info(" clear_all ------- %s" % str(globals()[var]))
del globals()[var]
def set_gpu_fraction(gpu_fraction=0.3):
"""Set the GPU memory fraction for the application.
Parameters
----------
gpu_fraction : None or float
Fraction of GPU memory, (0 ~ 1]. If None, allow gpu memory growth.
References
----------
- `TensorFlow using GPU <https://www.tensorflow.org/alpha/guide/using_gpu#allowing_gpu_memory_growth>`__
"""
if gpu_fraction is None:
tl.logging.info("[TL]: ALLOW GPU MEM GROWTH")
tf.config.gpu.set_per_process_memory_growth(True)
else:
tl.logging.info("[TL]: GPU MEM Fraction %f" % gpu_fraction)
tf.config.gpu.set_per_process_memory_fraction(0.4)
# gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction)
# sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
# return sess
def train_epoch(
network, X, y, cost, train_op=tf.optimizers.Adam(learning_rate=0.0001), acc=None, batch_size=100, shuffle=True
):
"""Training a given non time-series network by the given cost function, training data, batch_size etc.
for one epoch.
Parameters
----------
network : TensorLayer Model
the network to be trained.
X : numpy.array
The input of training data
y : numpy.array
The target of training data
cost : TensorLayer or TensorFlow loss function
Metric for loss function, e.g tl.cost.cross_entropy.
train_op : TensorFlow optimizer
The optimizer for training e.g. tf.optimizers.Adam().
acc : TensorFlow/numpy expression or None
Metric for accuracy or others. If None, would not print the information.
batch_size : int
The batch size for training and evaluating.
shuffle : boolean
Indicating whether to shuffle the dataset in training.
Returns
-------
loss_ep : Tensor. Average loss of this epoch.
acc_ep : Tensor or None. Average accuracy(metric) of this epoch. None if acc is not given.
n_step : int. Number of iterations taken in this epoch.
"""
network.train()
loss_ep = 0
acc_ep = 0
n_step = 0
for X_batch, y_batch in tl.iterate.minibatches(X, y, batch_size, shuffle=shuffle):
_loss, _acc = _train_step(network, X_batch, y_batch, cost=cost, train_op=train_op, acc=acc)
loss_ep += _loss
if acc is not None:
acc_ep += _acc
n_step += 1
loss_ep = loss_ep / n_step
acc_ep = acc_ep / n_step if acc is not None else None
return loss_ep, acc_ep, n_step
def run_epoch(network, X, y, cost=None, acc=None, batch_size=100, shuffle=False):
"""Run a given non time-series network by the given cost function, test data, batch_size etc.
for one epoch.
Parameters
----------
network : TensorLayer Model
the network to be trained.
X : numpy.array
The input of training data
y : numpy.array
The target of training data
cost : TensorLayer or TensorFlow loss function
Metric for loss function, e.g tl.cost.cross_entropy.
acc : TensorFlow/numpy expression or None
Metric for accuracy or others. If None, would not print the information.
batch_size : int
The batch size for training and evaluating.
shuffle : boolean
Indicating whether to shuffle the dataset in training.
Returns
-------
loss_ep : Tensor. Average loss of this epoch. None if 'cost' is not given.
acc_ep : Tensor. Average accuracy(metric) of this epoch. None if 'acc' is not given.
n_step : int. Number of iterations taken in this epoch.
"""
network.eval()
loss_ep = 0
acc_ep = 0
n_step = 0
for X_batch, y_batch in tl.iterate.minibatches(X, y, batch_size, shuffle=shuffle):
_loss, _acc = _run_step(network, X_batch, y_batch, cost=cost, acc=acc)
if cost is not None:
loss_ep += _loss
if acc is not None:
acc_ep += _acc
n_step += 1
loss_ep = loss_ep / n_step if cost is not None else None
acc_ep = acc_ep / n_step if acc is not None else None
return loss_ep, acc_ep, n_step
@tf.function
def _train_step(network, X_batch, y_batch, cost, train_op=tf.optimizers.Adam(learning_rate=0.0001), acc=None):
"""Train for one step"""
with tf.GradientTape() as tape:
y_pred = network(X_batch)
_loss = cost(y_pred, y_batch)
grad = tape.gradient(_loss, network.trainable_weights)
train_op.apply_gradients(zip(grad, network.trainable_weights))
if acc is not None:
_acc = acc(y_pred, y_batch)
return _loss, _acc
else:
return _loss, None
# @tf.function # FIXME : enable tf.function will cause some bugs in numpy, need fixing
def _run_step(network, X_batch, y_batch, cost=None, acc=None):
"""Run for one step"""
y_pred = network(X_batch)
_loss, _acc = None, None
if cost is not None:
_loss = cost(y_pred, y_batch)
if acc is not None:
_acc = acc(y_pred, y_batch)
return _loss, _acc