You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 110 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963
  1. #! /usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import base64
  4. import datetime
  5. import gzip
  6. import json
  7. import math
  8. import os
  9. import pickle
  10. import re
  11. import shutil
  12. # import ast
  13. import sys
  14. import tarfile
  15. import time
  16. import zipfile
  17. import cloudpickle
  18. import h5py
  19. import numpy as np
  20. import progressbar
  21. import scipy.io as sio
  22. import tensorflow as tf
  23. from six.moves import cPickle
  24. from tensorflow.python.keras.saving import model_config as model_config_lib
  25. from tensorflow.python.platform import gfile
  26. from tensorflow.python.util import serialization
  27. from tensorflow.python.util.tf_export import keras_export
  28. from tensorflow.python import pywrap_tensorflow
  29. import tensorlayer as tl
  30. from tensorlayer import logging, nlp, utils, visualize
  31. if tl.BACKEND == 'mindspore':
  32. from mindspore.ops.operations import Assign
  33. from mindspore.nn import Cell
  34. from mindspore import Tensor
  35. import mindspore as ms
  36. if tl.BACKEND == 'paddle':
  37. import paddle as pd
  38. if sys.version_info[0] == 2:
  39. from urllib import urlretrieve
  40. else:
  41. from urllib.request import urlretrieve
  42. # import tensorflow.contrib.eager.python.saver as tfes
  43. # TODO: tf2.0 not stable, cannot import tensorflow.contrib.eager.python.saver
  44. __all__ = [
  45. 'assign_weights',
  46. 'del_file',
  47. 'del_folder',
  48. 'download_file_from_google_drive',
  49. 'exists_or_mkdir',
  50. 'file_exists',
  51. 'folder_exists',
  52. 'load_and_assign_npz',
  53. 'load_and_assign_npz_dict',
  54. 'load_ckpt',
  55. 'load_cropped_svhn',
  56. 'load_file_list',
  57. 'load_folder_list',
  58. 'load_npy_to_any',
  59. 'load_npz',
  60. 'maybe_download_and_extract',
  61. 'natural_keys',
  62. 'npz_to_W_pdf',
  63. 'read_file',
  64. 'save_any_to_npy',
  65. 'save_ckpt',
  66. 'save_npz',
  67. 'save_npz_dict',
  68. 'tf_variables_to_numpy',
  69. 'ms_variables_to_numpy',
  70. 'assign_tf_variable',
  71. 'assign_ms_variable',
  72. 'assign_pd_variable',
  73. 'save_weights_to_hdf5',
  74. 'load_hdf5_to_weights_in_order',
  75. 'load_hdf5_to_weights',
  76. 'save_hdf5_graph',
  77. 'load_hdf5_graph',
  78. # 'net2static_graph',
  79. 'static_graph2net',
  80. # 'save_pkl_graph',
  81. # 'load_pkl_graph',
  82. 'load_and_assign_ckpt',
  83. 'ckpt_to_npz_dict'
  84. ]
  85. def func2str(expr):
  86. b = cloudpickle.dumps(expr)
  87. s = base64.b64encode(b).decode()
  88. return s
  89. def str2func(s):
  90. b = base64.b64decode(s)
  91. expr = cloudpickle.loads(b)
  92. return expr
  93. # def net2static_graph(network):
  94. # saved_file = dict()
  95. # # if network._NameNone is True:
  96. # # saved_file.update({"name": None})
  97. # # else:
  98. # # saved_file.update({"name": network.name})
  99. # # if not isinstance(network.inputs, list):
  100. # # saved_file.update({"inputs": network.inputs._info[0].name})
  101. # # else:
  102. # # saved_inputs = []
  103. # # for saved_input in network.inputs:
  104. # # saved_inputs.append(saved_input._info[0].name)
  105. # # saved_file.update({"inputs": saved_inputs})
  106. # # if not isinstance(network.outputs, list):
  107. # # saved_file.update({"outputs": network.outputs._info[0].name})
  108. # # else:
  109. # # saved_outputs = []
  110. # # for saved_output in network.outputs:
  111. # # saved_outputs.append(saved_output._info[0].name)
  112. # # saved_file.update({"outputs": saved_outputs})
  113. # saved_file.update({"config": network.config})
  114. #
  115. # return saved_file
  116. @keras_export('keras.models.save_model')
  117. def save_keras_model(model):
  118. # f.attrs['keras_model_config'] = json.dumps(
  119. # {
  120. # 'class_name': model.__class__.__name__,
  121. # 'config': model.get_config()
  122. # },
  123. # default=serialization.get_json_type).encode('utf8')
  124. #
  125. # f.flush()
  126. return json.dumps(
  127. {
  128. 'class_name': model.__class__.__name__,
  129. 'config': model.get_config()
  130. }, default=serialization.get_json_type
  131. ).encode('utf8')
  132. @keras_export('keras.models.load_model')
  133. def load_keras_model(model_config):
  134. custom_objects = {}
  135. if model_config is None:
  136. raise ValueError('No model found in config.')
  137. model_config = json.loads(model_config.decode('utf-8'))
  138. model = model_config_lib.model_from_config(model_config, custom_objects=custom_objects)
  139. return model
  140. def save_hdf5_graph(network, filepath='model.hdf5', save_weights=False, customized_data=None):
  141. """Save the architecture of TL model into a hdf5 file. Support saving model weights.
  142. Parameters
  143. -----------
  144. network : TensorLayer Model.
  145. The network to save.
  146. filepath : str
  147. The name of model file.
  148. save_weights : bool
  149. Whether to save model weights.
  150. customized_data : dict
  151. The user customized meta data.
  152. Examples
  153. --------
  154. >>> # Save the architecture (with parameters)
  155. >>> tl.files.save_hdf5_graph(network, filepath='model.hdf5', save_weights=True)
  156. >>> # Save the architecture (without parameters)
  157. >>> tl.files.save_hdf5_graph(network, filepath='model.hdf5', save_weights=False)
  158. >>> # Load the architecture in another script (no parameters restore)
  159. >>> net = tl.files.load_hdf5_graph(filepath='model.hdf5', load_weights=False)
  160. >>> # Load the architecture in another script (restore parameters)
  161. >>> net = tl.files.load_hdf5_graph(filepath='model.hdf5', load_weights=True)
  162. """
  163. if network.outputs is None:
  164. raise RuntimeError("save_hdf5_graph not support dynamic mode yet")
  165. logging.info("[*] Saving TL model into {}, saving weights={}".format(filepath, save_weights))
  166. model_config = network.config # net2static_graph(network)
  167. model_config["version_info"]["save_date"] = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc
  168. ).isoformat()
  169. model_config_str = str(model_config)
  170. customized_data_str = str(customized_data)
  171. # version_info = {
  172. # "tensorlayer_version": tl.__version__,
  173. # "backend": "tensorflow",
  174. # "backend_version": tf.__version__,
  175. # "training_device": "gpu",
  176. # "save_date": datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
  177. # }
  178. # version_info_str = str(version_info)
  179. with h5py.File(filepath, 'w') as f:
  180. f.attrs["model_config"] = model_config_str.encode('utf8')
  181. f.attrs["customized_data"] = customized_data_str.encode('utf8')
  182. # f.attrs["version_info"] = version_info_str.encode('utf8')
  183. if save_weights:
  184. _save_weights_to_hdf5_group(f, network.all_layers)
  185. f.flush()
  186. logging.info("[*] Saved TL model into {}, saving weights={}".format(filepath, save_weights))
  187. def generate_func(args):
  188. for key in args:
  189. if isinstance(args[key], tuple) and args[key][0] == 'is_Func':
  190. fn = str2func(args[key][1])
  191. args[key] = fn
  192. # if key in ['act']:
  193. # # fn_dict = args[key]
  194. # # module_path = fn_dict['module_path']
  195. # # func_name = fn_dict['func_name']
  196. # # lib = importlib.import_module(module_path)
  197. # # fn = getattr(lib, func_name)
  198. # # args[key] = fn
  199. # fn = str2func(args[key])
  200. # args[key] = fn
  201. # elif key in ['fn']:
  202. # fn = str2func(args[key])
  203. # args[key] = fn
  204. def eval_layer(layer_kwargs):
  205. layer_class = layer_kwargs.pop('class')
  206. args = layer_kwargs['args']
  207. layer_type = args.pop('layer_type')
  208. if layer_type == "normal":
  209. generate_func(args)
  210. return eval('tl.layers.' + layer_class)(**args)
  211. elif layer_type == "layerlist":
  212. ret_layer = []
  213. layers = args["layers"]
  214. for layer_graph in layers:
  215. ret_layer.append(eval_layer(layer_graph))
  216. args['layers'] = ret_layer
  217. return eval('tl.layers.' + layer_class)(**args)
  218. elif layer_type == "modellayer":
  219. M = static_graph2net(args['model'])
  220. args['model'] = M
  221. return eval('tl.layers.' + layer_class)(**args)
  222. elif layer_type == "keraslayer":
  223. M = load_keras_model(args['fn'])
  224. input_shape = args.pop('keras_input_shape')
  225. _ = M(np.random.random(input_shape).astype(np.float32))
  226. args['fn'] = M
  227. args['fn_weights'] = M.trainable_variables
  228. return eval('tl.layers.' + layer_class)(**args)
  229. else:
  230. raise RuntimeError("Unknown layer type.")
  231. def static_graph2net(model_config):
  232. layer_dict = {}
  233. model_name = model_config["name"]
  234. inputs_tensors = model_config["inputs"]
  235. outputs_tensors = model_config["outputs"]
  236. all_args = model_config["model_architecture"]
  237. for idx, layer_kwargs in enumerate(all_args):
  238. layer_class = layer_kwargs["class"] # class of current layer
  239. prev_layers = layer_kwargs.pop("prev_layer") # name of previous layers
  240. net = eval_layer(layer_kwargs)
  241. if layer_class in tl.layers.inputs.__all__:
  242. net = net._nodes[0].out_tensors[0]
  243. if prev_layers is not None:
  244. for prev_layer in prev_layers:
  245. if not isinstance(prev_layer, list):
  246. output = net(layer_dict[prev_layer])
  247. layer_dict[output._info[0].name] = output
  248. else:
  249. list_layers = [layer_dict[layer] for layer in prev_layer]
  250. output = net(list_layers)
  251. layer_dict[output._info[0].name] = output
  252. else:
  253. layer_dict[net._info[0].name] = net
  254. if not isinstance(inputs_tensors, list):
  255. model_inputs = layer_dict[inputs_tensors]
  256. else:
  257. model_inputs = []
  258. for inputs_tensor in inputs_tensors:
  259. model_inputs.append(layer_dict[inputs_tensor])
  260. if not isinstance(outputs_tensors, list):
  261. model_outputs = layer_dict[outputs_tensors]
  262. else:
  263. model_outputs = []
  264. for outputs_tensor in outputs_tensors:
  265. model_outputs.append(layer_dict[outputs_tensor])
  266. from tensorlayer.models import Model
  267. M = Model(inputs=model_inputs, outputs=model_outputs, name=model_name)
  268. logging.info("[*] Load graph finished")
  269. return M
  270. def load_hdf5_graph(filepath='model.hdf5', load_weights=False):
  271. """Restore TL model archtecture from a a pickle file. Support loading model weights.
  272. Parameters
  273. -----------
  274. filepath : str
  275. The name of model file.
  276. load_weights : bool
  277. Whether to load model weights.
  278. Returns
  279. --------
  280. network : TensorLayer Model.
  281. Examples
  282. --------
  283. - see ``tl.files.save_hdf5_graph``
  284. """
  285. logging.info("[*] Loading TL model from {}, loading weights={}".format(filepath, load_weights))
  286. f = h5py.File(filepath, 'r')
  287. model_config_str = f.attrs["model_config"].decode('utf8')
  288. model_config = eval(model_config_str)
  289. # version_info_str = f.attrs["version_info"].decode('utf8')
  290. # version_info = eval(version_info_str)
  291. version_info = model_config["version_info"]
  292. backend_version = version_info["backend_version"]
  293. tensorlayer_version = version_info["tensorlayer_version"]
  294. if backend_version != tf.__version__:
  295. logging.warning(
  296. "Saved model uses tensorflow version {}, but now you are using tensorflow version {}".format(
  297. backend_version, tf.__version__
  298. )
  299. )
  300. if tensorlayer_version != tl.__version__:
  301. logging.warning(
  302. "Saved model uses tensorlayer version {}, but now you are using tensorlayer version {}".format(
  303. tensorlayer_version, tl.__version__
  304. )
  305. )
  306. M = static_graph2net(model_config)
  307. if load_weights:
  308. if not ('layer_names' in f.attrs.keys()):
  309. raise RuntimeError("Saved model does not contain weights.")
  310. M.load_weights(filepath=filepath)
  311. f.close()
  312. logging.info("[*] Loaded TL model from {}, loading weights={}".format(filepath, load_weights))
  313. return M
  314. # def load_pkl_graph(name='model.pkl'):
  315. # """Restore TL model archtecture from a a pickle file. No parameters be restored.
  316. #
  317. # Parameters
  318. # -----------
  319. # name : str
  320. # The name of graph file.
  321. #
  322. # Returns
  323. # --------
  324. # network : TensorLayer Model.
  325. #
  326. # Examples
  327. # --------
  328. # >>> # It is better to use load_hdf5_graph
  329. # """
  330. # logging.info("[*] Loading TL graph from {}".format(name))
  331. # with open(name, 'rb') as file:
  332. # saved_file = pickle.load(file)
  333. #
  334. # M = static_graph2net(saved_file)
  335. #
  336. # return M
  337. #
  338. #
  339. # def save_pkl_graph(network, name='model.pkl'):
  340. # """Save the architecture of TL model into a pickle file. No parameters be saved.
  341. #
  342. # Parameters
  343. # -----------
  344. # network : TensorLayer layer
  345. # The network to save.
  346. # name : str
  347. # The name of graph file.
  348. #
  349. # Example
  350. # --------
  351. # >>> # It is better to use save_hdf5_graph
  352. # """
  353. # if network.outputs is None:
  354. # raise AssertionError("save_graph not support dynamic mode yet")
  355. #
  356. # logging.info("[*] Saving TL graph into {}".format(name))
  357. #
  358. # saved_file = net2static_graph(network)
  359. #
  360. # with open(name, 'wb') as file:
  361. # pickle.dump(saved_file, file, protocol=pickle.HIGHEST_PROTOCOL)
  362. # logging.info("[*] Saved graph")
  363. # Load dataset functions
  364. def load_mnist_dataset(shape=(-1, 784), path='data'):
  365. """Load the original mnist.
  366. Automatically download MNIST dataset and return the training, validation and test set with 50000, 10000 and 10000 digit images respectively.
  367. Parameters
  368. ----------
  369. shape : tuple
  370. The shape of digit images (the default is (-1, 784), alternatively (-1, 28, 28, 1)).
  371. path : str
  372. The path that the data is downloaded to.
  373. Returns
  374. -------
  375. X_train, y_train, X_val, y_val, X_test, y_test: tuple
  376. Return splitted training/validation/test set respectively.
  377. Examples
  378. --------
  379. >>> X_train, y_train, X_val, y_val, X_test, y_test = tl.files.load_mnist_dataset(shape=(-1,784), path='datasets')
  380. >>> X_train, y_train, X_val, y_val, X_test, y_test = tl.files.load_mnist_dataset(shape=(-1, 28, 28, 1))
  381. """
  382. return _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/')
  383. def load_fashion_mnist_dataset(shape=(-1, 784), path='data'):
  384. """Load the fashion mnist.
  385. 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>`__.
  386. Parameters
  387. ----------
  388. shape : tuple
  389. The shape of digit images (the default is (-1, 784), alternatively (-1, 28, 28, 1)).
  390. path : str
  391. The path that the data is downloaded to.
  392. Returns
  393. -------
  394. X_train, y_train, X_val, y_val, X_test, y_test: tuple
  395. Return splitted training/validation/test set respectively.
  396. Examples
  397. --------
  398. >>> X_train, y_train, X_val, y_val, X_test, y_test = tl.files.load_fashion_mnist_dataset(shape=(-1,784), path='datasets')
  399. >>> X_train, y_train, X_val, y_val, X_test, y_test = tl.files.load_fashion_mnist_dataset(shape=(-1, 28, 28, 1))
  400. """
  401. return _load_mnist_dataset(
  402. shape, path, name='fashion_mnist', url='http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/'
  403. )
  404. def _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/'):
  405. """A generic function to load mnist-like dataset.
  406. Parameters:
  407. ----------
  408. shape : tuple
  409. The shape of digit images.
  410. path : str
  411. The path that the data is downloaded to.
  412. name : str
  413. The dataset name you want to use(the default is 'mnist').
  414. url : str
  415. The url of dataset(the default is 'http://yann.lecun.com/exdb/mnist/').
  416. """
  417. path = os.path.join(path, name)
  418. # Define functions for loading mnist-like data's images and labels.
  419. # For convenience, they also download the requested files if needed.
  420. def load_mnist_images(path, filename):
  421. filepath = maybe_download_and_extract(filename, path, url)
  422. logging.info(filepath)
  423. # Read the inputs in Yann LeCun's binary format.
  424. with gzip.open(filepath, 'rb') as f:
  425. data = np.frombuffer(f.read(), np.uint8, offset=16)
  426. # The inputs are vectors now, we reshape them to monochrome 2D images,
  427. # following the shape convention: (examples, channels, rows, columns)
  428. data = data.reshape(shape)
  429. # The inputs come as bytes, we convert them to float32 in range [0,1].
  430. # (Actually to range [0, 255/256], for compatibility to the version
  431. # provided at http://deeplearning.net/data/mnist/mnist.pkl.gz.)
  432. return data / np.float32(256)
  433. def load_mnist_labels(path, filename):
  434. filepath = maybe_download_and_extract(filename, path, url)
  435. # Read the labels in Yann LeCun's binary format.
  436. with gzip.open(filepath, 'rb') as f:
  437. data = np.frombuffer(f.read(), np.uint8, offset=8)
  438. # The labels are vectors of integers now, that's exactly what we want.
  439. return data
  440. # Download and read the training and test set images and labels.
  441. logging.info("Load or Download {0} > {1}".format(name.upper(), path))
  442. X_train = load_mnist_images(path, 'train-images-idx3-ubyte.gz')
  443. y_train = load_mnist_labels(path, 'train-labels-idx1-ubyte.gz')
  444. X_test = load_mnist_images(path, 't10k-images-idx3-ubyte.gz')
  445. y_test = load_mnist_labels(path, 't10k-labels-idx1-ubyte.gz')
  446. # We reserve the last 10000 training examples for validation.
  447. X_train, X_val = X_train[:-10000], X_train[-10000:]
  448. y_train, y_val = y_train[:-10000], y_train[-10000:]
  449. # We just return all the arrays in order, as expected in main().
  450. # (It doesn't matter how we do this as long as we can read them again.)
  451. X_train = np.asarray(X_train, dtype=np.float32)
  452. y_train = np.asarray(y_train, dtype=np.int32)
  453. X_val = np.asarray(X_val, dtype=np.float32)
  454. y_val = np.asarray(y_val, dtype=np.int32)
  455. X_test = np.asarray(X_test, dtype=np.float32)
  456. y_test = np.asarray(y_test, dtype=np.int32)
  457. return X_train, y_train, X_val, y_val, X_test, y_test
  458. def load_cifar10_dataset(shape=(-1, 32, 32, 3), path='data', plotable=False):
  459. """Load CIFAR-10 dataset.
  460. It consists of 60000 32x32 colour images in 10 classes, with
  461. 6000 images per class. There are 50000 training images and 10000 test images.
  462. The dataset is divided into five training batches and one test batch, each with
  463. 10000 images. The test batch contains exactly 1000 randomly-selected images from
  464. each class. The training batches contain the remaining images in random order,
  465. but some training batches may contain more images from one class than another.
  466. Between them, the training batches contain exactly 5000 images from each class.
  467. Parameters
  468. ----------
  469. shape : tupe
  470. The shape of digit images e.g. (-1, 3, 32, 32) and (-1, 32, 32, 3).
  471. path : str
  472. The path that the data is downloaded to, defaults is ``data/cifar10/``.
  473. plotable : boolean
  474. Whether to plot some image examples, False as default.
  475. Examples
  476. --------
  477. >>> X_train, y_train, X_test, y_test = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3))
  478. References
  479. ----------
  480. - `CIFAR website <https://www.cs.toronto.edu/~kriz/cifar.html>`__
  481. - `Data download link <https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz>`__
  482. - `<https://teratail.com/questions/28932>`__
  483. """
  484. path = os.path.join(path, 'cifar10')
  485. logging.info("Load or Download cifar10 > {}".format(path))
  486. # Helper function to unpickle the data
  487. def unpickle(file):
  488. fp = open(file, 'rb')
  489. if sys.version_info.major == 2:
  490. data = pickle.load(fp)
  491. elif sys.version_info.major == 3:
  492. data = pickle.load(fp, encoding='latin-1')
  493. fp.close()
  494. return data
  495. filename = 'cifar-10-python.tar.gz'
  496. url = 'https://www.cs.toronto.edu/~kriz/'
  497. # Download and uncompress file
  498. maybe_download_and_extract(filename, path, url, extract=True)
  499. # Unpickle file and fill in data
  500. X_train = None
  501. y_train = []
  502. for i in range(1, 6):
  503. data_dic = unpickle(os.path.join(path, 'cifar-10-batches-py/', "data_batch_{}".format(i)))
  504. if i == 1:
  505. X_train = data_dic['data']
  506. else:
  507. X_train = np.vstack((X_train, data_dic['data']))
  508. y_train += data_dic['labels']
  509. test_data_dic = unpickle(os.path.join(path, 'cifar-10-batches-py/', "test_batch"))
  510. X_test = test_data_dic['data']
  511. y_test = np.array(test_data_dic['labels'])
  512. if shape == (-1, 3, 32, 32):
  513. X_test = X_test.reshape(shape)
  514. X_train = X_train.reshape(shape)
  515. elif shape == (-1, 32, 32, 3):
  516. X_test = X_test.reshape(shape, order='F')
  517. X_train = X_train.reshape(shape, order='F')
  518. X_test = np.transpose(X_test, (0, 2, 1, 3))
  519. X_train = np.transpose(X_train, (0, 2, 1, 3))
  520. else:
  521. X_test = X_test.reshape(shape)
  522. X_train = X_train.reshape(shape)
  523. y_train = np.array(y_train)
  524. if plotable:
  525. if sys.platform.startswith('darwin'):
  526. import matplotlib
  527. matplotlib.use('TkAgg')
  528. import matplotlib.pyplot as plt
  529. logging.info('\nCIFAR-10')
  530. fig = plt.figure(1)
  531. logging.info('Shape of a training image: X_train[0] %s' % X_train[0].shape)
  532. plt.ion() # interactive mode
  533. count = 1
  534. for _ in range(10): # each row
  535. for _ in range(10): # each column
  536. _ = fig.add_subplot(10, 10, count)
  537. if shape == (-1, 3, 32, 32):
  538. # plt.imshow(X_train[count-1], interpolation='nearest')
  539. plt.imshow(np.transpose(X_train[count - 1], (1, 2, 0)), interpolation='nearest')
  540. # plt.imshow(np.transpose(X_train[count-1], (2, 1, 0)), interpolation='nearest')
  541. elif shape == (-1, 32, 32, 3):
  542. plt.imshow(X_train[count - 1], interpolation='nearest')
  543. # plt.imshow(np.transpose(X_train[count-1], (1, 0, 2)), interpolation='nearest')
  544. else:
  545. raise Exception("Do not support the given 'shape' to plot the image examples")
  546. plt.gca().xaxis.set_major_locator(plt.NullLocator()) # 不显示刻度(tick)
  547. plt.gca().yaxis.set_major_locator(plt.NullLocator())
  548. count = count + 1
  549. plt.draw() # interactive mode
  550. plt.pause(3) # interactive mode
  551. logging.info("X_train: %s" % X_train.shape)
  552. logging.info("y_train: %s" % y_train.shape)
  553. logging.info("X_test: %s" % X_test.shape)
  554. logging.info("y_test: %s" % y_test.shape)
  555. X_train = np.asarray(X_train, dtype=np.float32)
  556. X_test = np.asarray(X_test, dtype=np.float32)
  557. y_train = np.asarray(y_train, dtype=np.int32)
  558. y_test = np.asarray(y_test, dtype=np.int32)
  559. return X_train, y_train, X_test, y_test
  560. def load_cropped_svhn(path='data', include_extra=True):
  561. """Load Cropped SVHN.
  562. The Cropped Street View House Numbers (SVHN) Dataset contains 32x32x3 RGB images.
  563. 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/>`__.
  564. Parameters
  565. ----------
  566. path : str
  567. The path that the data is downloaded to.
  568. include_extra : boolean
  569. If True (default), add extra images to the training set.
  570. Returns
  571. -------
  572. X_train, y_train, X_test, y_test: tuple
  573. Return splitted training/test set respectively.
  574. Examples
  575. ---------
  576. >>> X_train, y_train, X_test, y_test = tl.files.load_cropped_svhn(include_extra=False)
  577. >>> tl.vis.save_images(X_train[0:100], [10, 10], 'svhn.png')
  578. """
  579. start_time = time.time()
  580. path = os.path.join(path, 'cropped_svhn')
  581. logging.info("Load or Download Cropped SVHN > {} | include extra images: {}".format(path, include_extra))
  582. url = "http://ufldl.stanford.edu/housenumbers/"
  583. np_file = os.path.join(path, "train_32x32.npz")
  584. if file_exists(np_file) is False:
  585. filename = "train_32x32.mat"
  586. filepath = maybe_download_and_extract(filename, path, url)
  587. mat = sio.loadmat(filepath)
  588. X_train = mat['X'] / 255.0 # to [0, 1]
  589. X_train = np.transpose(X_train, (3, 0, 1, 2))
  590. y_train = np.squeeze(mat['y'], axis=1)
  591. y_train[y_train == 10] = 0 # replace 10 to 0
  592. np.savez(np_file, X=X_train, y=y_train)
  593. del_file(filepath)
  594. else:
  595. v = np.load(np_file, allow_pickle=True)
  596. X_train = v['X']
  597. y_train = v['y']
  598. logging.info(" n_train: {}".format(len(y_train)))
  599. np_file = os.path.join(path, "test_32x32.npz")
  600. if file_exists(np_file) is False:
  601. filename = "test_32x32.mat"
  602. filepath = maybe_download_and_extract(filename, path, url)
  603. mat = sio.loadmat(filepath)
  604. X_test = mat['X'] / 255.0
  605. X_test = np.transpose(X_test, (3, 0, 1, 2))
  606. y_test = np.squeeze(mat['y'], axis=1)
  607. y_test[y_test == 10] = 0
  608. np.savez(np_file, X=X_test, y=y_test)
  609. del_file(filepath)
  610. else:
  611. v = np.load(np_file, allow_pickle=True)
  612. X_test = v['X']
  613. y_test = v['y']
  614. logging.info(" n_test: {}".format(len(y_test)))
  615. if include_extra:
  616. logging.info(" getting extra 531131 images, please wait ...")
  617. np_file = os.path.join(path, "extra_32x32.npz")
  618. if file_exists(np_file) is False:
  619. logging.info(" the first time to load extra images will take long time to convert the file format ...")
  620. filename = "extra_32x32.mat"
  621. filepath = maybe_download_and_extract(filename, path, url)
  622. mat = sio.loadmat(filepath)
  623. X_extra = mat['X'] / 255.0
  624. X_extra = np.transpose(X_extra, (3, 0, 1, 2))
  625. y_extra = np.squeeze(mat['y'], axis=1)
  626. y_extra[y_extra == 10] = 0
  627. np.savez(np_file, X=X_extra, y=y_extra)
  628. del_file(filepath)
  629. else:
  630. v = np.load(np_file, allow_pickle=True)
  631. X_extra = v['X']
  632. y_extra = v['y']
  633. # print(X_train.shape, X_extra.shape)
  634. logging.info(" adding n_extra {} to n_train {}".format(len(y_extra), len(y_train)))
  635. t = time.time()
  636. X_train = np.concatenate((X_train, X_extra), 0)
  637. y_train = np.concatenate((y_train, y_extra), 0)
  638. # X_train = np.append(X_train, X_extra, axis=0)
  639. # y_train = np.append(y_train, y_extra, axis=0)
  640. logging.info(" added n_extra {} to n_train {} took {}s".format(len(y_extra), len(y_train), time.time() - t))
  641. else:
  642. logging.info(" no extra images are included")
  643. logging.info(" image size: %s n_train: %d n_test: %d" % (str(X_train.shape[1:4]), len(y_train), len(y_test)))
  644. logging.info(" took: {}s".format(int(time.time() - start_time)))
  645. return X_train, y_train, X_test, y_test
  646. def load_ptb_dataset(path='data'):
  647. """Load Penn TreeBank (PTB) dataset.
  648. It is used in many LANGUAGE MODELING papers,
  649. including "Empirical Evaluation and Combination of Advanced Language
  650. Modeling Techniques", "Recurrent Neural Network Regularization".
  651. It consists of 929k training words, 73k validation words, and 82k test
  652. words. It has 10k words in its vocabulary.
  653. Parameters
  654. ----------
  655. path : str
  656. The path that the data is downloaded to, defaults is ``data/ptb/``.
  657. Returns
  658. --------
  659. train_data, valid_data, test_data : list of int
  660. The training, validating and testing data in integer format.
  661. vocab_size : int
  662. The vocabulary size.
  663. Examples
  664. --------
  665. >>> train_data, valid_data, test_data, vocab_size = tl.files.load_ptb_dataset()
  666. References
  667. ---------------
  668. - ``tensorflow.models.rnn.ptb import reader``
  669. - `Manual download <http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz>`__
  670. Notes
  671. ------
  672. - If you want to get the raw data, see the source code.
  673. """
  674. path = os.path.join(path, 'ptb')
  675. logging.info("Load or Download Penn TreeBank (PTB) dataset > {}".format(path))
  676. # Maybe dowload and uncompress tar, or load exsisting files
  677. filename = 'simple-examples.tgz'
  678. url = 'http://www.fit.vutbr.cz/~imikolov/rnnlm/'
  679. maybe_download_and_extract(filename, path, url, extract=True)
  680. data_path = os.path.join(path, 'simple-examples', 'data')
  681. train_path = os.path.join(data_path, "ptb.train.txt")
  682. valid_path = os.path.join(data_path, "ptb.valid.txt")
  683. test_path = os.path.join(data_path, "ptb.test.txt")
  684. word_to_id = nlp.build_vocab(nlp.read_words(train_path))
  685. train_data = nlp.words_to_word_ids(nlp.read_words(train_path), word_to_id)
  686. valid_data = nlp.words_to_word_ids(nlp.read_words(valid_path), word_to_id)
  687. test_data = nlp.words_to_word_ids(nlp.read_words(test_path), word_to_id)
  688. vocab_size = len(word_to_id)
  689. # logging.info(nlp.read_words(train_path)) # ... 'according', 'to', 'mr.', '<unk>', '<eos>']
  690. # logging.info(train_data) # ... 214, 5, 23, 1, 2]
  691. # logging.info(word_to_id) # ... 'beyond': 1295, 'anti-nuclear': 9599, 'trouble': 1520, '<eos>': 2 ... }
  692. # logging.info(vocabulary) # 10000
  693. # exit()
  694. return train_data, valid_data, test_data, vocab_size
  695. def load_matt_mahoney_text8_dataset(path='data'):
  696. """Load Matt Mahoney's dataset.
  697. Download a text file from Matt Mahoney's website
  698. if not present, and make sure it's the right size.
  699. Extract the first file enclosed in a zip file as a list of words.
  700. This dataset can be used for Word Embedding.
  701. Parameters
  702. ----------
  703. path : str
  704. The path that the data is downloaded to, defaults is ``data/mm_test8/``.
  705. Returns
  706. --------
  707. list of str
  708. The raw text data e.g. [.... 'their', 'families', 'who', 'were', 'expelled', 'from', 'jerusalem', ...]
  709. Examples
  710. --------
  711. >>> words = tl.files.load_matt_mahoney_text8_dataset()
  712. >>> print('Data size', len(words))
  713. """
  714. path = os.path.join(path, 'mm_test8')
  715. logging.info("Load or Download matt_mahoney_text8 Dataset> {}".format(path))
  716. filename = 'text8.zip'
  717. url = 'http://mattmahoney.net/dc/'
  718. maybe_download_and_extract(filename, path, url, expected_bytes=31344016)
  719. with zipfile.ZipFile(os.path.join(path, filename)) as f:
  720. word_list = f.read(f.namelist()[0]).split()
  721. for idx, _ in enumerate(word_list):
  722. word_list[idx] = word_list[idx].decode()
  723. return word_list
  724. def load_imdb_dataset(
  725. path='data', nb_words=None, skip_top=0, maxlen=None, test_split=0.2, seed=113, start_char=1, oov_char=2,
  726. index_from=3
  727. ):
  728. """Load IMDB dataset.
  729. Parameters
  730. ----------
  731. path : str
  732. The path that the data is downloaded to, defaults is ``data/imdb/``.
  733. nb_words : int
  734. Number of words to get.
  735. skip_top : int
  736. Top most frequent words to ignore (they will appear as oov_char value in the sequence data).
  737. maxlen : int
  738. Maximum sequence length. Any longer sequence will be truncated.
  739. seed : int
  740. Seed for reproducible data shuffling.
  741. start_char : int
  742. The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character.
  743. oov_char : int
  744. Words that were cut out because of the num_words or skip_top limit will be replaced with this character.
  745. index_from : int
  746. Index actual words with this index and higher.
  747. Examples
  748. --------
  749. >>> X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(
  750. ... nb_words=20000, test_split=0.2)
  751. >>> print('X_train.shape', X_train.shape)
  752. (20000,) [[1, 62, 74, ... 1033, 507, 27],[1, 60, 33, ... 13, 1053, 7]..]
  753. >>> print('y_train.shape', y_train.shape)
  754. (20000,) [1 0 0 ..., 1 0 1]
  755. References
  756. -----------
  757. - `Modified from keras. <https://github.com/fchollet/keras/blob/master/keras/datasets/imdb.py>`__
  758. """
  759. path = os.path.join(path, 'imdb')
  760. filename = "imdb.pkl"
  761. url = 'https://s3.amazonaws.com/text-datasets/'
  762. maybe_download_and_extract(filename, path, url)
  763. if filename.endswith(".gz"):
  764. f = gzip.open(os.path.join(path, filename), 'rb')
  765. else:
  766. f = open(os.path.join(path, filename), 'rb')
  767. X, labels = cPickle.load(f)
  768. f.close()
  769. np.random.seed(seed)
  770. np.random.shuffle(X)
  771. np.random.seed(seed)
  772. np.random.shuffle(labels)
  773. if start_char is not None:
  774. X = [[start_char] + [w + index_from for w in x] for x in X]
  775. elif index_from:
  776. X = [[w + index_from for w in x] for x in X]
  777. if maxlen:
  778. new_X = []
  779. new_labels = []
  780. for x, y in zip(X, labels):
  781. if len(x) < maxlen:
  782. new_X.append(x)
  783. new_labels.append(y)
  784. X = new_X
  785. labels = new_labels
  786. if not X:
  787. raise Exception(
  788. 'After filtering for sequences shorter than maxlen=' + str(maxlen) + ', no sequence was kept. '
  789. 'Increase maxlen.'
  790. )
  791. if not nb_words:
  792. nb_words = max([max(x) for x in X])
  793. # by convention, use 2 as OOV word
  794. # reserve 'index_from' (=3 by default) characters: 0 (padding), 1 (start), 2 (OOV)
  795. if oov_char is not None:
  796. X = [[oov_char if (w >= nb_words or w < skip_top) else w for w in x] for x in X]
  797. else:
  798. nX = []
  799. for x in X:
  800. nx = []
  801. for w in x:
  802. if (w >= nb_words or w < skip_top):
  803. nx.append(w)
  804. nX.append(nx)
  805. X = nX
  806. X_train = np.array(X[:int(len(X) * (1 - test_split))])
  807. y_train = np.array(labels[:int(len(X) * (1 - test_split))])
  808. X_test = np.array(X[int(len(X) * (1 - test_split)):])
  809. y_test = np.array(labels[int(len(X) * (1 - test_split)):])
  810. return X_train, y_train, X_test, y_test
  811. def load_nietzsche_dataset(path='data'):
  812. """Load Nietzsche dataset.
  813. Parameters
  814. ----------
  815. path : str
  816. The path that the data is downloaded to, defaults is ``data/nietzsche/``.
  817. Returns
  818. --------
  819. str
  820. The content.
  821. Examples
  822. --------
  823. >>> see tutorial_generate_text.py
  824. >>> words = tl.files.load_nietzsche_dataset()
  825. >>> words = basic_clean_str(words)
  826. >>> words = words.split()
  827. """
  828. logging.info("Load or Download nietzsche dataset > {}".format(path))
  829. path = os.path.join(path, 'nietzsche')
  830. filename = "nietzsche.txt"
  831. url = 'https://s3.amazonaws.com/text-datasets/'
  832. filepath = maybe_download_and_extract(filename, path, url)
  833. with open(filepath, "r") as f:
  834. words = f.read()
  835. return words
  836. def load_wmt_en_fr_dataset(path='data'):
  837. """Load WMT'15 English-to-French translation dataset.
  838. 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.
  839. Returns the directories of training data and test data.
  840. Parameters
  841. ----------
  842. path : str
  843. The path that the data is downloaded to, defaults is ``data/wmt_en_fr/``.
  844. References
  845. ----------
  846. - Code modified from /tensorflow/models/rnn/translation/data_utils.py
  847. Notes
  848. -----
  849. Usually, it will take a long time to download this dataset.
  850. """
  851. path = os.path.join(path, 'wmt_en_fr')
  852. # URLs for WMT data.
  853. _WMT_ENFR_TRAIN_URL = "http://www.statmt.org/wmt10/"
  854. _WMT_ENFR_DEV_URL = "http://www.statmt.org/wmt15/"
  855. def gunzip_file(gz_path, new_path):
  856. """Unzips from gz_path into new_path."""
  857. logging.info("Unpacking %s to %s" % (gz_path, new_path))
  858. with gzip.open(gz_path, "rb") as gz_file:
  859. with open(new_path, "wb") as new_file:
  860. for line in gz_file:
  861. new_file.write(line)
  862. def get_wmt_enfr_train_set(path):
  863. """Download the WMT en-fr training corpus to directory unless it's there."""
  864. filename = "training-giga-fren.tar"
  865. maybe_download_and_extract(filename, path, _WMT_ENFR_TRAIN_URL, extract=True)
  866. train_path = os.path.join(path, "giga-fren.release2.fixed")
  867. gunzip_file(train_path + ".fr.gz", train_path + ".fr")
  868. gunzip_file(train_path + ".en.gz", train_path + ".en")
  869. return train_path
  870. def get_wmt_enfr_dev_set(path):
  871. """Download the WMT en-fr training corpus to directory unless it's there."""
  872. filename = "dev-v2.tgz"
  873. dev_file = maybe_download_and_extract(filename, path, _WMT_ENFR_DEV_URL, extract=False)
  874. dev_name = "newstest2013"
  875. dev_path = os.path.join(path, "newstest2013")
  876. if not (gfile.Exists(dev_path + ".fr") and gfile.Exists(dev_path + ".en")):
  877. logging.info("Extracting tgz file %s" % dev_file)
  878. with tarfile.open(dev_file, "r:gz") as dev_tar:
  879. fr_dev_file = dev_tar.getmember("dev/" + dev_name + ".fr")
  880. en_dev_file = dev_tar.getmember("dev/" + dev_name + ".en")
  881. fr_dev_file.name = dev_name + ".fr" # Extract without "dev/" prefix.
  882. en_dev_file.name = dev_name + ".en"
  883. dev_tar.extract(fr_dev_file, path)
  884. dev_tar.extract(en_dev_file, path)
  885. return dev_path
  886. logging.info("Load or Download WMT English-to-French translation > {}".format(path))
  887. train_path = get_wmt_enfr_train_set(path)
  888. dev_path = get_wmt_enfr_dev_set(path)
  889. return train_path, dev_path
  890. def load_flickr25k_dataset(tag='sky', path="data", n_threads=50, printable=False):
  891. """Load Flickr25K dataset.
  892. Returns a list of images by a given tag from Flick25k dataset,
  893. it will download Flickr25k from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__
  894. at the first time you use it.
  895. Parameters
  896. ------------
  897. tag : str or None
  898. What images to return.
  899. - If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.
  900. - If you want to get all images, set to ``None``.
  901. path : str
  902. The path that the data is downloaded to, defaults is ``data/flickr25k/``.
  903. n_threads : int
  904. The number of thread to read image.
  905. printable : boolean
  906. Whether to print infomation when reading images, default is ``False``.
  907. Examples
  908. -----------
  909. Get images with tag of sky
  910. >>> images = tl.files.load_flickr25k_dataset(tag='sky')
  911. Get all images
  912. >>> images = tl.files.load_flickr25k_dataset(tag=None, n_threads=100, printable=True)
  913. """
  914. path = os.path.join(path, 'flickr25k')
  915. filename = 'mirflickr25k.zip'
  916. url = 'http://press.liacs.nl/mirflickr/mirflickr25k/'
  917. # download dataset
  918. if folder_exists(os.path.join(path, "mirflickr")) is False:
  919. logging.info("[*] Flickr25k is nonexistent in {}".format(path))
  920. maybe_download_and_extract(filename, path, url, extract=True)
  921. del_file(os.path.join(path, filename))
  922. # return images by the given tag.
  923. # 1. image path list
  924. folder_imgs = os.path.join(path, "mirflickr")
  925. path_imgs = load_file_list(path=folder_imgs, regx='\\.jpg', printable=False)
  926. path_imgs.sort(key=natural_keys)
  927. # 2. tag path list
  928. folder_tags = os.path.join(path, "mirflickr", "meta", "tags")
  929. path_tags = load_file_list(path=folder_tags, regx='\\.txt', printable=False)
  930. path_tags.sort(key=natural_keys)
  931. # 3. select images
  932. if tag is None:
  933. logging.info("[Flickr25k] reading all images")
  934. else:
  935. logging.info("[Flickr25k] reading images with tag: {}".format(tag))
  936. images_list = []
  937. for idx, _v in enumerate(path_tags):
  938. tags = read_file(os.path.join(folder_tags, path_tags[idx])).split('\n')
  939. # logging.info(idx+1, tags)
  940. if tag is None or tag in tags:
  941. images_list.append(path_imgs[idx])
  942. images = visualize.read_images(images_list, folder_imgs, n_threads=n_threads, printable=printable)
  943. return images
  944. def load_flickr1M_dataset(tag='sky', size=10, path="data", n_threads=50, printable=False):
  945. """Load Flick1M dataset.
  946. Returns a list of images by a given tag from Flickr1M dataset,
  947. it will download Flickr1M from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__
  948. at the first time you use it.
  949. Parameters
  950. ------------
  951. tag : str or None
  952. What images to return.
  953. - If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.
  954. - If you want to get all images, set to ``None``.
  955. size : int
  956. integer between 1 to 10. 1 means 100k images ... 5 means 500k images, 10 means all 1 million images. Default is 10.
  957. path : str
  958. The path that the data is downloaded to, defaults is ``data/flickr25k/``.
  959. n_threads : int
  960. The number of thread to read image.
  961. printable : boolean
  962. Whether to print infomation when reading images, default is ``False``.
  963. Examples
  964. ----------
  965. Use 200k images
  966. >>> images = tl.files.load_flickr1M_dataset(tag='zebra', size=2)
  967. Use 1 Million images
  968. >>> images = tl.files.load_flickr1M_dataset(tag='zebra')
  969. """
  970. path = os.path.join(path, 'flickr1M')
  971. logging.info("[Flickr1M] using {}% of images = {}".format(size * 10, size * 100000))
  972. images_zip = [
  973. 'images0.zip', 'images1.zip', 'images2.zip', 'images3.zip', 'images4.zip', 'images5.zip', 'images6.zip',
  974. 'images7.zip', 'images8.zip', 'images9.zip'
  975. ]
  976. tag_zip = 'tags.zip'
  977. url = 'http://press.liacs.nl/mirflickr/mirflickr1m/'
  978. # download dataset
  979. for image_zip in images_zip[0:size]:
  980. image_folder = image_zip.split(".")[0]
  981. # logging.info(path+"/"+image_folder)
  982. if folder_exists(os.path.join(path, image_folder)) is False:
  983. # logging.info(image_zip)
  984. logging.info("[Flickr1M] {} is missing in {}".format(image_folder, path))
  985. maybe_download_and_extract(image_zip, path, url, extract=True)
  986. del_file(os.path.join(path, image_zip))
  987. # os.system("mv {} {}".format(os.path.join(path, 'images'), os.path.join(path, image_folder)))
  988. shutil.move(os.path.join(path, 'images'), os.path.join(path, image_folder))
  989. else:
  990. logging.info("[Flickr1M] {} exists in {}".format(image_folder, path))
  991. # download tag
  992. if folder_exists(os.path.join(path, "tags")) is False:
  993. logging.info("[Flickr1M] tag files is nonexistent in {}".format(path))
  994. maybe_download_and_extract(tag_zip, path, url, extract=True)
  995. del_file(os.path.join(path, tag_zip))
  996. else:
  997. logging.info("[Flickr1M] tags exists in {}".format(path))
  998. # 1. image path list
  999. images_list = []
  1000. images_folder_list = []
  1001. for i in range(0, size):
  1002. images_folder_list += load_folder_list(path=os.path.join(path, 'images%d' % i))
  1003. images_folder_list.sort(key=lambda s: int(s.split('/')[-1])) # folder/images/ddd
  1004. for folder in images_folder_list[0:size * 10]:
  1005. tmp = load_file_list(path=folder, regx='\\.jpg', printable=False)
  1006. tmp.sort(key=lambda s: int(s.split('.')[-2])) # ddd.jpg
  1007. images_list.extend([os.path.join(folder, x) for x in tmp])
  1008. # 2. tag path list
  1009. tag_list = []
  1010. tag_folder_list = load_folder_list(os.path.join(path, "tags"))
  1011. # tag_folder_list.sort(key=lambda s: int(s.split("/")[-1])) # folder/images/ddd
  1012. tag_folder_list.sort(key=lambda s: int(os.path.basename(s)))
  1013. for folder in tag_folder_list[0:size * 10]:
  1014. tmp = load_file_list(path=folder, regx='\\.txt', printable=False)
  1015. tmp.sort(key=lambda s: int(s.split('.')[-2])) # ddd.txt
  1016. tmp = [os.path.join(folder, s) for s in tmp]
  1017. tag_list += tmp
  1018. # 3. select images
  1019. logging.info("[Flickr1M] searching tag: {}".format(tag))
  1020. select_images_list = []
  1021. for idx, _val in enumerate(tag_list):
  1022. tags = read_file(tag_list[idx]).split('\n')
  1023. if tag in tags:
  1024. select_images_list.append(images_list[idx])
  1025. logging.info("[Flickr1M] reading images with tag: {}".format(tag))
  1026. images = visualize.read_images(select_images_list, '', n_threads=n_threads, printable=printable)
  1027. return images
  1028. def load_cyclegan_dataset(filename='summer2winter_yosemite', path='data'):
  1029. """Load images from CycleGAN's database, see `this link <https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/>`__.
  1030. Parameters
  1031. ------------
  1032. filename : str
  1033. The dataset you want, see `this link <https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/>`__.
  1034. path : str
  1035. The path that the data is downloaded to, defaults is `data/cyclegan`
  1036. Examples
  1037. ---------
  1038. >>> im_train_A, im_train_B, im_test_A, im_test_B = load_cyclegan_dataset(filename='summer2winter_yosemite')
  1039. """
  1040. path = os.path.join(path, 'cyclegan')
  1041. url = 'https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/'
  1042. if folder_exists(os.path.join(path, filename)) is False:
  1043. logging.info("[*] {} is nonexistent in {}".format(filename, path))
  1044. maybe_download_and_extract(filename + '.zip', path, url, extract=True)
  1045. del_file(os.path.join(path, filename + '.zip'))
  1046. def load_image_from_folder(path):
  1047. path_imgs = load_file_list(path=path, regx='\\.jpg', printable=False)
  1048. return visualize.read_images(path_imgs, path=path, n_threads=10, printable=False)
  1049. im_train_A = load_image_from_folder(os.path.join(path, filename, "trainA"))
  1050. im_train_B = load_image_from_folder(os.path.join(path, filename, "trainB"))
  1051. im_test_A = load_image_from_folder(os.path.join(path, filename, "testA"))
  1052. im_test_B = load_image_from_folder(os.path.join(path, filename, "testB"))
  1053. def if_2d_to_3d(images): # [h, w] --> [h, w, 3]
  1054. for i, _v in enumerate(images):
  1055. if len(images[i].shape) == 2:
  1056. images[i] = images[i][:, :, np.newaxis]
  1057. images[i] = np.tile(images[i], (1, 1, 3))
  1058. return images
  1059. im_train_A = if_2d_to_3d(im_train_A)
  1060. im_train_B = if_2d_to_3d(im_train_B)
  1061. im_test_A = if_2d_to_3d(im_test_A)
  1062. im_test_B = if_2d_to_3d(im_test_B)
  1063. return im_train_A, im_train_B, im_test_A, im_test_B
  1064. def download_file_from_google_drive(ID, destination):
  1065. """Download file from Google Drive.
  1066. See ``tl.files.load_celebA_dataset`` for example.
  1067. Parameters
  1068. --------------
  1069. ID : str
  1070. The driver ID.
  1071. destination : str
  1072. The destination for save file.
  1073. """
  1074. try:
  1075. from tqdm import tqdm
  1076. except ImportError as e:
  1077. print(e)
  1078. raise ImportError("Module tqdm not found. Please install tqdm via pip or other package managers.")
  1079. try:
  1080. import requests
  1081. except ImportError as e:
  1082. print(e)
  1083. raise ImportError("Module requests not found. Please install requests via pip or other package managers.")
  1084. def save_response_content(response, destination, chunk_size=32 * 1024):
  1085. total_size = int(response.headers.get('content-length', 0))
  1086. with open(destination, "wb") as f:
  1087. for chunk in tqdm(response.iter_content(chunk_size), total=total_size, unit='B', unit_scale=True,
  1088. desc=destination):
  1089. if chunk: # filter out keep-alive new chunks
  1090. f.write(chunk)
  1091. def get_confirm_token(response):
  1092. for key, value in response.cookies.items():
  1093. if key.startswith('download_warning'):
  1094. return value
  1095. return None
  1096. URL = "https://docs.google.com/uc?export=download"
  1097. session = requests.Session()
  1098. response = session.get(URL, params={'id': ID}, stream=True)
  1099. token = get_confirm_token(response)
  1100. if token:
  1101. params = {'id': ID, 'confirm': token}
  1102. response = session.get(URL, params=params, stream=True)
  1103. save_response_content(response, destination)
  1104. def load_celebA_dataset(path='data'):
  1105. """Load CelebA dataset
  1106. Return a list of image path.
  1107. Parameters
  1108. -----------
  1109. path : str
  1110. The path that the data is downloaded to, defaults is ``data/celebA/``.
  1111. """
  1112. data_dir = 'celebA'
  1113. filename, drive_id = "img_align_celeba.zip", "0B7EVK8r0v71pZjFTYXZWM3FlRnM"
  1114. save_path = os.path.join(path, filename)
  1115. image_path = os.path.join(path, data_dir)
  1116. if os.path.exists(image_path):
  1117. logging.info('[*] {} already exists'.format(save_path))
  1118. else:
  1119. exists_or_mkdir(path)
  1120. download_file_from_google_drive(drive_id, save_path)
  1121. zip_dir = ''
  1122. with zipfile.ZipFile(save_path) as zf:
  1123. zip_dir = zf.namelist()[0]
  1124. zf.extractall(path)
  1125. os.remove(save_path)
  1126. os.rename(os.path.join(path, zip_dir), image_path)
  1127. data_files = load_file_list(path=image_path, regx='\\.jpg', printable=False)
  1128. for i, _v in enumerate(data_files):
  1129. data_files[i] = os.path.join(image_path, data_files[i])
  1130. return data_files
  1131. def load_voc_dataset(path='data', dataset='2012', contain_classes_in_person=False):
  1132. """Pascal VOC 2007/2012 Dataset.
  1133. It has 20 objects:
  1134. aeroplane, bicycle, bird, boat, bottle, bus, car, cat, chair, cow, diningtable, dog, horse, motorbike, person, pottedplant, sheep, sofa, train, tvmonitor
  1135. and additional 3 classes : head, hand, foot for person.
  1136. Parameters
  1137. -----------
  1138. path : str
  1139. The path that the data is downloaded to, defaults is ``data/VOC``.
  1140. dataset : str
  1141. The VOC dataset version, `2012`, `2007`, `2007test` or `2012test`. We usually train model on `2007+2012` and test it on `2007test`.
  1142. contain_classes_in_person : boolean
  1143. Whether include head, hand and foot annotation, default is False.
  1144. Returns
  1145. ---------
  1146. imgs_file_list : list of str
  1147. Full paths of all images.
  1148. imgs_semseg_file_list : list of str
  1149. Full paths of all maps for semantic segmentation. Note that not all images have this map!
  1150. imgs_insseg_file_list : list of str
  1151. Full paths of all maps for instance segmentation. Note that not all images have this map!
  1152. imgs_ann_file_list : list of str
  1153. Full paths of all annotations for bounding box and object class, all images have this annotations.
  1154. classes : list of str
  1155. Classes in order.
  1156. classes_in_person : list of str
  1157. Classes in person.
  1158. classes_dict : dictionary
  1159. Class label to integer.
  1160. n_objs_list : list of int
  1161. Number of objects in all images in ``imgs_file_list`` in order.
  1162. objs_info_list : list of str
  1163. Darknet format for the annotation of all images in ``imgs_file_list`` in order. ``[class_id x_centre y_centre width height]`` in ratio format.
  1164. objs_info_dicts : dictionary
  1165. The annotation of all images in ``imgs_file_list``, ``{imgs_file_list : dictionary for annotation}``,
  1166. format from `TensorFlow/Models/object-detection <https://github.com/tensorflow/models/blob/master/object_detection/create_pascal_tf_record.py>`__.
  1167. Examples
  1168. ----------
  1169. >>> imgs_file_list, imgs_semseg_file_list, imgs_insseg_file_list, imgs_ann_file_list,
  1170. >>> classes, classes_in_person, classes_dict,
  1171. >>> n_objs_list, objs_info_list, objs_info_dicts = tl.files.load_voc_dataset(dataset="2012", contain_classes_in_person=False)
  1172. >>> idx = 26
  1173. >>> print(classes)
  1174. ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
  1175. >>> print(classes_dict)
  1176. {'sheep': 16, 'horse': 12, 'bicycle': 1, 'bottle': 4, 'cow': 9, 'sofa': 17, 'car': 6, 'dog': 11, 'cat': 7, 'person': 14, 'train': 18, 'diningtable': 10, 'aeroplane': 0, 'bus': 5, 'pottedplant': 15, 'tvmonitor': 19, 'chair': 8, 'bird': 2, 'boat': 3, 'motorbike': 13}
  1177. >>> print(imgs_file_list[idx])
  1178. data/VOC/VOC2012/JPEGImages/2007_000423.jpg
  1179. >>> print(n_objs_list[idx])
  1180. 2
  1181. >>> print(imgs_ann_file_list[idx])
  1182. data/VOC/VOC2012/Annotations/2007_000423.xml
  1183. >>> print(objs_info_list[idx])
  1184. 14 0.173 0.461333333333 0.142 0.496
  1185. 14 0.828 0.542666666667 0.188 0.594666666667
  1186. >>> ann = tl.prepro.parse_darknet_ann_str_to_list(objs_info_list[idx])
  1187. >>> print(ann)
  1188. [[14, 0.173, 0.461333333333, 0.142, 0.496], [14, 0.828, 0.542666666667, 0.188, 0.594666666667]]
  1189. >>> c, b = tl.prepro.parse_darknet_ann_list_to_cls_box(ann)
  1190. >>> print(c, b)
  1191. [14, 14] [[0.173, 0.461333333333, 0.142, 0.496], [0.828, 0.542666666667, 0.188, 0.594666666667]]
  1192. References
  1193. -------------
  1194. - `Pascal VOC2012 Website <http://host.robots.ox.ac.uk/pascal/VOC/voc2012/#devkit>`__.
  1195. - `Pascal VOC2007 Website <http://host.robots.ox.ac.uk/pascal/VOC/voc2007/>`__.
  1196. """
  1197. import xml.etree.ElementTree as ET
  1198. try:
  1199. import lxml.etree as etree
  1200. except ImportError as e:
  1201. print(e)
  1202. raise ImportError("Module lxml not found. Please install lxml via pip or other package managers.")
  1203. path = os.path.join(path, 'VOC')
  1204. def _recursive_parse_xml_to_dict(xml):
  1205. """Recursively parses XML contents to python dict.
  1206. We assume that `object` tags are the only ones that can appear
  1207. multiple times at the same level of a tree.
  1208. Args:
  1209. xml: xml tree obtained by parsing XML file contents using lxml.etree
  1210. Returns:
  1211. Python dictionary holding XML contents.
  1212. """
  1213. if not xml:
  1214. # if xml is not None:
  1215. return {xml.tag: xml.text}
  1216. result = {}
  1217. for child in xml:
  1218. child_result = _recursive_parse_xml_to_dict(child)
  1219. if child.tag != 'object':
  1220. result[child.tag] = child_result[child.tag]
  1221. else:
  1222. if child.tag not in result:
  1223. result[child.tag] = []
  1224. result[child.tag].append(child_result[child.tag])
  1225. return {xml.tag: result}
  1226. if dataset == "2012":
  1227. url = "http://host.robots.ox.ac.uk/pascal/VOC/voc2012/"
  1228. tar_filename = "VOCtrainval_11-May-2012.tar"
  1229. extracted_filename = "VOC2012" # "VOCdevkit/VOC2012"
  1230. logging.info(" [============= VOC 2012 =============]")
  1231. elif dataset == "2012test":
  1232. extracted_filename = "VOC2012test" # "VOCdevkit/VOC2012"
  1233. logging.info(" [============= VOC 2012 Test Set =============]")
  1234. logging.info(
  1235. " \nAuthor: 2012test only have person annotation, so 2007test is highly recommended for testing !\n"
  1236. )
  1237. time.sleep(3)
  1238. if os.path.isdir(os.path.join(path, extracted_filename)) is False:
  1239. logging.info("For VOC 2012 Test data - online registration required")
  1240. logging.info(
  1241. " Please download VOC2012test.tar from: \n register: http://host.robots.ox.ac.uk:8080 \n voc2012 : http://host.robots.ox.ac.uk:8080/eval/challenges/voc2012/ \ndownload: http://host.robots.ox.ac.uk:8080/eval/downloads/VOC2012test.tar"
  1242. )
  1243. logging.info(" unzip VOC2012test.tar,rename the folder to VOC2012test and put it into %s" % path)
  1244. exit()
  1245. # # http://host.robots.ox.ac.uk:8080/eval/downloads/VOC2012test.tar
  1246. # url = "http://host.robots.ox.ac.uk:8080/eval/downloads/"
  1247. # tar_filename = "VOC2012test.tar"
  1248. elif dataset == "2007":
  1249. url = "http://host.robots.ox.ac.uk/pascal/VOC/voc2007/"
  1250. tar_filename = "VOCtrainval_06-Nov-2007.tar"
  1251. extracted_filename = "VOC2007"
  1252. logging.info(" [============= VOC 2007 =============]")
  1253. elif dataset == "2007test":
  1254. # http://host.robots.ox.ac.uk/pascal/VOC/voc2007/index.html#testdata
  1255. # http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtest_06-Nov-2007.tar
  1256. url = "http://host.robots.ox.ac.uk/pascal/VOC/voc2007/"
  1257. tar_filename = "VOCtest_06-Nov-2007.tar"
  1258. extracted_filename = "VOC2007test"
  1259. logging.info(" [============= VOC 2007 Test Set =============]")
  1260. else:
  1261. raise Exception("Please set the dataset aug to 2012, 2012test or 2007.")
  1262. # download dataset
  1263. if dataset != "2012test":
  1264. _platform = sys.platform
  1265. if folder_exists(os.path.join(path, extracted_filename)) is False:
  1266. logging.info("[VOC] {} is nonexistent in {}".format(extracted_filename, path))
  1267. maybe_download_and_extract(tar_filename, path, url, extract=True)
  1268. del_file(os.path.join(path, tar_filename))
  1269. if dataset == "2012":
  1270. if _platform == "win32":
  1271. os.system("mv {}\VOCdevkit\VOC2012 {}\VOC2012".format(path, path))
  1272. else:
  1273. os.system("mv {}/VOCdevkit/VOC2012 {}/VOC2012".format(path, path))
  1274. elif dataset == "2007":
  1275. if _platform == "win32":
  1276. os.system("mv {}\VOCdevkit\VOC2007 {}\VOC2007".format(path, path))
  1277. else:
  1278. os.system("mv {}/VOCdevkit/VOC2007 {}/VOC2007".format(path, path))
  1279. elif dataset == "2007test":
  1280. if _platform == "win32":
  1281. os.system("mv {}\VOCdevkit\VOC2007 {}\VOC2007test".format(path, path))
  1282. else:
  1283. os.system("mv {}/VOCdevkit/VOC2007 {}/VOC2007test".format(path, path))
  1284. del_folder(os.path.join(path, 'VOCdevkit'))
  1285. # object classes(labels) NOTE: YOU CAN CUSTOMIZE THIS LIST
  1286. classes = [
  1287. "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog",
  1288. "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"
  1289. ]
  1290. if contain_classes_in_person:
  1291. classes_in_person = ["head", "hand", "foot"]
  1292. else:
  1293. classes_in_person = []
  1294. classes += classes_in_person # use extra 3 classes for person
  1295. classes_dict = utils.list_string_to_dict(classes)
  1296. logging.info("[VOC] object classes {}".format(classes_dict))
  1297. # 1. image path list
  1298. # folder_imgs = path+"/"+extracted_filename+"/JPEGImages/"
  1299. folder_imgs = os.path.join(path, extracted_filename, "JPEGImages")
  1300. imgs_file_list = load_file_list(path=folder_imgs, regx='\\.jpg', printable=False)
  1301. logging.info("[VOC] {} images found".format(len(imgs_file_list)))
  1302. imgs_file_list.sort(
  1303. key=lambda s: int(s.replace('.', ' ').replace('_', '').split(' ')[-2])
  1304. ) # 2007_000027.jpg --> 2007000027
  1305. imgs_file_list = [os.path.join(folder_imgs, s) for s in imgs_file_list]
  1306. # logging.info('IM',imgs_file_list[0::3333], imgs_file_list[-1])
  1307. if dataset != "2012test":
  1308. # ======== 2. semantic segmentation maps path list
  1309. # folder_semseg = path+"/"+extracted_filename+"/SegmentationClass/"
  1310. folder_semseg = os.path.join(path, extracted_filename, "SegmentationClass")
  1311. imgs_semseg_file_list = load_file_list(path=folder_semseg, regx='\\.png', printable=False)
  1312. logging.info("[VOC] {} maps for semantic segmentation found".format(len(imgs_semseg_file_list)))
  1313. imgs_semseg_file_list.sort(
  1314. key=lambda s: int(s.replace('.', ' ').replace('_', '').split(' ')[-2])
  1315. ) # 2007_000032.png --> 2007000032
  1316. imgs_semseg_file_list = [os.path.join(folder_semseg, s) for s in imgs_semseg_file_list]
  1317. # logging.info('Semantic Seg IM',imgs_semseg_file_list[0::333], imgs_semseg_file_list[-1])
  1318. # ======== 3. instance segmentation maps path list
  1319. # folder_insseg = path+"/"+extracted_filename+"/SegmentationObject/"
  1320. folder_insseg = os.path.join(path, extracted_filename, "SegmentationObject")
  1321. imgs_insseg_file_list = load_file_list(path=folder_insseg, regx='\\.png', printable=False)
  1322. logging.info("[VOC] {} maps for instance segmentation found".format(len(imgs_semseg_file_list)))
  1323. imgs_insseg_file_list.sort(
  1324. key=lambda s: int(s.replace('.', ' ').replace('_', '').split(' ')[-2])
  1325. ) # 2007_000032.png --> 2007000032
  1326. imgs_insseg_file_list = [os.path.join(folder_insseg, s) for s in imgs_insseg_file_list]
  1327. # logging.info('Instance Seg IM',imgs_insseg_file_list[0::333], imgs_insseg_file_list[-1])
  1328. else:
  1329. imgs_semseg_file_list = []
  1330. imgs_insseg_file_list = []
  1331. # 4. annotations for bounding box and object class
  1332. # folder_ann = path+"/"+extracted_filename+"/Annotations/"
  1333. folder_ann = os.path.join(path, extracted_filename, "Annotations")
  1334. imgs_ann_file_list = load_file_list(path=folder_ann, regx='\\.xml', printable=False)
  1335. logging.info(
  1336. "[VOC] {} XML annotation files for bounding box and object class found".format(len(imgs_ann_file_list))
  1337. )
  1338. imgs_ann_file_list.sort(
  1339. key=lambda s: int(s.replace('.', ' ').replace('_', '').split(' ')[-2])
  1340. ) # 2007_000027.xml --> 2007000027
  1341. imgs_ann_file_list = [os.path.join(folder_ann, s) for s in imgs_ann_file_list]
  1342. # logging.info('ANN',imgs_ann_file_list[0::3333], imgs_ann_file_list[-1])
  1343. if dataset == "2012test": # remove unused images in JPEG folder
  1344. imgs_file_list_new = []
  1345. for ann in imgs_ann_file_list:
  1346. ann = os.path.split(ann)[-1].split('.')[0]
  1347. for im in imgs_file_list:
  1348. if ann in im:
  1349. imgs_file_list_new.append(im)
  1350. break
  1351. imgs_file_list = imgs_file_list_new
  1352. logging.info("[VOC] keep %d images" % len(imgs_file_list_new))
  1353. # parse XML annotations
  1354. def convert(size, box):
  1355. dw = 1. / size[0]
  1356. dh = 1. / size[1]
  1357. x = (box[0] + box[1]) / 2.0
  1358. y = (box[2] + box[3]) / 2.0
  1359. w = box[1] - box[0]
  1360. h = box[3] - box[2]
  1361. x = x * dw
  1362. w = w * dw
  1363. y = y * dh
  1364. h = h * dh
  1365. return x, y, w, h
  1366. def convert_annotation(file_name):
  1367. """Given VOC2012 XML Annotations, returns number of objects and info."""
  1368. in_file = open(file_name)
  1369. out_file = ""
  1370. tree = ET.parse(in_file)
  1371. root = tree.getroot()
  1372. size = root.find('size')
  1373. w = int(size.find('width').text)
  1374. h = int(size.find('height').text)
  1375. n_objs = 0
  1376. for obj in root.iter('object'):
  1377. if dataset != "2012test":
  1378. difficult = obj.find('difficult').text
  1379. cls = obj.find('name').text
  1380. if cls not in classes or int(difficult) == 1:
  1381. continue
  1382. else:
  1383. cls = obj.find('name').text
  1384. if cls not in classes:
  1385. continue
  1386. cls_id = classes.index(cls)
  1387. xmlbox = obj.find('bndbox')
  1388. b = (
  1389. float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
  1390. float(xmlbox.find('ymax').text)
  1391. )
  1392. bb = convert((w, h), b)
  1393. out_file += str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n'
  1394. n_objs += 1
  1395. if cls in "person":
  1396. for part in obj.iter('part'):
  1397. cls = part.find('name').text
  1398. if cls not in classes_in_person:
  1399. continue
  1400. cls_id = classes.index(cls)
  1401. xmlbox = part.find('bndbox')
  1402. b = (
  1403. float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text),
  1404. float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text)
  1405. )
  1406. bb = convert((w, h), b)
  1407. # out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
  1408. out_file += str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n'
  1409. n_objs += 1
  1410. in_file.close()
  1411. return n_objs, out_file
  1412. logging.info("[VOC] Parsing xml annotations files")
  1413. n_objs_list = []
  1414. objs_info_list = [] # Darknet Format list of string
  1415. objs_info_dicts = {}
  1416. for idx, ann_file in enumerate(imgs_ann_file_list):
  1417. n_objs, objs_info = convert_annotation(ann_file)
  1418. n_objs_list.append(n_objs)
  1419. objs_info_list.append(objs_info)
  1420. with tf.io.gfile.GFile(ann_file, 'r') as fid:
  1421. xml_str = fid.read()
  1422. xml = etree.fromstring(xml_str)
  1423. data = _recursive_parse_xml_to_dict(xml)['annotation']
  1424. objs_info_dicts.update({imgs_file_list[idx]: data})
  1425. return imgs_file_list, imgs_semseg_file_list, imgs_insseg_file_list, imgs_ann_file_list, classes, classes_in_person, classes_dict, n_objs_list, objs_info_list, objs_info_dicts
  1426. def load_mpii_pose_dataset(path='data', is_16_pos_only=False):
  1427. """Load MPII Human Pose Dataset.
  1428. Parameters
  1429. -----------
  1430. path : str
  1431. The path that the data is downloaded to.
  1432. is_16_pos_only : boolean
  1433. If True, only return the peoples contain 16 pose keypoints. (Usually be used for single person pose estimation)
  1434. Returns
  1435. ----------
  1436. img_train_list : list of str
  1437. The image directories of training data.
  1438. ann_train_list : list of dict
  1439. The annotations of training data.
  1440. img_test_list : list of str
  1441. The image directories of testing data.
  1442. ann_test_list : list of dict
  1443. The annotations of testing data.
  1444. Examples
  1445. --------
  1446. >>> import pprint
  1447. >>> import tensorlayer as tl
  1448. >>> img_train_list, ann_train_list, img_test_list, ann_test_list = tl.files.load_mpii_pose_dataset()
  1449. >>> image = tl.vis.read_image(img_train_list[0])
  1450. >>> tl.vis.draw_mpii_pose_to_image(image, ann_train_list[0], 'image.png')
  1451. >>> pprint.pprint(ann_train_list[0])
  1452. References
  1453. -----------
  1454. - `MPII Human Pose Dataset. CVPR 14 <http://human-pose.mpi-inf.mpg.de>`__
  1455. - `MPII Human Pose Models. CVPR 16 <http://pose.mpi-inf.mpg.de>`__
  1456. - `MPII Human Shape, Poselet Conditioned Pictorial Structures and etc <http://pose.mpi-inf.mpg.de/#related>`__
  1457. - `MPII Keyponts and ID <http://human-pose.mpi-inf.mpg.de/#download>`__
  1458. """
  1459. path = os.path.join(path, 'mpii_human_pose')
  1460. logging.info("Load or Download MPII Human Pose > {}".format(path))
  1461. # annotation
  1462. url = "http://datasets.d2.mpi-inf.mpg.de/andriluka14cvpr/"
  1463. tar_filename = "mpii_human_pose_v1_u12_2.zip"
  1464. extracted_filename = "mpii_human_pose_v1_u12_2"
  1465. if folder_exists(os.path.join(path, extracted_filename)) is False:
  1466. logging.info("[MPII] (annotation) {} is nonexistent in {}".format(extracted_filename, path))
  1467. maybe_download_and_extract(tar_filename, path, url, extract=True)
  1468. del_file(os.path.join(path, tar_filename))
  1469. # images
  1470. url = "http://datasets.d2.mpi-inf.mpg.de/andriluka14cvpr/"
  1471. tar_filename = "mpii_human_pose_v1.tar.gz"
  1472. extracted_filename2 = "images"
  1473. if folder_exists(os.path.join(path, extracted_filename2)) is False:
  1474. logging.info("[MPII] (images) {} is nonexistent in {}".format(extracted_filename, path))
  1475. maybe_download_and_extract(tar_filename, path, url, extract=True)
  1476. del_file(os.path.join(path, tar_filename))
  1477. # parse annotation, format see http://human-pose.mpi-inf.mpg.de/#download
  1478. logging.info("reading annotations from mat file ...")
  1479. # mat = sio.loadmat(os.path.join(path, extracted_filename, "mpii_human_pose_v1_u12_1.mat"))
  1480. # def fix_wrong_joints(joint): # https://github.com/mitmul/deeppose/blob/master/datasets/mpii_dataset.py
  1481. # if '12' in joint and '13' in joint and '2' in joint and '3' in joint:
  1482. # if ((joint['12'][0] < joint['13'][0]) and
  1483. # (joint['3'][0] < joint['2'][0])):
  1484. # joint['2'], joint['3'] = joint['3'], joint['2']
  1485. # if ((joint['12'][0] > joint['13'][0]) and
  1486. # (joint['3'][0] > joint['2'][0])):
  1487. # joint['2'], joint['3'] = joint['3'], joint['2']
  1488. # return joint
  1489. ann_train_list = []
  1490. ann_test_list = []
  1491. img_train_list = []
  1492. img_test_list = []
  1493. def save_joints():
  1494. # joint_data_fn = os.path.join(path, 'data.json')
  1495. # fp = open(joint_data_fn, 'w')
  1496. mat = sio.loadmat(os.path.join(path, extracted_filename, "mpii_human_pose_v1_u12_1.mat"))
  1497. for _, (anno, train_flag) in enumerate( # all images
  1498. zip(mat['RELEASE']['annolist'][0, 0][0], mat['RELEASE']['img_train'][0, 0][0])):
  1499. img_fn = anno['image']['name'][0, 0][0]
  1500. train_flag = int(train_flag)
  1501. # print(i, img_fn, train_flag) # DEBUG print all images
  1502. if train_flag:
  1503. img_train_list.append(img_fn)
  1504. ann_train_list.append([])
  1505. else:
  1506. img_test_list.append(img_fn)
  1507. ann_test_list.append([])
  1508. head_rect = []
  1509. if 'x1' in str(anno['annorect'].dtype):
  1510. head_rect = zip(
  1511. [x1[0, 0] for x1 in anno['annorect']['x1'][0]], [y1[0, 0] for y1 in anno['annorect']['y1'][0]],
  1512. [x2[0, 0] for x2 in anno['annorect']['x2'][0]], [y2[0, 0] for y2 in anno['annorect']['y2'][0]]
  1513. )
  1514. else:
  1515. head_rect = [] # TODO
  1516. if 'annopoints' in str(anno['annorect'].dtype):
  1517. annopoints = anno['annorect']['annopoints'][0]
  1518. head_x1s = anno['annorect']['x1'][0]
  1519. head_y1s = anno['annorect']['y1'][0]
  1520. head_x2s = anno['annorect']['x2'][0]
  1521. head_y2s = anno['annorect']['y2'][0]
  1522. for annopoint, head_x1, head_y1, head_x2, head_y2 in zip(annopoints, head_x1s, head_y1s, head_x2s,
  1523. head_y2s):
  1524. # if annopoint != []:
  1525. # if len(annopoint) != 0:
  1526. if annopoint.size:
  1527. head_rect = [
  1528. float(head_x1[0, 0]),
  1529. float(head_y1[0, 0]),
  1530. float(head_x2[0, 0]),
  1531. float(head_y2[0, 0])
  1532. ]
  1533. # joint coordinates
  1534. annopoint = annopoint['point'][0, 0]
  1535. j_id = [str(j_i[0, 0]) for j_i in annopoint['id'][0]]
  1536. x = [x[0, 0] for x in annopoint['x'][0]]
  1537. y = [y[0, 0] for y in annopoint['y'][0]]
  1538. joint_pos = {}
  1539. for _j_id, (_x, _y) in zip(j_id, zip(x, y)):
  1540. joint_pos[int(_j_id)] = [float(_x), float(_y)]
  1541. # joint_pos = fix_wrong_joints(joint_pos)
  1542. # visibility list
  1543. if 'is_visible' in str(annopoint.dtype):
  1544. vis = [v[0] if v.size > 0 else [0] for v in annopoint['is_visible'][0]]
  1545. vis = dict([(k, int(v[0])) if len(v) > 0 else v for k, v in zip(j_id, vis)])
  1546. else:
  1547. vis = None
  1548. # if len(joint_pos) == 16:
  1549. if ((is_16_pos_only ==True) and (len(joint_pos) == 16)) or (is_16_pos_only == False):
  1550. # only use image with 16 key points / or use all
  1551. data = {
  1552. 'filename': img_fn,
  1553. 'train': train_flag,
  1554. 'head_rect': head_rect,
  1555. 'is_visible': vis,
  1556. 'joint_pos': joint_pos
  1557. }
  1558. # print(json.dumps(data), file=fp) # py3
  1559. if train_flag:
  1560. ann_train_list[-1].append(data)
  1561. else:
  1562. ann_test_list[-1].append(data)
  1563. # def write_line(datum, fp):
  1564. # joints = sorted([[int(k), v] for k, v in datum['joint_pos'].items()])
  1565. # joints = np.array([j for i, j in joints]).flatten()
  1566. #
  1567. # out = [datum['filename']]
  1568. # out.extend(joints)
  1569. # out = [str(o) for o in out]
  1570. # out = ','.join(out)
  1571. #
  1572. # print(out, file=fp)
  1573. # def split_train_test():
  1574. # # fp_test = open('data/mpii/test_joints.csv', 'w')
  1575. # fp_test = open(os.path.join(path, 'test_joints.csv'), 'w')
  1576. # # fp_train = open('data/mpii/train_joints.csv', 'w')
  1577. # fp_train = open(os.path.join(path, 'train_joints.csv'), 'w')
  1578. # # all_data = open('data/mpii/data.json').readlines()
  1579. # all_data = open(os.path.join(path, 'data.json')).readlines()
  1580. # N = len(all_data)
  1581. # N_test = int(N * 0.1)
  1582. # N_train = N - N_test
  1583. #
  1584. # print('N:{}'.format(N))
  1585. # print('N_train:{}'.format(N_train))
  1586. # print('N_test:{}'.format(N_test))
  1587. #
  1588. # np.random.seed(1701)
  1589. # perm = np.random.permutation(N)
  1590. # test_indices = perm[:N_test]
  1591. # train_indices = perm[N_test:]
  1592. #
  1593. # print('train_indices:{}'.format(len(train_indices)))
  1594. # print('test_indices:{}'.format(len(test_indices)))
  1595. #
  1596. # for i in train_indices:
  1597. # datum = json.loads(all_data[i].strip())
  1598. # write_line(datum, fp_train)
  1599. #
  1600. # for i in test_indices:
  1601. # datum = json.loads(all_data[i].strip())
  1602. # write_line(datum, fp_test)
  1603. save_joints()
  1604. # split_train_test() #
  1605. # read images dir
  1606. logging.info("reading images list ...")
  1607. img_dir = os.path.join(path, extracted_filename2)
  1608. _img_list = load_file_list(path=os.path.join(path, extracted_filename2), regx='\\.jpg', printable=False)
  1609. # ann_list = json.load(open(os.path.join(path, 'data.json')))
  1610. for i, im in enumerate(img_train_list):
  1611. if im not in _img_list:
  1612. print('missing training image {} in {} (remove from img(ann)_train_list)'.format(im, img_dir))
  1613. # img_train_list.remove(im)
  1614. del img_train_list[i]
  1615. del ann_train_list[i]
  1616. for i, im in enumerate(img_test_list):
  1617. if im not in _img_list:
  1618. print('missing testing image {} in {} (remove from img(ann)_test_list)'.format(im, img_dir))
  1619. # img_test_list.remove(im)
  1620. del img_train_list[i]
  1621. del ann_train_list[i]
  1622. # check annotation and images
  1623. n_train_images = len(img_train_list)
  1624. n_test_images = len(img_test_list)
  1625. n_images = n_train_images + n_test_images
  1626. logging.info("n_images: {} n_train_images: {} n_test_images: {}".format(n_images, n_train_images, n_test_images))
  1627. n_train_ann = len(ann_train_list)
  1628. n_test_ann = len(ann_test_list)
  1629. n_ann = n_train_ann + n_test_ann
  1630. logging.info("n_ann: {} n_train_ann: {} n_test_ann: {}".format(n_ann, n_train_ann, n_test_ann))
  1631. n_train_people = len(sum(ann_train_list, []))
  1632. n_test_people = len(sum(ann_test_list, []))
  1633. n_people = n_train_people + n_test_people
  1634. logging.info("n_people: {} n_train_people: {} n_test_people: {}".format(n_people, n_train_people, n_test_people))
  1635. # add path to all image file name
  1636. for i, value in enumerate(img_train_list):
  1637. img_train_list[i] = os.path.join(img_dir, value)
  1638. for i, value in enumerate(img_test_list):
  1639. img_test_list[i] = os.path.join(img_dir, value)
  1640. return img_train_list, ann_train_list, img_test_list, ann_test_list
  1641. def save_npz(save_list=None, name='model.npz'):
  1642. """Input parameters and the file name, save parameters into .npz file. Use tl.utils.load_npz() to restore.
  1643. Parameters
  1644. ----------
  1645. save_list : list of tensor
  1646. A list of parameters (tensor) to be saved.
  1647. name : str
  1648. The name of the `.npz` file.
  1649. Examples
  1650. --------
  1651. Save model to npz
  1652. >>> tl.files.save_npz(network.all_weights, name='model.npz')
  1653. Load model from npz (Method 1)
  1654. >>> load_params = tl.files.load_npz(name='model.npz')
  1655. >>> tl.files.assign_weights(load_params, network)
  1656. Load model from npz (Method 2)
  1657. >>> tl.files.load_and_assign_npz(name='model.npz', network=network)
  1658. References
  1659. ----------
  1660. `Saving dictionary using numpy <http://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez>`__
  1661. """
  1662. logging.info("[*] Saving TL weights into %s" % name)
  1663. if save_list is None:
  1664. save_list = []
  1665. if tl.BACKEND == 'tensorflow':
  1666. save_list_var = tf_variables_to_numpy(save_list)
  1667. elif tl.BACKEND == 'mindspore':
  1668. save_list_var = ms_variables_to_numpy(save_list)
  1669. elif tl.BACKEND == 'paddle':
  1670. save_list_var = pd_variables_to_numpy(save_list)
  1671. else:
  1672. raise NotImplementedError("This backend is not supported")
  1673. # print(name, save_list_var)
  1674. np.savez(name, params=save_list_var)
  1675. save_list_var = None
  1676. del save_list_var
  1677. logging.info("[*] Saved")
  1678. def load_npz(path='', name='model.npz'):
  1679. """Load the parameters of a Model saved by tl.files.save_npz().
  1680. Parameters
  1681. ----------
  1682. path : str
  1683. Folder path to `.npz` file.
  1684. name : str
  1685. The name of the `.npz` file.
  1686. Returns
  1687. --------
  1688. list of array
  1689. A list of parameters in order.
  1690. Examples
  1691. --------
  1692. - See ``tl.files.save_npz``
  1693. References
  1694. ----------
  1695. - `Saving dictionary using numpy <http://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez>`__
  1696. """
  1697. d = np.load(os.path.join(path, name), allow_pickle=True)
  1698. return d['params']
  1699. def assign_params(**kwargs):
  1700. raise Exception("please change assign_params --> assign_weights")
  1701. def assign_weights(weights, network):
  1702. """Assign the given parameters to the TensorLayer network.
  1703. Parameters
  1704. ----------
  1705. weights : list of array
  1706. A list of model weights (array) in order.
  1707. network : :class:`Layer`
  1708. The network to be assigned.
  1709. Returns
  1710. --------
  1711. 1) list of operations if in graph mode
  1712. A list of tf ops in order that assign weights. Support sess.run(ops) manually.
  1713. 2) list of tf variables if in eager mode
  1714. A list of tf variables (assigned weights) in order.
  1715. Examples
  1716. --------
  1717. References
  1718. ----------
  1719. - `Assign value to a TensorFlow variable <http://stackoverflow.com/questions/34220532/how-to-assign-value-to-a-tensorflow-variable>`__
  1720. """
  1721. ops = []
  1722. if tl.BACKEND == 'tensorflow':
  1723. for idx, param in enumerate(weights):
  1724. ops.append(network.all_weights[idx].assign(param))
  1725. elif tl.BACKEND == 'mindspore':
  1726. class Assign_net(Cell):
  1727. def __init__(self, y):
  1728. super(Assign_net, self).__init__()
  1729. self.y = y
  1730. def construct(self, x):
  1731. Assign()(self.y, x)
  1732. for idx, param in enumerate(weights):
  1733. assign_param = Tensor(param, dtype=ms.float32)
  1734. # net = Assign_net(network.all_weights[idx])
  1735. # net(assign_param)
  1736. Assign()(network.all_weights[idx], assign_param)
  1737. elif tl.BACKEND == 'paddle':
  1738. for idx, param in enumerate(weights):
  1739. assign_pd_variable(network.all_weights[idx], param)
  1740. else:
  1741. raise NotImplementedError ("This backend is not supported")
  1742. return ops
  1743. def load_and_assign_npz(name=None, network=None):
  1744. """Load model from npz and assign to a network.
  1745. Parameters
  1746. -------------
  1747. name : str
  1748. The name of the `.npz` file.
  1749. network : :class:`Model`
  1750. The network to be assigned.
  1751. Examples
  1752. --------
  1753. - See ``tl.files.save_npz``
  1754. """
  1755. if network is None:
  1756. raise ValueError("network is None.")
  1757. if not os.path.exists(name):
  1758. logging.error("file {} doesn't exist.".format(name))
  1759. return False
  1760. else:
  1761. weights = load_npz(name=name)
  1762. assign_weights(weights, network)
  1763. logging.info("[*] Load {} SUCCESS!".format(name))
  1764. def save_npz_dict(save_list=None, name='model.npz'):
  1765. """Input parameters and the file name, save parameters as a dictionary into .npz file.
  1766. Use ``tl.files.load_and_assign_npz_dict()`` to restore.
  1767. Parameters
  1768. ----------
  1769. save_list : list of parameters
  1770. A list of parameters (tensor) to be saved.
  1771. name : str
  1772. The name of the `.npz` file.
  1773. """
  1774. if save_list is None:
  1775. save_list = []
  1776. save_list_names = [tensor.name for tensor in save_list]
  1777. if tl.BACKEND == 'tensorflow':
  1778. save_list_var = tf_variables_to_numpy(save_list)
  1779. elif tl.BACKEND == 'mindspore':
  1780. save_list_var = ms_variables_to_numpy(save_list)
  1781. elif tl.BACKEND == 'paddle':
  1782. save_list_var = pd_variables_to_numpy(save_list)
  1783. else:
  1784. raise NotImplementedError('Not implemented')
  1785. save_var_dict = {save_list_names[idx]: val for idx, val in enumerate(save_list_var)}
  1786. np.savez(name, **save_var_dict)
  1787. save_list_var = None
  1788. save_var_dict = None
  1789. del save_list_var
  1790. del save_var_dict
  1791. logging.info("[*] Model saved in npz_dict %s" % name)
  1792. def load_and_assign_npz_dict(name='model.npz', network=None, skip=False):
  1793. """Restore the parameters saved by ``tl.files.save_npz_dict()``.
  1794. Parameters
  1795. -------------
  1796. name : str
  1797. The name of the `.npz` file.
  1798. network : :class:`Model`
  1799. The network to be assigned.
  1800. skip : boolean
  1801. If 'skip' == True, loaded weights whose name is not found in network's weights will be skipped.
  1802. If 'skip' is False, error will be raised when mismatch is found. Default False.
  1803. """
  1804. if not os.path.exists(name):
  1805. logging.error("file {} doesn't exist.".format(name))
  1806. return False
  1807. weights = np.load(name, allow_pickle=True)
  1808. if len(weights.keys()) != len(set(weights.keys())):
  1809. raise Exception("Duplication in model npz_dict %s" % name)
  1810. net_weights_name = [w.name for w in network.all_weights]
  1811. for key in weights.keys():
  1812. if key not in net_weights_name:
  1813. if skip:
  1814. logging.warning("Weights named '%s' not found in network. Skip it." % key)
  1815. else:
  1816. raise RuntimeError(
  1817. "Weights named '%s' not found in network. Hint: set argument skip=Ture "
  1818. "if you want to skip redundant or mismatch weights." % key
  1819. )
  1820. else:
  1821. if tl.BACKEND == 'tensorflow':
  1822. assign_tf_variable(network.all_weights[net_weights_name.index(key)], weights[key])
  1823. elif tl.BACKEND == 'mindspore':
  1824. assign_param = Tensor(weights[key], dtype=ms.float32)
  1825. assign_ms_variable(network.all_weights[net_weights_name.index(key)], assign_param)
  1826. elif tl.BACKEND == 'paddle':
  1827. assign_pd_variable(network.all_weights[net_weights_name.index(key)], weights[key])
  1828. else:
  1829. raise NotImplementedError('Not implemented')
  1830. logging.info("[*] Model restored from npz_dict %s" % name)
  1831. def save_ckpt(mode_name='model.ckpt', save_dir='checkpoint', var_list=None, global_step=None, printable=False):
  1832. """Save parameters into `ckpt` file.
  1833. Parameters
  1834. ------------
  1835. mode_name : str
  1836. The name of the model, default is ``model.ckpt``.
  1837. save_dir : str
  1838. The path / file directory to the `ckpt`, default is ``checkpoint``.
  1839. var_list : list of tensor
  1840. The parameters / variables (tensor) to be saved. If empty, save all global variables (default).
  1841. global_step : int or None
  1842. Step number.
  1843. printable : boolean
  1844. Whether to print all parameters information.
  1845. See Also
  1846. --------
  1847. load_ckpt
  1848. """
  1849. if var_list is None:
  1850. if sess is None:
  1851. # FIXME: not sure whether global variables can be accessed in eager mode
  1852. raise ValueError(
  1853. "If var_list is None, sess must be specified. "
  1854. "In eager mode, can not access global variables easily. "
  1855. )
  1856. var_list = []
  1857. ckpt_file = os.path.join(save_dir, mode_name)
  1858. if var_list == []:
  1859. var_list = tf.global_variables()
  1860. logging.info("[*] save %s n_weights: %d" % (ckpt_file, len(var_list)))
  1861. if printable:
  1862. for idx, v in enumerate(var_list):
  1863. logging.info(" param {:3}: {:15} {}".format(idx, v.name, str(v.get_shape())))
  1864. if sess:
  1865. # graph mode
  1866. saver = tf.train.Saver(var_list)
  1867. saver.save(sess, ckpt_file, global_step=global_step)
  1868. else:
  1869. # eager mode
  1870. # saver = tfes.Saver(var_list)
  1871. # saver.save(ckpt_file, global_step=global_step)
  1872. # TODO: tf2.0 not stable, cannot import tensorflow.contrib.eager.python.saver
  1873. pass
  1874. def load_ckpt(sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, is_latest=True, printable=False):
  1875. """Load parameters from `ckpt` file.
  1876. Parameters
  1877. ------------
  1878. sess : Session
  1879. TensorFlow Session.
  1880. mode_name : str
  1881. The name of the model, default is ``model.ckpt``.
  1882. save_dir : str
  1883. The path / file directory to the `ckpt`, default is ``checkpoint``.
  1884. var_list : list of tensor
  1885. The parameters / variables (tensor) to be saved. If empty, save all global variables (default).
  1886. is_latest : boolean
  1887. Whether to load the latest `ckpt`, if False, load the `ckpt` with the name of ```mode_name``.
  1888. printable : boolean
  1889. Whether to print all parameters information.
  1890. Examples
  1891. ----------
  1892. - Save all global parameters.
  1893. >>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', save_dir='model', printable=True)
  1894. - Save specific parameters.
  1895. >>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', printable=True)
  1896. - Load latest ckpt.
  1897. >>> tl.files.load_ckpt(sess=sess, var_list=net.all_params, save_dir='model', printable=True)
  1898. - Load specific ckpt.
  1899. >>> tl.files.load_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', is_latest=False, printable=True)
  1900. """
  1901. # if sess is None:
  1902. # raise ValueError("session is None.")
  1903. if var_list is None:
  1904. if sess is None:
  1905. # FIXME: not sure whether global variables can be accessed in eager mode
  1906. raise ValueError(
  1907. "If var_list is None, sess must be specified. "
  1908. "In eager mode, can not access global variables easily. "
  1909. )
  1910. var_list = []
  1911. if is_latest:
  1912. ckpt_file = tf.train.latest_checkpoint(save_dir)
  1913. else:
  1914. ckpt_file = os.path.join(save_dir, mode_name)
  1915. if not var_list:
  1916. var_list = tf.global_variables()
  1917. logging.info("[*] load %s n_weights: %d" % (ckpt_file, len(var_list)))
  1918. if printable:
  1919. for idx, v in enumerate(var_list):
  1920. logging.info(" weights {:3}: {:15} {}".format(idx, v.name, str(v.get_shape())))
  1921. try:
  1922. if sess:
  1923. # graph mode
  1924. saver = tf.train.Saver(var_list)
  1925. saver.restore(sess, ckpt_file)
  1926. else:
  1927. # eager mode
  1928. # saver = tfes.Saver(var_list)
  1929. # saver.restore(ckpt_file)
  1930. # TODO: tf2.0 not stable, cannot import tensorflow.contrib.eager.python.saver
  1931. pass
  1932. except Exception as e:
  1933. logging.info(e)
  1934. logging.info("[*] load ckpt fail ...")
  1935. def save_any_to_npy(save_dict=None, name='file.npy'):
  1936. """Save variables to `.npy` file.
  1937. Parameters
  1938. ------------
  1939. save_dict : directory
  1940. The variables to be saved.
  1941. name : str
  1942. File name.
  1943. Examples
  1944. ---------
  1945. >>> tl.files.save_any_to_npy(save_dict={'data': ['a','b']}, name='test.npy')
  1946. >>> data = tl.files.load_npy_to_any(name='test.npy')
  1947. >>> print(data)
  1948. {'data': ['a','b']}
  1949. """
  1950. if save_dict is None:
  1951. save_dict = {}
  1952. np.save(name, save_dict)
  1953. def load_npy_to_any(path='', name='file.npy'):
  1954. """Load `.npy` file.
  1955. Parameters
  1956. ------------
  1957. path : str
  1958. Path to the file (optional).
  1959. name : str
  1960. File name.
  1961. Examples
  1962. ---------
  1963. - see tl.files.save_any_to_npy()
  1964. """
  1965. file_path = os.path.join(path, name)
  1966. try:
  1967. return np.load(file_path, allow_pickle=True).item()
  1968. except Exception:
  1969. return np.load(file_path, allow_pickle=True)
  1970. raise Exception("[!] Fail to load %s" % file_path)
  1971. def file_exists(filepath):
  1972. """Check whether a file exists by given file path."""
  1973. return os.path.isfile(filepath)
  1974. def folder_exists(folderpath):
  1975. """Check whether a folder exists by given folder path."""
  1976. return os.path.isdir(folderpath)
  1977. def del_file(filepath):
  1978. """Delete a file by given file path."""
  1979. os.remove(filepath)
  1980. def del_folder(folderpath):
  1981. """Delete a folder by given folder path."""
  1982. shutil.rmtree(folderpath)
  1983. def read_file(filepath):
  1984. """Read a file and return a string.
  1985. Examples
  1986. ---------
  1987. >>> data = tl.files.read_file('data.txt')
  1988. """
  1989. with open(filepath, 'r') as afile:
  1990. return afile.read()
  1991. def load_file_list(path=None, regx='\.jpg', printable=True, keep_prefix=False):
  1992. r"""Return a file list in a folder by given a path and regular expression.
  1993. Parameters
  1994. ----------
  1995. path : str or None
  1996. A folder path, if `None`, use the current directory.
  1997. regx : str
  1998. The regx of file name.
  1999. printable : boolean
  2000. Whether to print the files infomation.
  2001. keep_prefix : boolean
  2002. Whether to keep path in the file name.
  2003. Examples
  2004. ----------
  2005. >>> file_list = tl.files.load_file_list(path=None, regx='w1pre_[0-9]+\.(npz)')
  2006. """
  2007. if path is None:
  2008. path = os.getcwd()
  2009. file_list = os.listdir(path)
  2010. return_list = []
  2011. for _, f in enumerate(file_list):
  2012. if re.search(regx, f):
  2013. return_list.append(f)
  2014. # return_list.sort()
  2015. if keep_prefix:
  2016. for i, f in enumerate(return_list):
  2017. return_list[i] = os.path.join(path, f)
  2018. if printable:
  2019. logging.info('Match file list = %s' % return_list)
  2020. logging.info('Number of files = %d' % len(return_list))
  2021. return return_list
  2022. def load_folder_list(path=""):
  2023. """Return a folder list in a folder by given a folder path.
  2024. Parameters
  2025. ----------
  2026. path : str
  2027. A folder path.
  2028. """
  2029. return [os.path.join(path, o) for o in os.listdir(path) if os.path.isdir(os.path.join(path, o))]
  2030. def exists_or_mkdir(path, verbose=True):
  2031. """Check a folder by given name, if not exist, create the folder and return False,
  2032. if directory exists, return True.
  2033. Parameters
  2034. ----------
  2035. path : str
  2036. A folder path.
  2037. verbose : boolean
  2038. If True (default), prints results.
  2039. Returns
  2040. --------
  2041. boolean
  2042. True if folder already exist, otherwise, returns False and create the folder.
  2043. Examples
  2044. --------
  2045. >>> tl.files.exists_or_mkdir("checkpoints/train")
  2046. """
  2047. if not os.path.exists(path):
  2048. if verbose:
  2049. logging.info("[*] creates %s ..." % path)
  2050. os.makedirs(path)
  2051. return False
  2052. else:
  2053. if verbose:
  2054. logging.info("[!] %s exists ..." % path)
  2055. return True
  2056. def maybe_download_and_extract(filename, working_directory, url_source, extract=False, expected_bytes=None):
  2057. """Checks if file exists in working_directory otherwise tries to dowload the file,
  2058. and optionally also tries to extract the file if format is ".zip" or ".tar"
  2059. Parameters
  2060. -----------
  2061. filename : str
  2062. The name of the (to be) dowloaded file.
  2063. working_directory : str
  2064. A folder path to search for the file in and dowload the file to
  2065. url : str
  2066. The URL to download the file from
  2067. extract : boolean
  2068. If True, tries to uncompress the dowloaded file is ".tar.gz/.tar.bz2" or ".zip" file, default is False.
  2069. expected_bytes : int or None
  2070. If set tries to verify that the downloaded file is of the specified size, otherwise raises an Exception, defaults is None which corresponds to no check being performed.
  2071. Returns
  2072. ----------
  2073. str
  2074. File path of the dowloaded (uncompressed) file.
  2075. Examples
  2076. --------
  2077. >>> down_file = tl.files.maybe_download_and_extract(filename='train-images-idx3-ubyte.gz',
  2078. ... working_directory='data/',
  2079. ... url_source='http://yann.lecun.com/exdb/mnist/')
  2080. >>> tl.files.maybe_download_and_extract(filename='ADEChallengeData2016.zip',
  2081. ... working_directory='data/',
  2082. ... url_source='http://sceneparsing.csail.mit.edu/data/',
  2083. ... extract=True)
  2084. """
  2085. # We first define a download function, supporting both Python 2 and 3.
  2086. def _download(filename, working_directory, url_source):
  2087. progress_bar = progressbar.ProgressBar()
  2088. def _dlProgress(count, blockSize, totalSize, pbar=progress_bar):
  2089. if (totalSize != 0):
  2090. if not pbar.max_value:
  2091. totalBlocks = math.ceil(float(totalSize) / float(blockSize))
  2092. pbar.max_value = int(totalBlocks)
  2093. pbar.update(count, force=True)
  2094. filepath = os.path.join(working_directory, filename)
  2095. logging.info('Downloading %s...\n' % filename)
  2096. urlretrieve(url_source + filename, filepath, reporthook=_dlProgress)
  2097. exists_or_mkdir(working_directory, verbose=False)
  2098. filepath = os.path.join(working_directory, filename)
  2099. if not os.path.exists(filepath):
  2100. _download(filename, working_directory, url_source)
  2101. statinfo = os.stat(filepath)
  2102. logging.info('Succesfully downloaded %s %s bytes.' % (filename, statinfo.st_size)) # , 'bytes.')
  2103. if (not (expected_bytes is None) and (expected_bytes != statinfo.st_size)):
  2104. raise Exception('Failed to verify ' + filename + '. Can you get to it with a browser?')
  2105. if (extract):
  2106. if tarfile.is_tarfile(filepath):
  2107. logging.info('Trying to extract tar file')
  2108. tarfile.open(filepath, 'r').extractall(working_directory)
  2109. logging.info('... Success!')
  2110. elif zipfile.is_zipfile(filepath):
  2111. logging.info('Trying to extract zip file')
  2112. with zipfile.ZipFile(filepath) as zf:
  2113. zf.extractall(working_directory)
  2114. logging.info('... Success!')
  2115. else:
  2116. logging.info("Unknown compression_format only .tar.gz/.tar.bz2/.tar and .zip supported")
  2117. return filepath
  2118. def natural_keys(text):
  2119. """Sort list of string with number in human order.
  2120. Examples
  2121. ----------
  2122. >>> l = ['im1.jpg', 'im31.jpg', 'im11.jpg', 'im21.jpg', 'im03.jpg', 'im05.jpg']
  2123. >>> l.sort(key=tl.files.natural_keys)
  2124. ['im1.jpg', 'im03.jpg', 'im05', 'im11.jpg', 'im21.jpg', 'im31.jpg']
  2125. >>> l.sort() # that is what we dont want
  2126. ['im03.jpg', 'im05', 'im1.jpg', 'im11.jpg', 'im21.jpg', 'im31.jpg']
  2127. References
  2128. ----------
  2129. - `link <http://nedbatchelder.com/blog/200712/human_sorting.html>`__
  2130. """
  2131. # - alist.sort(key=natural_keys) sorts in human order
  2132. # http://nedbatchelder.com/blog/200712/human_sorting.html
  2133. # (See Toothy's implementation in the comments)
  2134. def atoi(text):
  2135. return int(text) if text.isdigit() else text
  2136. return [atoi(c) for c in re.split('(\d+)', text)]
  2137. # Visualizing npz files
  2138. def npz_to_W_pdf(path=None, regx='w1pre_[0-9]+\.(npz)'):
  2139. r"""Convert the first weight matrix of `.npz` file to `.pdf` by using `tl.visualize.W()`.
  2140. Parameters
  2141. ----------
  2142. path : str
  2143. A folder path to `npz` files.
  2144. regx : str
  2145. Regx for the file name.
  2146. Examples
  2147. ---------
  2148. Convert the first weight matrix of w1_pre...npz file to w1_pre...pdf.
  2149. >>> tl.files.npz_to_W_pdf(path='/Users/.../npz_file/', regx='w1pre_[0-9]+\.(npz)')
  2150. """
  2151. file_list = load_file_list(path=path, regx=regx)
  2152. for f in file_list:
  2153. W = load_npz(path, f)[0]
  2154. logging.info("%s --> %s" % (f, f.split('.')[0] + '.pdf'))
  2155. visualize.draw_weights(W, second=10, saveable=True, name=f.split('.')[0], fig_idx=2012)
  2156. def tf_variables_to_numpy(variables):
  2157. """Convert TF tensor or a list of tensors into a list of numpy array"""
  2158. if not isinstance(variables, list):
  2159. var_list = [variables]
  2160. else:
  2161. var_list = variables
  2162. results = [v.numpy() for v in var_list]
  2163. return results
  2164. def ms_variables_to_numpy(variables):
  2165. """Convert MS tensor or list of tensors into a list of numpy array"""
  2166. if not isinstance(variables, list):
  2167. var_list = [variables]
  2168. else:
  2169. var_list = variables
  2170. results = [v.data.asnumpy() for v in var_list]
  2171. return results
  2172. def pd_variables_to_numpy(variables):
  2173. if not isinstance(variables, list):
  2174. var_list = [variables]
  2175. else:
  2176. var_list = variables
  2177. results = [v.numpy() for v in var_list]
  2178. return results
  2179. def assign_tf_variable(variable, value):
  2180. """Assign value to a TF variable"""
  2181. variable.assign(value)
  2182. def assign_ms_variable(variable, value):
  2183. class Assign_net(Cell):
  2184. def __init__(self, y):
  2185. super(Assign_net, self).__init__()
  2186. self.y = y
  2187. def construct(self, x):
  2188. Assign()(self.y, x)
  2189. # net = Assign_net(variable)
  2190. # net(value)
  2191. Assign()(variable, value)
  2192. def assign_pd_variable(variable, value):
  2193. pd.assign(value, variable)
  2194. def _save_weights_to_hdf5_group(f, layers):
  2195. """
  2196. Save layer/model weights into hdf5 group recursively.
  2197. Parameters
  2198. ----------
  2199. f: hdf5 group
  2200. A hdf5 group created by h5py.File() or create_group().
  2201. layers: list
  2202. A list of layers to save weights.
  2203. """
  2204. f.attrs['layer_names'] = [layer.name.encode('utf8') for layer in layers]
  2205. for layer in layers:
  2206. g = f.create_group(layer.name)
  2207. if isinstance(layer, tl.models.Model):
  2208. _save_weights_to_hdf5_group(g, layer.all_layers)
  2209. elif isinstance(layer, tl.layers.ModelLayer):
  2210. _save_weights_to_hdf5_group(g, layer.model.all_layers)
  2211. elif isinstance(layer, tl.layers.LayerList):
  2212. _save_weights_to_hdf5_group(g, layer.layers)
  2213. elif isinstance(layer, tl.layers.Layer):
  2214. if layer.all_weights is not None:
  2215. weight_values = tf_variables_to_numpy(layer.all_weights)
  2216. weight_names = [w.name.encode('utf8') for w in layer.all_weights]
  2217. else:
  2218. weight_values = []
  2219. weight_names = []
  2220. g.attrs['weight_names'] = weight_names
  2221. for name, val in zip(weight_names, weight_values):
  2222. val_dataset = g.create_dataset(name, val.shape, dtype=val.dtype)
  2223. if not val.shape:
  2224. # scalar
  2225. val_dataset[()] = val
  2226. else:
  2227. val_dataset[:] = val
  2228. else:
  2229. raise Exception("Only layer or model can be saved into hdf5.")
  2230. def _load_weights_from_hdf5_group_in_order(f, layers):
  2231. """
  2232. Load layer weights from a hdf5 group sequentially.
  2233. Parameters
  2234. ----------
  2235. f: hdf5 group
  2236. A hdf5 group created by h5py.File() or create_group().
  2237. layers: list
  2238. A list of layers to load weights.
  2239. """
  2240. layer_names = [n.decode('utf8') for n in f.attrs["layer_names"]]
  2241. for idx, name in enumerate(layer_names):
  2242. g = f[name]
  2243. layer = layers[idx]
  2244. if isinstance(layer, tl.models.Model):
  2245. _load_weights_from_hdf5_group_in_order(g, layer.all_layers)
  2246. elif isinstance(layer, tl.layers.ModelLayer):
  2247. _load_weights_from_hdf5_group_in_order(g, layer.model.all_layers)
  2248. elif isinstance(layer, tl.layers.LayerList):
  2249. _load_weights_from_hdf5_group_in_order(g, layer.layers)
  2250. elif isinstance(layer, tl.layers.Layer):
  2251. weight_names = [n.decode('utf8') for n in g.attrs['weight_names']]
  2252. for iid, w_name in enumerate(weight_names):
  2253. assign_tf_variable(layer.all_weights[iid], np.asarray(g[w_name]))
  2254. else:
  2255. raise Exception("Only layer or model can be saved into hdf5.")
  2256. if idx == len(layers) - 1:
  2257. break
  2258. def _load_weights_from_hdf5_group(f, layers, skip=False):
  2259. """
  2260. Load layer weights from a hdf5 group by layer name.
  2261. Parameters
  2262. ----------
  2263. f: hdf5 group
  2264. A hdf5 group created by h5py.File() or create_group().
  2265. layers: list
  2266. A list of layers to load weights.
  2267. skip : boolean
  2268. If 'skip' == True, loaded layer whose name is not found in 'layers' will be skipped. If 'skip' is False,
  2269. error will be raised when mismatch is found. Default False.
  2270. """
  2271. layer_names = [n.decode('utf8') for n in f.attrs["layer_names"]]
  2272. layer_index = {layer.name: layer for layer in layers}
  2273. for idx, name in enumerate(layer_names):
  2274. if name not in layer_index.keys():
  2275. if skip:
  2276. logging.warning("Layer named '%s' not found in network. Skip it." % name)
  2277. else:
  2278. raise RuntimeError(
  2279. "Layer named '%s' not found in network. Hint: set argument skip=Ture "
  2280. "if you want to skip redundant or mismatch Layers." % name
  2281. )
  2282. else:
  2283. g = f[name]
  2284. layer = layer_index[name]
  2285. if isinstance(layer, tl.models.Model):
  2286. _load_weights_from_hdf5_group(g, layer.all_layers, skip)
  2287. elif isinstance(layer, tl.layers.ModelLayer):
  2288. _load_weights_from_hdf5_group(g, layer.model.all_layers, skip)
  2289. elif isinstance(layer, tl.layers.LayerList):
  2290. _load_weights_from_hdf5_group(g, layer.layers, skip)
  2291. elif isinstance(layer, tl.layers.Layer):
  2292. weight_names = [n.decode('utf8') for n in g.attrs['weight_names']]
  2293. for iid, w_name in enumerate(weight_names):
  2294. # FIXME : this is only for compatibility
  2295. if isinstance(layer, tl.layers.BatchNorm) and np.asarray(g[w_name]).ndim > 1:
  2296. assign_tf_variable(layer.all_weights[iid], np.asarray(g[w_name]).squeeze())
  2297. continue
  2298. assign_tf_variable(layer.all_weights[iid], np.asarray(g[w_name]))
  2299. else:
  2300. raise Exception("Only layer or model can be saved into hdf5.")
  2301. def save_weights_to_hdf5(filepath, network):
  2302. """Input filepath and save weights in hdf5 format.
  2303. Parameters
  2304. ----------
  2305. filepath : str
  2306. Filename to which the weights will be saved.
  2307. network : Model
  2308. TL model.
  2309. Returns
  2310. -------
  2311. """
  2312. logging.info("[*] Saving TL weights into %s" % filepath)
  2313. with h5py.File(filepath, 'w') as f:
  2314. _save_weights_to_hdf5_group(f, network.all_layers)
  2315. logging.info("[*] Saved")
  2316. def load_hdf5_to_weights_in_order(filepath, network):
  2317. """Load weights sequentially from a given file of hdf5 format
  2318. Parameters
  2319. ----------
  2320. filepath : str
  2321. Filename to which the weights will be loaded, should be of hdf5 format.
  2322. network : Model
  2323. TL model.
  2324. Notes:
  2325. If the file contains more weights than given 'weights', then the redundant ones will be ignored
  2326. if all previous weights match perfectly.
  2327. Returns
  2328. -------
  2329. """
  2330. f = h5py.File(filepath, 'r')
  2331. try:
  2332. layer_names = [n.decode('utf8') for n in f.attrs["layer_names"]]
  2333. except Exception:
  2334. raise NameError(
  2335. "The loaded hdf5 file needs to have 'layer_names' as attributes. "
  2336. "Please check whether this hdf5 file is saved from TL."
  2337. )
  2338. if len(network.all_layers) != len(layer_names):
  2339. logging.warning(
  2340. "Number of weights mismatch."
  2341. "Trying to load a saved file with " + str(len(layer_names)) + " layers into a model with " +
  2342. str(len(network.all_layers)) + " layers."
  2343. )
  2344. _load_weights_from_hdf5_group_in_order(f, network.all_layers)
  2345. f.close()
  2346. logging.info("[*] Load %s SUCCESS!" % filepath)
  2347. def load_hdf5_to_weights(filepath, network, skip=False):
  2348. """Load weights by name from a given file of hdf5 format
  2349. Parameters
  2350. ----------
  2351. filepath : str
  2352. Filename to which the weights will be loaded, should be of hdf5 format.
  2353. network : Model
  2354. TL model.
  2355. skip : bool
  2356. If 'skip' == True, loaded weights whose name is not found in 'weights' will be skipped. If 'skip' is False,
  2357. error will be raised when mismatch is found. Default False.
  2358. Returns
  2359. -------
  2360. """
  2361. f = h5py.File(filepath, 'r')
  2362. try:
  2363. layer_names = [n.decode('utf8') for n in f.attrs["layer_names"]]
  2364. except Exception:
  2365. raise NameError(
  2366. "The loaded hdf5 file needs to have 'layer_names' as attributes. "
  2367. "Please check whether this hdf5 file is saved from TL."
  2368. )
  2369. net_index = {layer.name: layer for layer in network.all_layers}
  2370. if len(network.all_layers) != len(layer_names):
  2371. logging.warning(
  2372. "Number of weights mismatch."
  2373. "Trying to load a saved file with " + str(len(layer_names)) + " layers into a model with " +
  2374. str(len(network.all_layers)) + " layers."
  2375. )
  2376. # check mismatch form network weights to hdf5
  2377. for name in net_index.keys():
  2378. if name not in layer_names:
  2379. logging.warning("Network layer named '%s' not found in loaded hdf5 file. It will be skipped." % name)
  2380. # load weights from hdf5 to network
  2381. _load_weights_from_hdf5_group(f, network.all_layers, skip)
  2382. f.close()
  2383. logging.info("[*] Load %s SUCCESS!" % filepath)
  2384. def load_and_assign_ckpt(model_dir, network=None, skip=True):
  2385. """Load weights by name from a given file of ckpt format
  2386. Parameters
  2387. ----------
  2388. model_dir : str
  2389. Filename to which the weights will be loaded, should be of ckpt format.
  2390. Examples: model_dir = /root/cnn_model/
  2391. network : Model
  2392. TL model.
  2393. skip : bool
  2394. If 'skip' == True, loaded weights whose name is not found in 'weights' will be skipped. If 'skip' is False,
  2395. error will be raised when mismatch is found. Default False.
  2396. Returns
  2397. -------
  2398. """
  2399. model_dir = model_dir
  2400. model_path = None
  2401. for root, dirs, files in os.walk(model_dir):
  2402. for file in files:
  2403. filename, extension = os.path.splitext(file)
  2404. if extension in ['.data-00000-of-00001', '.index', '.meta']:
  2405. model_path = model_dir + '/' + filename
  2406. break
  2407. if model_path == None:
  2408. raise Exception('The ckpt file is not found')
  2409. reader = pywrap_tensorflow.NewCheckpointReader(model_path)
  2410. var_to_shape_map = reader.get_variable_to_shape_map()
  2411. net_weights_name = [w.name for w in network.all_weights]
  2412. for key in var_to_shape_map:
  2413. if key not in net_weights_name:
  2414. if skip:
  2415. logging.warning("Weights named '%s' not found in network. Skip it." % key)
  2416. else:
  2417. raise RuntimeError(
  2418. "Weights named '%s' not found in network. Hint: set argument skip=Ture "
  2419. "if you want to skip redundant or mismatch weights." % key
  2420. )
  2421. else:
  2422. assign_tf_variable(network.all_weights[net_weights_name.index(key)], reader.get_tensor(key))
  2423. logging.info("[*] Model restored from ckpt %s" % filename)
  2424. def ckpt_to_npz_dict(model_dir, save_name='model.npz'):
  2425. """ Save ckpt weights to npz file
  2426. Parameters
  2427. ----------
  2428. model_dir : str
  2429. Filename to which the weights will be loaded, should be of ckpt format.
  2430. Examples: model_dir = /root/cnn_model/
  2431. save_name : str
  2432. The save_name of the `.npz` file.
  2433. Returns
  2434. -------
  2435. """
  2436. model_dir = model_dir
  2437. model_path = None
  2438. for root, dirs, files in os.walk(model_dir):
  2439. for file in files:
  2440. filename, extension = os.path.splitext(file)
  2441. if extension in ['.data-00000-of-00001', '.index', '.meta']:
  2442. model_path = model_dir + '/' + filename
  2443. break
  2444. if model_path == None:
  2445. raise Exception('The ckpt file is not found')
  2446. reader = pywrap_tensorflow.NewCheckpointReader(model_path)
  2447. var_to_shape_map = reader.get_variable_to_shape_map()
  2448. parameters_dict = {}
  2449. for key in sorted(var_to_shape_map):
  2450. parameters_dict[key] = reader.get_tensor(key)
  2451. np.savez(save_name, **parameters_dict)
  2452. parameters_dict = None
  2453. del parameters_dict
  2454. logging.info("[*] Ckpt weights saved in npz_dict %s" % save_name)

TensorLayer3.0 是一款兼容多种深度学习框架为计算后端的深度学习库。计划兼容TensorFlow, Pytorch, MindSpore, Paddle.