-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathutils.py
2904 lines (2423 loc) · 106 KB
/
utils.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
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/python
# -*- coding: utf-8 -*-
import base64
import datetime
import gzip
import json
import math
import os
import pickle
import re
import shutil
# import ast
import sys
import tarfile
import time
import zipfile
import cloudpickle
import h5py
import numpy as np
import progressbar
import scipy.io as sio
from six.moves import cPickle
import tensorlayerx as tlx
from tensorlayerx import logging
from tensorlayerx.utils import visualize
if tlx.BACKEND == 'tensorflow':
from tensorflow.python.keras.saving import model_config as model_config_lib
from tensorflow.python.platform import gfile
from tensorflow.python.util import serialization
from tensorflow.python.util.tf_export import keras_export
from tensorflow.python import pywrap_tensorflow
import tensorflow as tf
@keras_export('keras.model.save_model')
def save_keras_model(model):
# f.attrs['keras_model_config'] = json.dumps(
# {
# 'class_name': model.__class__.__name__,
# 'config': model.get_config()
# },
# default=serialization.get_json_type).encode('utf8')
#
# f.flush()
return json.dumps(
{
'class_name': model.__class__.__name__,
'config': model.get_config()
}, default=serialization.get_json_type
).encode('utf8')
@keras_export('keras.model.load_model')
def load_keras_model(model_config):
custom_objects = {}
if model_config is None:
raise ValueError('No model found in config.')
model_config = json.loads(model_config.decode('utf-8'))
model = model_config_lib.model_from_config(model_config, custom_objects=custom_objects)
return model
if tlx.BACKEND == 'mindspore':
from mindspore.ops.operations import Assign
from mindspore.nn import Cell
from mindspore import Tensor
import mindspore as ms
if tlx.BACKEND == 'paddle':
import paddle as pd
if tlx.BACKEND == 'torch':
import torch
if tlx.BACKEND == 'jittor':
import jittor
if sys.version_info[0] == 2:
from urllib import urlretrieve
else:
from urllib.request import urlretrieve
# import tensorflow.contrib.eager.python.saver as tfes
# TODO: tf2.0 not stable, cannot import tensorflow.contrib.eager.python.saver
__all__ = [
'assign_weights',
'del_file',
'del_folder',
'download_file_from_google_drive',
'exists_or_mkdir',
'file_exists',
'folder_exists',
'load_and_assign_npz',
'load_and_assign_npz_dict',
'load_ckpt',
'load_cropped_svhn',
'load_file_list',
'load_folder_list',
'load_npy_to_any',
'load_npz',
'maybe_download_and_extract',
'natural_keys',
'npz_to_W_pdf',
'read_file',
'save_any_to_npy',
'save_ckpt',
'save_npz',
'save_npz_dict',
'tf_variables_to_numpy',
'ms_variables_to_numpy',
'assign_tf_variable',
'assign_ms_variable',
'assign_pd_variable',
'save_weights_to_hdf5',
'load_hdf5_to_weights_in_order',
'load_hdf5_to_weights',
'save_hdf5_graph',
'load_hdf5_graph',
'load_and_assign_ckpt',
'ckpt_to_npz_dict'
]
def func2str(expr):
b = cloudpickle.dumps(expr)
s = base64.b64encode(b).decode()
return s
def str2func(s):
b = base64.b64decode(s)
expr = cloudpickle.loads(b)
return expr
def save_hdf5_graph(network, filepath='model.hdf5', save_weights=False, customized_data=None):
"""Save the architecture of TL model into a hdf5 file. Support saving model weights.
Parameters
-----------
network : TensorLayer Model.
The network to save.
filepath : str
The name of model file.
save_weights : bool
Whether to save model weights.
customized_data : dict
The user customized meta data.
Examples
--------
>>> # Save the architecture (with parameters)
>>> tlx.files.save_hdf5_graph(network, filepath='model.hdf5', save_weights=True)
>>> # Save the architecture (without parameters)
>>> tlx.files.save_hdf5_graph(network, filepath='model.hdf5', save_weights=False)
>>> # Load the architecture in another script (no parameters restore)
>>> net = tlx.files.load_hdf5_graph(filepath='model.hdf5', load_weights=False)
>>> # Load the architecture in another script (restore parameters)
>>> net = tlx.files.load_hdf5_graph(filepath='model.hdf5', load_weights=True)
"""
if network.outputs is None:
raise RuntimeError("save_hdf5_graph not support dynamic mode yet")
logging.info("[*] Saving TL model into {}, saving weights={}".format(filepath, save_weights))
model_config = network.config # net2static_graph(network)
model_config["version_info"]["save_date"] = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc
).isoformat()
model_config_str = str(model_config)
customized_data_str = str(customized_data)
with h5py.File(filepath, 'w') as f:
f.attrs["model_config"] = model_config_str.encode('utf8')
f.attrs["customized_data"] = customized_data_str.encode('utf8')
if save_weights:
_save_weights_to_hdf5_group(f, network.all_layers)
f.flush()
logging.info("[*] Saved TL model into {}, saving weights={}".format(filepath, save_weights))
def generate_func(args):
for key in args:
if isinstance(args[key], tuple) and args[key][0] == 'is_Func':
fn = str2func(args[key][1])
args[key] = fn
# if key in ['act']:
# # fn_dict = args[key]
# # module_path = fn_dict['module_path']
# # func_name = fn_dict['func_name']
# # lib = importlib.import_module(module_path)
# # fn = getattr(lib, func_name)
# # args[key] = fn
# fn = str2func(args[key])
# args[key] = fn
# elif key in ['fn']:
# fn = str2func(args[key])
# args[key] = fn
def load_hdf5_graph(filepath='model.hdf5', load_weights=False):
"""Restore TL model archtecture from a a pickle file. Support loading model weights.
Parameters
-----------
filepath : str
The name of model file.
load_weights : bool
Whether to load model weights.
Returns
--------
network : TensorLayer Model.
Examples
--------
- see ``tlx.files.save_hdf5_graph``
"""
logging.info("[*] Loading TL model from {}, loading weights={}".format(filepath, load_weights))
f = h5py.File(filepath, 'r')
model_config_str = f.attrs["model_config"].decode('utf8')
model_config = eval(model_config_str)
# version_info_str = f.attrs["version_info"].decode('utf8')
# version_info = eval(version_info_str)
version_info = model_config["version_info"]
backend_version = version_info["backend_version"]
tensorlayerx_version = version_info["tensorlayerx_version"]
if backend_version != tf.__version__:
logging.warning(
"Saved model uses tensorflow version {}, but now you are using tensorflow version {}".format(
backend_version, tf.__version__
)
)
if tensorlayerx_version != tlx.__version__:
logging.warning(
"Saved model uses tensorlayerx version {}, but now you are using tensorlayerx version {}".format(
tensorlayerx_version, tlx.__version__
)
)
M = static_graph2net(model_config)
if load_weights:
if not ('layer_names' in f.attrs.keys()):
raise RuntimeError("Saved model does not contain weights.")
M.load_weights(filepath=filepath)
f.close()
logging.info("[*] Loaded TL model from {}, loading weights={}".format(filepath, load_weights))
return M
def load_mnist_dataset(shape=(-1, 784), path='data'):
"""Load the original mnist.
Automatically download MNIST dataset and return the training, validation and test set with 50000, 10000 and 10000 digit images respectively.
Parameters
----------
shape : tuple
The shape of digit images (the default is (-1, 784), alternatively (-1, 28, 28, 1)).
path : str
The path that the data is downloaded to.
Returns
-------
X_train, y_train, X_val, y_val, X_test, y_test: tuple
Return splitted training/validation/test set respectively.
Examples
--------
>>> X_train, y_train, X_val, y_val, X_test, y_test = tlx.files.load_mnist_dataset(shape=(-1,784), path='datasets')
>>> X_train, y_train, X_val, y_val, X_test, y_test = tlx.files.load_mnist_dataset(shape=(-1, 28, 28, 1))
"""
return _load_mnist_dataset(shape, path, name='mnist', url='https://ossci-datasets.s3.amazonaws.com/mnist/')
def load_fashion_mnist_dataset(shape=(-1, 784), path='data'):
"""Load the fashion mnist.
Automatically download fashion-MNIST dataset and return the training, validation and test set with 50000, 10000 and 10000 fashion images respectively, `examples <http://marubon-ds.blogspot.co.uk/2017/09/fashion-mnist-exploring.html>`__.
Parameters
----------
shape : tuple
The shape of digit images (the default is (-1, 784), alternatively (-1, 28, 28, 1)).
path : str
The path that the data is downloaded to.
Returns
-------
X_train, y_train, X_val, y_val, X_test, y_test: tuple
Return splitted training/validation/test set respectively.
Examples
--------
>>> X_train, y_train, X_val, y_val, X_test, y_test = tlx.files.load_fashion_mnist_dataset(shape=(-1,784), path='datasets')
>>> X_train, y_train, X_val, y_val, X_test, y_test = tlx.files.load_fashion_mnist_dataset(shape=(-1, 28, 28, 1))
"""
return _load_mnist_dataset(
shape, path, name='fashion_mnist', url='http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/'
)
def _load_mnist_dataset(shape, path, name='mnist', url='https://ossci-datasets.s3.amazonaws.com/mnist/'):
"""A generic function to load mnist-like dataset.
Parameters:
----------
shape : tuple
The shape of digit images.
path : str
The path that the data is downloaded to.
name : str
The dataset name you want to use(the default is 'mnist').
url : str
The url of dataset(the default is 'https://ossci-datasets.s3.amazonaws.com/mnist/').
"""
path = os.path.join(path, name)
# Define functions for loading mnist-like data's images and labels.
# For convenience, they also download the requested files if needed.
def load_mnist_images(path, filename):
filepath = maybe_download_and_extract(filename, path, url)
logging.info(filepath)
# Read the inputs in Yann LeCun's binary format.
with gzip.open(filepath, 'rb') as f:
data = np.frombuffer(f.read(), np.uint8, offset=16)
# The inputs are vectors now, we reshape them to monochrome 2D images,
# following the shape convention: (examples, channels, rows, columns)
data = data.reshape(shape)
# The inputs come as bytes, we convert them to float32 in range [0,1].
# (Actually to range [0, 255/256], for compatibility to the version
# provided at http://deeplearning.net/data/mnist/mnist.pkl.gz.)
return data / np.float32(256)
def load_mnist_labels(path, filename):
filepath = maybe_download_and_extract(filename, path, url)
# Read the labels in Yann LeCun's binary format.
with gzip.open(filepath, 'rb') as f:
data = np.frombuffer(f.read(), np.uint8, offset=8)
# The labels are vectors of integers now, that's exactly what we want.
return data
# Download and read the training and test set images and labels.
logging.info("Load or Download {0} > {1}".format(name.upper(), path))
X_train = load_mnist_images(path, 'train-images-idx3-ubyte.gz')
y_train = load_mnist_labels(path, 'train-labels-idx1-ubyte.gz')
X_test = load_mnist_images(path, 't10k-images-idx3-ubyte.gz')
y_test = load_mnist_labels(path, 't10k-labels-idx1-ubyte.gz')
# We reserve the last 10000 training examples for validation.
X_train, X_val = X_train[:-10000], X_train[-10000:]
y_train, y_val = y_train[:-10000], y_train[-10000:]
# We just return all the arrays in order, as expected in main().
# (It doesn't matter how we do this as long as we can read them again.)
X_train = np.asarray(X_train, dtype=np.float32)
y_train = np.asarray(y_train, dtype=np.int32)
X_val = np.asarray(X_val, dtype=np.float32)
y_val = np.asarray(y_val, dtype=np.int32)
X_test = np.asarray(X_test, dtype=np.float32)
y_test = np.asarray(y_test, dtype=np.int32)
return X_train, y_train, X_val, y_val, X_test, y_test
def load_cifar10_dataset(shape=(-1, 32, 32, 3), path='data', plotable=False):
"""Load CIFAR-10 dataset.
It consists of 60000 32x32 colour images in 10 classes, with
6000 images per class. There are 50000 training images and 10000 test images.
The dataset is divided into five training batches and one test batch, each with
10000 images. The test batch contains exactly 1000 randomly-selected images from
each class. The training batches contain the remaining images in random order,
but some training batches may contain more images from one class than another.
Between them, the training batches contain exactly 5000 images from each class.
Parameters
----------
shape : tupe
The shape of digit images e.g. (-1, 3, 32, 32) and (-1, 32, 32, 3).
path : str
The path that the data is downloaded to, defaults is ``data/cifar10/``.
plotable : boolean
Whether to plot some image examples, False as default.
Examples
--------
>>> X_train, y_train, X_test, y_test = tlx.files.load_cifar10_dataset(shape=(-1, 32, 32, 3))
References
----------
- `CIFAR website <https://www.cs.toronto.edu/~kriz/cifar.html>`__
- `Data download link <https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz>`__
- `<https://teratail.com/questions/28932>`__
"""
path = os.path.join(path, 'cifar10')
logging.info("Load or Download cifar10 > {}".format(path))
# Helper function to unpickle the data
def unpickle(file):
fp = open(file, 'rb')
if sys.version_info.major == 2:
data = pickle.load(fp)
elif sys.version_info.major == 3:
data = pickle.load(fp, encoding='latin-1')
fp.close()
return data
filename = 'cifar-10-python.tar.gz'
url = 'https://www.cs.toronto.edu/~kriz/'
# Download and uncompress file
maybe_download_and_extract(filename, path, url, extract=True)
# Unpickle file and fill in data
X_train = None
y_train = []
for i in range(1, 6):
data_dic = unpickle(os.path.join(path, 'cifar-10-batches-py/', "data_batch_{}".format(i)))
if i == 1:
X_train = data_dic['data']
else:
X_train = np.vstack((X_train, data_dic['data']))
y_train += data_dic['labels']
test_data_dic = unpickle(os.path.join(path, 'cifar-10-batches-py/', "test_batch"))
X_test = test_data_dic['data']
y_test = np.array(test_data_dic['labels'])
if shape == (-1, 3, 32, 32):
X_test = X_test.reshape(shape)
X_train = X_train.reshape(shape)
elif shape == (-1, 32, 32, 3):
X_test = X_test.reshape(shape, order='F')
X_train = X_train.reshape(shape, order='F')
X_test = np.transpose(X_test, (0, 2, 1, 3))
X_train = np.transpose(X_train, (0, 2, 1, 3))
else:
X_test = X_test.reshape(shape)
X_train = X_train.reshape(shape)
y_train = np.array(y_train)
if plotable:
if sys.platform.startswith('darwin'):
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
logging.info('\nCIFAR-10')
fig = plt.figure(1)
logging.info('Shape of a training image: X_train[0] %s' % X_train[0].shape)
plt.ion() # interactive mode
count = 1
for _ in range(10): # each row
for _ in range(10): # each column
_ = fig.add_subplot(10, 10, count)
if shape == (-1, 3, 32, 32):
# plt.imshow(X_train[count-1], interpolation='nearest')
plt.imshow(np.transpose(X_train[count - 1], (1, 2, 0)), interpolation='nearest')
# plt.imshow(np.transpose(X_train[count-1], (2, 1, 0)), interpolation='nearest')
elif shape == (-1, 32, 32, 3):
plt.imshow(X_train[count - 1], interpolation='nearest')
# plt.imshow(np.transpose(X_train[count-1], (1, 0, 2)), interpolation='nearest')
else:
raise Exception("Do not support the given 'shape' to plot the image examples")
plt.gca().xaxis.set_major_locator(plt.NullLocator()) # 不显示刻度(tick)
plt.gca().yaxis.set_major_locator(plt.NullLocator())
count = count + 1
plt.draw() # interactive mode
plt.pause(3) # interactive mode
logging.info("X_train: %s" % X_train.shape)
logging.info("y_train: %s" % y_train.shape)
logging.info("X_test: %s" % X_test.shape)
logging.info("y_test: %s" % y_test.shape)
X_train = np.asarray(X_train, dtype=np.float32)
X_test = np.asarray(X_test, dtype=np.float32)
y_train = np.asarray(y_train, dtype=np.int32)
y_test = np.asarray(y_test, dtype=np.int32)
return X_train, y_train, X_test, y_test
def load_cropped_svhn(path='data', include_extra=True):
"""Load Cropped SVHN.
The Cropped Street View House Numbers (SVHN) Dataset contains 32x32x3 RGB images.
Digit '1' has label 1, '9' has label 9 and '0' has label 0 (the original dataset uses 10 to represent '0'), see `ufldl website <http://ufldl.stanford.edu/housenumbers/>`__.
Parameters
----------
path : str
The path that the data is downloaded to.
include_extra : boolean
If True (default), add extra images to the training set.
Returns
-------
X_train, y_train, X_test, y_test: tuple
Return splitted training/test set respectively.
Examples
---------
>>> X_train, y_train, X_test, y_test = tlx.files.load_cropped_svhn(include_extra=False)
>>> tlx.vis.save_images(X_train[0:100], [10, 10], 'svhn.png')
"""
start_time = time.time()
path = os.path.join(path, 'cropped_svhn')
logging.info("Load or Download Cropped SVHN > {} | include extra images: {}".format(path, include_extra))
url = "http://ufldl.stanford.edu/housenumbers/"
np_file = os.path.join(path, "train_32x32.npz")
if file_exists(np_file) is False:
filename = "train_32x32.mat"
filepath = maybe_download_and_extract(filename, path, url)
mat = sio.loadmat(filepath)
X_train = mat['X'] / 255.0 # to [0, 1]
X_train = np.transpose(X_train, (3, 0, 1, 2))
y_train = np.squeeze(mat['y'], axis=1)
y_train[y_train == 10] = 0 # replace 10 to 0
np.savez(np_file, X=X_train, y=y_train)
del_file(filepath)
else:
v = np.load(np_file, allow_pickle=True)
X_train = v['X']
y_train = v['y']
logging.info(" n_train: {}".format(len(y_train)))
np_file = os.path.join(path, "test_32x32.npz")
if file_exists(np_file) is False:
filename = "test_32x32.mat"
filepath = maybe_download_and_extract(filename, path, url)
mat = sio.loadmat(filepath)
X_test = mat['X'] / 255.0
X_test = np.transpose(X_test, (3, 0, 1, 2))
y_test = np.squeeze(mat['y'], axis=1)
y_test[y_test == 10] = 0
np.savez(np_file, X=X_test, y=y_test)
del_file(filepath)
else:
v = np.load(np_file, allow_pickle=True)
X_test = v['X']
y_test = v['y']
logging.info(" n_test: {}".format(len(y_test)))
if include_extra:
logging.info(" getting extra 531131 images, please wait ...")
np_file = os.path.join(path, "extra_32x32.npz")
if file_exists(np_file) is False:
logging.info(" the first time to load extra images will take long time to convert the file format ...")
filename = "extra_32x32.mat"
filepath = maybe_download_and_extract(filename, path, url)
mat = sio.loadmat(filepath)
X_extra = mat['X'] / 255.0
X_extra = np.transpose(X_extra, (3, 0, 1, 2))
y_extra = np.squeeze(mat['y'], axis=1)
y_extra[y_extra == 10] = 0
np.savez(np_file, X=X_extra, y=y_extra)
del_file(filepath)
else:
v = np.load(np_file, allow_pickle=True)
X_extra = v['X']
y_extra = v['y']
logging.info(" adding n_extra {} to n_train {}".format(len(y_extra), len(y_train)))
t = time.time()
X_train = np.concatenate((X_train, X_extra), 0)
y_train = np.concatenate((y_train, y_extra), 0)
# X_train = np.append(X_train, X_extra, axis=0)
# y_train = np.append(y_train, y_extra, axis=0)
logging.info(" added n_extra {} to n_train {} took {}s".format(len(y_extra), len(y_train), time.time() - t))
else:
logging.info(" no extra images are included")
logging.info(" image size: %s n_train: %d n_test: %d" % (str(X_train.shape[1:4]), len(y_train), len(y_test)))
logging.info(" took: {}s".format(int(time.time() - start_time)))
return X_train, y_train, X_test, y_test
# def load_ptb_dataset(path='data'):
# """Load Penn TreeBank (PTB) dataset.
#
# It is used in many LANGUAGE MODELING papers,
# including "Empirical Evaluation and Combination of Advanced Language
# Modeling Techniques", "Recurrent Neural Network Regularization".
# It consists of 929k training words, 73k validation words, and 82k test
# words. It has 10k words in its vocabulary.
#
# Parameters
# ----------
# path : str
# The path that the data is downloaded to, defaults is ``data/ptb/``.
#
# Returns
# --------
# train_data, valid_data, test_data : list of int
# The training, validating and testing data in integer format.
# vocab_size : int
# The vocabulary size.
#
# Examples
# --------
# >>> train_data, valid_data, test_data, vocab_size = tlx.files.load_ptb_dataset()
#
# References
# ---------------
# - ``tensorflow.model.rnn.ptb import reader``
# - `Manual download <http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz>`__
#
# Notes
# ------
# - If you want to get the raw data, see the source code.
#
# """
# path = os.path.join(path, 'ptb')
# logging.info("Load or Download Penn TreeBank (PTB) dataset > {}".format(path))
#
# # Maybe dowload and uncompress tar, or load exsisting files
# filename = 'simple-examples.tgz'
# url = 'http://www.fit.vutbr.cz/~imikolov/rnnlm/'
# maybe_download_and_extract(filename, path, url, extract=True)
#
# data_path = os.path.join(path, 'simple-examples', 'data')
# train_path = os.path.join(data_path, "ptb.train.txt")
# valid_path = os.path.join(data_path, "ptb.valid.txt")
# test_path = os.path.join(data_path, "ptb.test.txt")
#
# word_to_id = nlp.build_vocab(nlp.read_words(train_path))
#
# train_data = nlp.words_to_word_ids(nlp.read_words(train_path), word_to_id)
# valid_data = nlp.words_to_word_ids(nlp.read_words(valid_path), word_to_id)
# test_data = nlp.words_to_word_ids(nlp.read_words(test_path), word_to_id)
# vocab_size = len(word_to_id)
#
# # logging.info(nlp.read_words(train_path)) # ... 'according', 'to', 'mr.', '<unk>', '<eos>']
# # logging.info(train_data) # ... 214, 5, 23, 1, 2]
# # logging.info(word_to_id) # ... 'beyond': 1295, 'anti-nuclear': 9599, 'trouble': 1520, '<eos>': 2 ... }
# # logging.info(vocabulary) # 10000
# # exit()
# return train_data, valid_data, test_data, vocab_size
def load_matt_mahoney_text8_dataset(path='data'):
"""Load Matt Mahoney's dataset.
Download a text file from Matt Mahoney's website
if not present, and make sure it's the right size.
Extract the first file enclosed in a zip file as a list of words.
This dataset can be used for Word Embedding.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/mm_test8/``.
Returns
--------
list of str
The raw text data e.g. [.... 'their', 'families', 'who', 'were', 'expelled', 'from', 'jerusalem', ...]
Examples
--------
>>> words = tlx.files.load_matt_mahoney_text8_dataset()
>>> print('Data size', len(words))
"""
path = os.path.join(path, 'mm_test8')
logging.info("Load or Download matt_mahoney_text8 Dataset> {}".format(path))
filename = 'text8.zip'
url = 'http://mattmahoney.net/dc/'
maybe_download_and_extract(filename, path, url, expected_bytes=31344016)
with zipfile.ZipFile(os.path.join(path, filename)) as f:
word_list = f.read(f.namelist()[0]).split()
for idx, _ in enumerate(word_list):
word_list[idx] = word_list[idx].decode()
return word_list
def load_imdb_dataset(
path='data', nb_words=None, skip_top=0, maxlen=None, test_split=0.2, seed=113, start_char=1, oov_char=2,
index_from=3
):
"""Load IMDB dataset.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/imdb/``.
nb_words : int
Number of words to get.
skip_top : int
Top most frequent words to ignore (they will appear as oov_char value in the sequence data).
maxlen : int
Maximum sequence length. Any longer sequence will be truncated.
seed : int
Seed for reproducible data shuffling.
start_char : int
The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character.
oov_char : int
Words that were cut out because of the num_words or skip_top limit will be replaced with this character.
index_from : int
Index actual words with this index and higher.
Examples
--------
>>> X_train, y_train, X_test, y_test = tlx.files.load_imdb_dataset(
... nb_words=20000, test_split=0.2)
>>> print('X_train.shape', X_train.shape)
(20000,) [[1, 62, 74, ... 1033, 507, 27],[1, 60, 33, ... 13, 1053, 7]..]
>>> print('y_train.shape', y_train.shape)
(20000,) [1 0 0 ..., 1 0 1]
References
-----------
- `Modified from keras. <https://github.com/fchollet/keras/blob/master/keras/datasets/imdb.py>`__
"""
path = os.path.join(path, 'imdb')
filename = "imdb.pkl"
url = 'https://s3.amazonaws.com/text-datasets/'
maybe_download_and_extract(filename, path, url)
if filename.endswith(".gz"):
f = gzip.open(os.path.join(path, filename), 'rb')
else:
f = open(os.path.join(path, filename), 'rb')
X, labels = cPickle.load(f)
f.close()
np.random.seed(seed)
np.random.shuffle(X)
np.random.seed(seed)
np.random.shuffle(labels)
if start_char is not None:
X = [[start_char] + [w + index_from for w in x] for x in X]
elif index_from:
X = [[w + index_from for w in x] for x in X]
if maxlen:
new_X = []
new_labels = []
for x, y in zip(X, labels):
if len(x) < maxlen:
new_X.append(x)
new_labels.append(y)
X = new_X
labels = new_labels
if not X:
raise Exception(
'After filtering for sequences shorter than maxlen=' + str(maxlen) + ', no sequence was kept. '
'Increase maxlen.'
)
if not nb_words:
nb_words = max([max(x) for x in X])
# by convention, use 2 as OOV word
# reserve 'index_from' (=3 by default) characters: 0 (padding), 1 (start), 2 (OOV)
if oov_char is not None:
X = [[oov_char if (w >= nb_words or w < skip_top) else w for w in x] for x in X]
else:
nX = []
for x in X:
nx = []
for w in x:
if (w >= nb_words or w < skip_top):
nx.append(w)
nX.append(nx)
X = nX
X_train = np.array(X[:int(len(X) * (1 - test_split))])
y_train = np.array(labels[:int(len(X) * (1 - test_split))])
X_test = np.array(X[int(len(X) * (1 - test_split)):])
y_test = np.array(labels[int(len(X) * (1 - test_split)):])
return X_train, y_train, X_test, y_test
def load_nietzsche_dataset(path='data'):
"""Load Nietzsche dataset.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/nietzsche/``.
Returns
--------
str
The content.
Examples
--------
>>> see tutorial_generate_text.py
>>> words = tlx.files.load_nietzsche_dataset()
>>> words = basic_clean_str(words)
>>> words = words.split()
"""
logging.info("Load or Download nietzsche dataset > {}".format(path))
path = os.path.join(path, 'nietzsche')
filename = "nietzsche.txt"
url = 'https://s3.amazonaws.com/text-datasets/'
filepath = maybe_download_and_extract(filename, path, url)
with open(filepath, "r") as f:
words = f.read()
return words
def load_wmt_en_fr_dataset(path='data'):
"""Load WMT'15 English-to-French translation dataset.
It will download the data from the WMT'15 Website (10^9-French-English corpus), and the 2013 news test from the same site as development set.
Returns the directories of training data and test data.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/wmt_en_fr/``.
References
----------
- Code modified from /tensorflow/model/rnn/translation/data_utils.py
Notes
-----
Usually, it will take a long time to download this dataset.
"""
path = os.path.join(path, 'wmt_en_fr')
# URLs for WMT data.
_WMT_ENFR_TRAIN_URL = "http://www.statmt.org/wmt10/"
_WMT_ENFR_DEV_URL = "http://www.statmt.org/wmt15/"
def gunzip_file(gz_path, new_path):
"""Unzips from gz_path into new_path."""
logging.info("Unpacking %s to %s" % (gz_path, new_path))
with gzip.open(gz_path, "rb") as gz_file:
with open(new_path, "wb") as new_file:
for line in gz_file:
new_file.write(line)
def get_wmt_enfr_train_set(path):
"""Download the WMT en-fr training corpus to directory unless it's there."""
filename = "training-giga-fren.tar"
maybe_download_and_extract(filename, path, _WMT_ENFR_TRAIN_URL, extract=True)
train_path = os.path.join(path, "giga-fren.release2.fixed")
gunzip_file(train_path + ".fr.gz", train_path + ".fr")
gunzip_file(train_path + ".en.gz", train_path + ".en")
return train_path
def get_wmt_enfr_dev_set(path):
"""Download the WMT en-fr training corpus to directory unless it's there."""
filename = "dev-v2.tgz"
dev_file = maybe_download_and_extract(filename, path, _WMT_ENFR_DEV_URL, extract=False)
dev_name = "newstest2013"
dev_path = os.path.join(path, "newstest2013")
if not (gfile.Exists(dev_path + ".fr") and gfile.Exists(dev_path + ".en")):
logging.info("Extracting tgz file %s" % dev_file)
with tarfile.open(dev_file, "r:gz") as dev_tar:
fr_dev_file = dev_tar.getmember("dev/" + dev_name + ".fr")
en_dev_file = dev_tar.getmember("dev/" + dev_name + ".en")
fr_dev_file.name = dev_name + ".fr" # Extract without "dev/" prefix.
en_dev_file.name = dev_name + ".en"
dev_tar.extract(fr_dev_file, path)
dev_tar.extract(en_dev_file, path)
return dev_path
logging.info("Load or Download WMT English-to-French translation > {}".format(path))
train_path = get_wmt_enfr_train_set(path)
dev_path = get_wmt_enfr_dev_set(path)
return train_path, dev_path
def load_flickr25k_dataset(tag='sky', path="data", n_threads=50, printable=False):
"""Load Flickr25K dataset.
Returns a list of images by a given tag from Flick25k dataset,
it will download Flickr25k from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__
at the first time you use it.
Parameters
------------
tag : str or None
What images to return.
- If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.
- If you want to get all images, set to ``None``.
path : str
The path that the data is downloaded to, defaults is ``data/flickr25k/``.
n_threads : int
The number of thread to read image.
printable : boolean
Whether to print infomation when reading images, default is ``False``.
Examples
-----------
Get images with tag of sky
>>> images = tlx.files.load_flickr25k_dataset(tag='sky')
Get all images
>>> images = tlx.files.load_flickr25k_dataset(tag=None, n_threads=100, printable=True)
"""
path = os.path.join(path, 'flickr25k')
filename = 'mirflickr25k.zip'
url = 'http://press.liacs.nl/mirflickr/mirflickr25k/'
# download dataset
if folder_exists(os.path.join(path, "mirflickr")) is False:
logging.info("[*] Flickr25k is nonexistent in {}".format(path))
maybe_download_and_extract(filename, path, url, extract=True)
del_file(os.path.join(path, filename))
# return images by the given tag.
# 1. image path list
folder_imgs = os.path.join(path, "mirflickr")
path_imgs = load_file_list(path=folder_imgs, regx='\\.jpg', printable=False)
path_imgs.sort(key=natural_keys)
# 2. tag path list
folder_tags = os.path.join(path, "mirflickr", "meta", "tags")
path_tags = load_file_list(path=folder_tags, regx='\\.txt', printable=False)
path_tags.sort(key=natural_keys)
# 3. select images
if tag is None:
logging.info("[Flickr25k] reading all images")
else:
logging.info("[Flickr25k] reading images with tag: {}".format(tag))
images_list = []
for idx, _v in enumerate(path_tags):
tags = read_file(os.path.join(folder_tags, path_tags[idx])).split('\n')
# logging.info(idx+1, tags)
if tag is None or tag in tags:
images_list.append(path_imgs[idx])
images = visualize.read_images(images_list, folder_imgs, n_threads=n_threads, printable=printable)
return images
def load_flickr1M_dataset(tag='sky', size=10, path="data", n_threads=50, printable=False):
"""Load Flick1M dataset.
Returns a list of images by a given tag from Flickr1M dataset,
it will download Flickr1M from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__
at the first time you use it.
Parameters
------------
tag : str or None
What images to return.
- If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.
- If you want to get all images, set to ``None``.
size : int
integer between 1 to 10. 1 means 100k images ... 5 means 500k images, 10 means all 1 million images. Default is 10.
path : str
The path that the data is downloaded to, defaults is ``data/flickr25k/``.
n_threads : int
The number of thread to read image.
printable : boolean
Whether to print infomation when reading images, default is ``False``.
Examples
----------
Use 200k images
>>> images = tlx.files.load_flickr1M_dataset(tag='zebra', size=2)
Use 1 Million images