keras.js 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  1. var keras = keras || {};
  2. var json = json || require('./json');
  3. var python = python || require('./python');
  4. keras.ModelFactory = class {
  5. match(context) {
  6. const stream = context.stream;
  7. const signature = [ 0x89, 0x48, 0x44, 0x46, 0x0D, 0x0A, 0x1A, 0x0A ];
  8. if (stream.length > signature.length && stream.peek(signature.length).every((value, index) => value === signature[index])) {
  9. return 'keras.h5';
  10. }
  11. if (context.open('json')) {
  12. const obj = context.open('json');
  13. if (obj.mxnet_version || (obj.nodes && obj.arg_nodes && obj.heads)) {
  14. return undefined;
  15. }
  16. if (obj.modelTopology && (obj.format === 'layers-model' || obj.modelTopology.class_name || obj.modelTopology.model_config)) {
  17. return 'keras.json.tfjs';
  18. }
  19. if (obj.model_config || (obj.class_name && obj.config)) {
  20. return 'keras.json';
  21. }
  22. if (Array.isArray(obj) && obj.every((item) => item.weights && item.paths)) {
  23. return 'keras.json.tfjs.weights';
  24. }
  25. if (obj.tfjsVersion) {
  26. return 'keras.json.tfjs.metadata';
  27. }
  28. }
  29. if (context.open('pkl')) {
  30. const obj = context.open('pkl');
  31. if (obj.__class__ && obj.__class__.__module__ === 'keras.engine.sequential' && obj.__class__.__name__ === 'Sequential') {
  32. return 'keras.pickle';
  33. }
  34. }
  35. return undefined;
  36. }
  37. open(context, match) {
  38. const openModel = (format, producer, backend, config, weights) => {
  39. return keras.Metadata.open(context).then((metadata) => {
  40. return new keras.Model(metadata, format, producer, backend, config, weights);
  41. });
  42. };
  43. const openShards = (manifests, shards) => {
  44. const weights = new keras.Weights();
  45. const dtype_size_map = new Map([ [ 'float16', 2 ], [ 'float32', 4 ], [ 'float64', 8 ], [ 'int8', 1 ], [ 'int16', 2 ], [ 'int32', 4 ], [ 'int64', 8 ], [ 'uint8', 1 ], [ 'uint16', 2 ], [ 'uint32', 4 ], [ 'uint64', 8 ] ]);
  46. for (const manifest of manifests) {
  47. let buffer = null;
  48. if (Array.isArray(manifest.paths) && manifest.paths.length > 0 && manifest.paths.every((path) => shards.has(path))) {
  49. const list = manifest.paths.map((path) => shards.get(path));
  50. const size = list.reduce((a, b) => a + b.length, 0);
  51. buffer = new Uint8Array(size);
  52. let offset = 0;
  53. for (const item of list) {
  54. buffer.set(item, offset);
  55. offset += item.length;
  56. }
  57. }
  58. let offset = 0;
  59. for (const weight of manifest.weights) {
  60. const dtype = weight.quantization && weight.quantization.dtype ? weight.quantization.dtype : weight.dtype;
  61. if (!dtype_size_map.has(dtype)) {
  62. throw new keras.Error("Unsupported weight data type size '" + dtype + "'.");
  63. }
  64. const itemsize = dtype_size_map.get(dtype);
  65. const size = weight.shape.reduce((a, b) => a * b, 1);
  66. const length = itemsize * size;
  67. const data = buffer ? buffer.slice(offset, offset + length) : null;
  68. weights.add(weight.identifier, new keras.Tensor(weight.name, weight.shape, dtype, weight.quantization, true, data));
  69. offset += length;
  70. }
  71. }
  72. return Promise.resolve(weights);
  73. };
  74. const openManifests = (manifests) => {
  75. const shards = new Map();
  76. for (const manifest of manifests) {
  77. for (const path of manifest.paths) {
  78. if (!shards.has(path)) {
  79. shards.set(path, context.request(path, null));
  80. }
  81. }
  82. }
  83. const promises = shards.values();
  84. return Promise.all(promises).then((streams) => {
  85. for (const key of shards.keys()) {
  86. shards.set(key, streams.shift().peek());
  87. }
  88. return openShards(manifests, shards);
  89. }).catch(() => {
  90. shards.clear();
  91. return openShards(manifests, shards);
  92. });
  93. };
  94. const openModelJson = (context, obj) => {
  95. const modelTopology = obj.modelTopology;
  96. const backend = modelTopology.backend || '';
  97. const format = 'TensorFlow.js ' + (obj.format ? obj.format : 'Keras' + (modelTopology.keras_version ? (' v' + modelTopology.keras_version) : ''));
  98. const producer = obj.convertedBy || obj.generatedBy || '';
  99. const manifests = obj.weightsManifest;
  100. for (const manifest of manifests) {
  101. for (const weight of manifest.weights) {
  102. weight.identifier = '';
  103. }
  104. }
  105. const model_config = modelTopology.model_config ? modelTopology.model_config : modelTopology;
  106. return openManifests(manifests).then((weights) => {
  107. return openModel(format, producer, backend, model_config, weights);
  108. });
  109. };
  110. const stream = context.stream;
  111. switch (match) {
  112. case 'keras.h5': {
  113. return context.require('./hdf5').then((hdf5) => {
  114. const find_root_group = (file) => {
  115. const root_group = file.rootGroup;
  116. const kerasmodel = root_group.group('model/kerasmodel');
  117. if (kerasmodel && kerasmodel.attributes.has('model_config')) {
  118. return kerasmodel;
  119. }
  120. return root_group;
  121. };
  122. const read_model_config = (group) => {
  123. if (group.attributes.has('model_config')) {
  124. const buffer = group.attributes.get('model_config');
  125. const reader = json.TextReader.open(buffer);
  126. if (reader) {
  127. return reader.read();
  128. }
  129. }
  130. return null;
  131. };
  132. const load_attributes_from_hdf5_group = (group, name) => {
  133. if (group.attributes.has(name)) {
  134. return group.attributes.get(name);
  135. }
  136. if (group.attributes.has(name + '0')) {
  137. let index = 0;
  138. let value = [];
  139. while (group.attributes.has(name + index.toString())) {
  140. const chunk = group.attributes.get(name + index.toString());
  141. value = value.concat(chunk);
  142. index++;
  143. }
  144. return value;
  145. }
  146. return null;
  147. };
  148. const weights = new keras.Weights();
  149. const file = hdf5.File.open(stream);
  150. const root_group = find_root_group(file);
  151. const model_config = read_model_config(root_group);
  152. if (model_config) {
  153. const backend = root_group.attributes.get('backend') || '';
  154. const version = root_group.attributes.get('keras_version') || '';
  155. const format = 'Keras' + (version ? ' v' + version : '');
  156. const model_weights_group = root_group.group('model_weights');
  157. if (model_weights_group) {
  158. const layer_names = load_attributes_from_hdf5_group(model_weights_group, 'layer_names');
  159. for (const layer_name of layer_names) {
  160. const layer_weights = model_weights_group.group(layer_name);
  161. if (layer_weights) {
  162. const weight_names = load_attributes_from_hdf5_group(layer_weights, 'weight_names');
  163. if (Array.isArray(weight_names) && weight_names.length > 0) {
  164. for (const weight_name of weight_names) {
  165. const weight = layer_weights.group(weight_name);
  166. if (weight && weight.value) {
  167. const variable = weight.value;
  168. const tensor = new keras.Tensor(weight_name, variable.shape, variable.type, null, variable.littleEndian, variable.data);
  169. weights.add(layer_name, tensor);
  170. }
  171. }
  172. }
  173. }
  174. }
  175. }
  176. if (!model_config) {
  177. throw new keras.Error("'model_config' is not present.");
  178. }
  179. if (!model_config.class_name) {
  180. throw new keras.Error("'class_name' is not present.");
  181. }
  182. return openModel(format, '', backend, model_config, weights);
  183. }
  184. const layer_names = load_attributes_from_hdf5_group(root_group, 'layer_names');
  185. if (layer_names && Array.isArray(layer_names)) {
  186. const version = root_group.attributes.get('keras_version') || '';
  187. const format = 'Keras Weights' + (version ? ' v' + version : '');
  188. const backend = root_group.attributes.get('backend') || '';
  189. for (const layer_name of layer_names) {
  190. const layer_weights = root_group.group(layer_name);
  191. if (layer_weights) {
  192. const weight_names = load_attributes_from_hdf5_group(layer_weights, 'weight_names');
  193. if (Array.isArray(weight_names) && weight_names.length > 0) {
  194. for (const weight_name of weight_names) {
  195. const weight = layer_weights.group(weight_name);
  196. if (weight && weight.value) {
  197. const variable = weight.value;
  198. const components = weight_name.split('/');
  199. components.pop();
  200. const name = (components.length == 0 || components[0] !== layer_name) ? [ layer_name ].concat(components).join('/') : components.join('/');
  201. const tensor = new keras.Tensor(weight_name, variable.shape, variable.type, null, variable.littleEndian, variable.data);
  202. weights.add(name, tensor);
  203. }
  204. }
  205. }
  206. }
  207. }
  208. return openModel(format, '', backend, null, weights);
  209. }
  210. else {
  211. const rootKeys = new Set(root_group.attributes.keys());
  212. rootKeys.delete('nb_layers');
  213. if (rootKeys.size > 0 || root_group.value !== null) {
  214. throw new keras.Error('File format is not HDF5 Weights');
  215. }
  216. const format = 'HDF5 Weights';
  217. let weights_group = root_group;
  218. if (root_group.attributes.size === 0 && root_group.value === null && root_group.groups.size == 1) {
  219. const group = root_group.groups.values().next().value;
  220. if (group.attributes.size === 0 && group.value === null) {
  221. weights_group = group;
  222. }
  223. }
  224. const tensorKeys = new Set([ 'name', 'shape', 'quantization' ]);
  225. const groups = Array.from(weights_group.groups.values());
  226. if (groups.every((group) => group.attributes.size === 0 && group.groups.length == 0 && group.value !== null)) {
  227. for (const group of groups) {
  228. const variable = group.value;
  229. const tensor = new keras.Tensor(group.name, variable.shape, variable.type, null, variable.littleEndian, variable.type === 'string' ? variable.value : variable.data);
  230. weights.add('', tensor);
  231. }
  232. return openModel(format, '', '', null, weights);
  233. }
  234. if (groups.every((group) => group.value === null && Array.from(group.attributes.keys()).filter((key) => !tensorKeys.has(key)).length === 0 && Array.from(group.groups.values()).every((variable) => Object.keys(variable.attributes).length === 0 && variable.value !== null))) {
  235. for (const group of groups) {
  236. const moduleName = group.attributes.has('name') ? group.attributes.get('name') : group.name;
  237. for (const variableGroup of group.groups.values()) {
  238. if (variableGroup.attributes.size !== 0 || variableGroup.groups.size !== 0) {
  239. throw new keras.Error('Variable format is not HDF5 Weights');
  240. }
  241. const variable = variableGroup.value;
  242. if (!variable) {
  243. throw new keras.Error('Variable value is not HDF5 Weights');
  244. }
  245. const name = moduleName ? [ moduleName, variableGroup.name ].join('/') : moduleName.name;
  246. const tensor = new keras.Tensor(name, variable.shape, variable.type, null, variable.littleEndian, variable.type === 'string' ? variable.value : variable.data);
  247. weights.add(moduleName, tensor);
  248. }
  249. }
  250. return openModel(format, '', '', null, weights);
  251. }
  252. const walk = function(group) {
  253. if (group.attributes.size === 0 && group.value === null && group.groups.size > 0) {
  254. for (const subGroup of group.groups.values()) {
  255. walk(subGroup);
  256. }
  257. return;
  258. }
  259. const subKeys = new Set([ 'index', 'need_grad' ]);
  260. const attribtues = Array.from(group.attributes.keys());
  261. const match = attribtues.filter((key) => !subKeys.has(key)).length === 0;
  262. if (match && group.value !== null && group.groups.size === 0) {
  263. const variable = group.value;
  264. const variableName = group.path;
  265. let moduleName = variableName;
  266. const parts = variableName.split('/');
  267. if (parts.length > 1) {
  268. parts.pop();
  269. moduleName = parts.join('/');
  270. }
  271. const tensor = new keras.Tensor(variableName, variable.shape, variable.type, null, variable.littleEndian, variable.type === 'string' ? variable.value : variable.data);
  272. weights.add(moduleName, tensor);
  273. return;
  274. }
  275. throw new keras.Error('Module group format is not HDF5 Weights');
  276. };
  277. walk(weights_group);
  278. return openModel(format, '', '', null, weights);
  279. }
  280. });
  281. }
  282. case 'keras.json': {
  283. const obj = context.open('json');
  284. const format = 'Keras' + (obj.keras_version ? ' v' + obj.keras_version : '');
  285. const backend = obj.backend || '';
  286. const config = obj.model_config ? obj.model_config : obj;
  287. const weights = new keras.Weights();
  288. return openModel(format, '', backend, config, weights);
  289. }
  290. case 'keras.json.tfjs': {
  291. const obj = context.open('json');
  292. return openModelJson(context, obj);
  293. }
  294. case 'keras.json.tfjs.weights': {
  295. const obj = context.open('json');
  296. const manifests = [];
  297. const format = 'TensorFlow.js Weights';
  298. manifests.push(...obj);
  299. for (const manifest of manifests) {
  300. for (const weight of manifest.weights) {
  301. const parts = weight.name.split('/');
  302. parts.pop();
  303. weight.identifier = parts.join('/');
  304. }
  305. }
  306. return openManifests(manifests).then((weights) => {
  307. return openModel(format, '', '', null, weights);
  308. });
  309. }
  310. case 'keras.json.tfjs.metadata': {
  311. return context.request('model.json').then((buffer) => {
  312. const reader = json.TextReader.open(buffer);
  313. const obj = reader.read();
  314. return openModelJson(context, obj);
  315. });
  316. }
  317. case 'keras.pickle': {
  318. const execution = new python.Execution(null);
  319. const obj = context.open('pkl');
  320. const decoder = new TextDecoder('utf-8');
  321. const format = 'Keras Pickle' + (obj.keras_version ? ' v' + decoder.decode(obj.keras_version) : '');
  322. const backend = obj.backend ? decoder.decode(obj.backend) : '';
  323. const reader = json.TextReader.open(obj.model_config);
  324. const model_config = reader.read();
  325. const weights = new keras.Weights();
  326. const model_weights_group = obj.model_weights;
  327. if (model_weights_group) {
  328. const layer_names = model_weights_group.layer_names.map((buffer) => decoder.decode(buffer));
  329. for (const layer_name of layer_names) {
  330. const layer_weights = model_weights_group[layer_name];
  331. if (layer_weights) {
  332. const weight_names = layer_weights.weight_names.map((buffer) => decoder.decode(buffer));
  333. if (Array.isArray(weight_names) && weight_names.length > 0) {
  334. for (const weight_name of weight_names) {
  335. const buffer = layer_weights[weight_name];
  336. const unpickler = python.Unpickler.open(buffer);
  337. const variable = unpickler.load((name, args) => execution.invoke(name, args));
  338. const tensor = new keras.Tensor(weight_name, variable.shape, variable.dtype.name, null, true, variable.data);
  339. weights.add(layer_name, tensor);
  340. }
  341. }
  342. }
  343. }
  344. }
  345. return openModel(format, '', backend, model_config, weights);
  346. }
  347. default: {
  348. throw new keras.Error("Unsupported Keras format '" + match + "'.");
  349. }
  350. }
  351. }
  352. };
  353. keras.Model = class {
  354. constructor(metadata, format, producer, backend, config, weights) {
  355. this._format = format;
  356. this._backend = backend;
  357. this._producer = producer;
  358. metadata = new keras.GraphMetadata(metadata);
  359. this._graphs = [ new keras.Graph(metadata, config, weights) ];
  360. }
  361. get name() {
  362. return null;
  363. }
  364. get description() {
  365. return null;
  366. }
  367. get format() {
  368. return this._format;
  369. }
  370. get producer() {
  371. return this._producer;
  372. }
  373. get runtime() {
  374. return this._backend;
  375. }
  376. get graphs() {
  377. return this._graphs;
  378. }
  379. };
  380. keras.Graph = class {
  381. constructor(metadata, config, weights, group) {
  382. this._metadata = metadata;
  383. this._inputs = [];
  384. this._outputs = [];
  385. this._nodes = [];
  386. group = group || '';
  387. const loadNode = (layer, inputs, outputs, weights, group) => {
  388. layer = Object.assign({}, layer);
  389. layer.inputs = inputs;
  390. layer.outputs = outputs;
  391. return new keras.Node(this._metadata, layer, group, weights);
  392. };
  393. const getInputType = (layer) => {
  394. if (layer && layer.config) {
  395. let dataType = '?';
  396. let shape = [];
  397. const config = layer.config;
  398. if (config.dtype) {
  399. dataType = config.dtype;
  400. delete config.dtype;
  401. }
  402. if (config.batch_input_shape) {
  403. shape = config.batch_input_shape.map(s => s == null ? '?' : s);
  404. delete config.batch_input_shape;
  405. }
  406. return new keras.TensorType(dataType, new keras.TensorShape(shape));
  407. }
  408. return null;
  409. };
  410. if (config) {
  411. this._name = config.name || (config.config && config.config.name ? config.config.name : '');
  412. const is_connection = (item) => {
  413. return Array.isArray(item) && (item.length === 3 || item.length === 4) && typeof item[0] === 'string' && typeof item[1] === 'number' && typeof item[2] === 'number';
  414. };
  415. switch (config.class_name) {
  416. case 'AllCNN':
  417. case 'Sequential': {
  418. config = config.config;
  419. const inputs = null;
  420. const outputs = null;
  421. const inputName = 'input';
  422. let inputType = null;
  423. let argument = inputName;
  424. let index = 0;
  425. const layers = config.layers ? config.layers : config;
  426. for (const layer of layers) {
  427. let name = index.toString();
  428. let nodeInputs = [ { name: argument } ];
  429. if (index == 0) {
  430. if (inputs && inputs.length > 0) {
  431. nodeInputs = [ inputs[0] ];
  432. }
  433. else {
  434. inputType = getInputType(layer);
  435. }
  436. }
  437. index++;
  438. if (layer.config && layer.config.name) {
  439. name = layer.config.name;
  440. }
  441. argument = name;
  442. let nodeOutputs = [ argument ];
  443. if (index == layers.length) {
  444. if (outputs && outputs.length > 0) {
  445. nodeOutputs = [ outputs[0] ];
  446. argument = null;
  447. }
  448. }
  449. this.nodes.push(loadNode(layer, nodeInputs, nodeOutputs, weights, group));
  450. }
  451. if (!inputs) {
  452. this._inputs.push(new keras.Parameter(inputName, true, [ new keras.Argument(inputName, inputType, null) ]));
  453. }
  454. if (argument) {
  455. this._outputs.push(new keras.Parameter(argument, true, [ new keras.Argument(argument, null, null) ]));
  456. }
  457. break;
  458. }
  459. case 'Functional':
  460. case 'Model': {
  461. config = config.config;
  462. const nodes = new Map();
  463. if (config.layers) {
  464. for (const layer of config.layers) {
  465. layer.inputs = [];
  466. layer.outputs = [];
  467. layer.args = {};
  468. if (layer.name && !nodes.has(layer.name)) {
  469. nodes.set(layer.name, layer);
  470. }
  471. }
  472. const read_connection = (input_data) => {
  473. let name = input_data[0];
  474. const node = nodes.get(name);
  475. if (node) {
  476. // const node_index = input_data[1];
  477. const tensor_index = input_data[2];
  478. if (tensor_index !== 0) {
  479. name += ':' + tensor_index.toString();
  480. }
  481. while (tensor_index >= node.outputs.length) {
  482. node.outputs.push('');
  483. }
  484. node.outputs[tensor_index] = name;
  485. }
  486. return { name: name };
  487. };
  488. const read_value = (input_data) => {
  489. const array_size = (value) => {
  490. if (value.every((item) => Array.isArray(item) && item.length > 2 && item[0] === '_CONSTANT_VALUE' && item[1] === -1)) {
  491. for (let i = 0; i < value.length; i++) {
  492. value[i] = value[i][2];
  493. }
  494. }
  495. else if (value.every((item) => Array.isArray(item))) {
  496. const dims = value.map((item) => array_size(item));
  497. const dim = dims[0];
  498. for (let i = 1; i < dims.length; i++) {
  499. if (dim.length === dims[i].length) {
  500. if (!dims[i].every((value, i) => value ===dim[i])) {
  501. throw new python.Error('Invalid array shape.');
  502. }
  503. }
  504. }
  505. return [ value.length ].concat(dim);
  506. }
  507. return [ value.length ];
  508. };
  509. if (Array.isArray(input_data)) {
  510. const shape = array_size(input_data);
  511. return { shape: shape, value: input_data };
  512. }
  513. return { value: input_data };
  514. };
  515. for (const layer of config.layers) {
  516. if (layer.inbound_nodes) {
  517. for (const inbound_node of layer.inbound_nodes) {
  518. if (is_connection(inbound_node)) {
  519. layer.inputs.push(read_connection(inbound_node));
  520. const args = inbound_node[3] || {};
  521. layer.args = {};
  522. for (const entry of Object.entries(args)) {
  523. const key = entry[0];
  524. const value = entry[1];
  525. layer.args[key] = is_connection(value) ? read_connection(value) : read_value(value);
  526. }
  527. }
  528. else if (Array.isArray(inbound_node)) {
  529. for (const input_data of inbound_node) {
  530. if (is_connection(input_data)) {
  531. layer.inputs.push(read_connection(input_data));
  532. }
  533. else if (Array.isArray(input_data) && input_data.every((item) => is_connection(item))) {
  534. for (const input of input_data) {
  535. layer.inputs.push(read_connection(input));
  536. }
  537. }
  538. else if (Array.isArray(input_data)) {
  539. layer.inputs.push(read_value(input_data));
  540. }
  541. else {
  542. throw new keras.Error("Invalid inbound connection '" + JSON.stringify(input_data) + "'.");
  543. }
  544. }
  545. }
  546. else {
  547. throw new keras.Error("Invalid inbound node '" + JSON.stringify(inbound_node) + "'.");
  548. }
  549. }
  550. }
  551. }
  552. }
  553. const input_layers = is_connection(config.input_layers) ? [ config.input_layers ] : config.input_layers;
  554. if (input_layers) {
  555. for (let i = 0; i < input_layers.length; i++) {
  556. const input_layer = input_layers[i];
  557. const name = input_layer[0];
  558. let type = null;
  559. const node = nodes.get(name);
  560. if (node && node.class_name == 'InputLayer') {
  561. type = getInputType(node);
  562. nodes.delete(name);
  563. }
  564. const argument = new keras.Argument(name, type, null);
  565. const parameter = new keras.Parameter(name, true, [ argument ]);
  566. this._inputs.push(parameter);
  567. }
  568. }
  569. const output_layers = is_connection(config.output_layers) ? [ config.output_layers ] : config.output_layers;
  570. if (output_layers) {
  571. for (let j = 0; j < output_layers.length; j++) {
  572. const output_layer = output_layers[j];
  573. let outputName = output_layer[0];
  574. const outputNode = nodes.get(outputName);
  575. if (outputNode) {
  576. const outputIndex = output_layer[2];
  577. if (outputIndex != 0) {
  578. outputName += ':' + outputIndex.toString();
  579. }
  580. while (outputIndex >= outputNode.outputs.length) {
  581. outputNode.outputs.push('');
  582. }
  583. outputNode.outputs[outputIndex] = outputName;
  584. }
  585. const argument = new keras.Argument(outputName, null, null);
  586. const parameter = new keras.Parameter(outputName, true, [ argument ]);
  587. this._outputs.push(parameter);
  588. }
  589. }
  590. if (config.layers) {
  591. for (const layer of config.layers) {
  592. if (nodes.has(layer.name)) {
  593. this._nodes.push(loadNode(layer, layer.inputs, layer.outputs, weights, group));
  594. }
  595. }
  596. }
  597. break;
  598. }
  599. default:
  600. throw new keras.Error('\'' + config.class_name + '\' is not supported.');
  601. }
  602. }
  603. else if (weights) {
  604. for (const name of weights.keys()) {
  605. if (weights.get('', name).length <= 6) {
  606. const layer = { class_name: 'Weights', config: { name: name } };
  607. const node = new keras.Node(metadata, layer, '', weights);
  608. this._nodes.push(node);
  609. }
  610. }
  611. }
  612. }
  613. get name() {
  614. return this._name;
  615. }
  616. get inputs() {
  617. return this._inputs;
  618. }
  619. get outputs() {
  620. return this._outputs;
  621. }
  622. get nodes() {
  623. return this._nodes;
  624. }
  625. };
  626. keras.Parameter = class {
  627. constructor(name, visible, args) {
  628. this._name = name;
  629. this._visible = visible;
  630. this._arguments = args;
  631. }
  632. get name() {
  633. return this._name;
  634. }
  635. get visible() {
  636. return this._visible;
  637. }
  638. get arguments() {
  639. return this._arguments;
  640. }
  641. };
  642. keras.Argument = class {
  643. constructor(name, type, initializer) {
  644. if (typeof name !== 'string') {
  645. throw new keras.Error("Invalid argument identifier '" + JSON.stringify(name) + "'.");
  646. }
  647. this._name= name;
  648. this._type = type || null;
  649. this._initializer = initializer || null;
  650. }
  651. get name() {
  652. return this._name;
  653. }
  654. get type() {
  655. if (this._initializer) {
  656. return this._initializer.type;
  657. }
  658. return this._type;
  659. }
  660. get quantization() {
  661. if (this._initializer) {
  662. return this._initializer.quantization;
  663. }
  664. return null;
  665. }
  666. get initializer() {
  667. return this._initializer;
  668. }
  669. };
  670. keras.Node = class {
  671. constructor(metadata, layer, group, weights) {
  672. const config = layer.config || {};
  673. const args = layer.args || {};
  674. let inputs = layer.inputs || [];
  675. let outputs = layer.outputs || [];
  676. const name = config && config.name ? config.name : '';
  677. this._group = group || '';
  678. this._name = (this._group ? this._group + '/' : '') + name;
  679. this._inputs = [];
  680. this._outputs = [];
  681. this._attributes = [];
  682. this._chain = [];
  683. let names = [ name ];
  684. let type = layer.class_name;
  685. let model = false;
  686. switch (type) {
  687. case 'Model':
  688. case 'Functional':
  689. case 'Sequential': {
  690. const name = layer.name || (layer.config ? layer.config.name : '');
  691. this._type = new keras.Graph(metadata, layer, weights, (group ? group + '/' : '') + name);
  692. model = true;
  693. if (config) {
  694. delete config.layers;
  695. delete config.input_layers;
  696. delete config.output_layers;
  697. }
  698. this._inputs = [ new keras.Parameter('inputs', true, inputs.map((input) => new keras.Argument(input.name, null, null))) ];
  699. this._outputs = [ new keras.Parameter('outputs', true, outputs.map((name) => new keras.Argument(name, null, null))) ];
  700. inputs = [];
  701. outputs = [];
  702. break;
  703. }
  704. case 'Bidirectional':
  705. case 'TimeDistributed': {
  706. if (config && config.layer) {
  707. const inner = config.layer;
  708. delete config.layer;
  709. this._inner = new keras.Node(metadata, inner, null, null);
  710. if (type == 'Bidirectional' && inner.config.name) {
  711. names = [ name + '/forward_' + inner.config.name, name + '/backward_' + inner.config.name ];
  712. if (!group) {
  713. group = name;
  714. }
  715. }
  716. }
  717. this._type = metadata.type(type) || { name: type };
  718. break;
  719. }
  720. case 'TFOpLambda': {
  721. if (config && config.function) {
  722. type = config.function;
  723. delete config.function;
  724. }
  725. this._type = metadata.type(type) || { name: type };
  726. break;
  727. }
  728. default: {
  729. this._type = metadata.type(type) || { name: type };
  730. break;
  731. }
  732. }
  733. const initializers = {};
  734. if (weights && !model) {
  735. for (const name of names) {
  736. let tensors = weights.get(group, name);
  737. if (tensors.length > 0) {
  738. for (const initializer of tensors) {
  739. inputs.push({ name: initializer.name });
  740. initializers[initializer.name] = initializer;
  741. }
  742. }
  743. else {
  744. tensors = weights.get('', name);
  745. for (const initializer of tensors) {
  746. inputs.push({ name: initializer.name });
  747. initializers[initializer.name] = initializer;
  748. }
  749. }
  750. }
  751. }
  752. if (config && !Array.isArray(config)) {
  753. for (const entry of Object.entries(config)) {
  754. const name = entry[0];
  755. const value = entry[1];
  756. if (name === 'activation' && value !== 'linear') {
  757. if (typeof value === 'string') {
  758. const set = new Map([ [ 'elu', 'ELU' ], [ 'exponential', 'Exponential' ], [ 'hard_sigmoid', 'HardSigmoid' ], [ 'linear', 'Linear' ], [ 'relu', 'ReLU' ], [ 'selu', 'SELU' ], [ 'softmax', 'Softmax'], [ 'sigmoid', 'Sigmoid' ], [ 'softplus', 'SoftPlus' ], [ 'softsign', 'SoftSign' ], [ 'tanh', 'TanH' ] ]);
  759. const type = set.has(value) ? set.get(value) : value;
  760. this.chain.push(new keras.Node(metadata, { class_name: type }, null, null));
  761. }
  762. else if (value && typeof value.class_name === 'string' && value.config) {
  763. const type = value.class_name;
  764. if (!metadata.type(type)) {
  765. metadata.add(type, { name: type, category: 'Activation' });
  766. }
  767. this.chain.push(new keras.Node(metadata, value, null, null));
  768. }
  769. }
  770. if (name !== 'name') {
  771. const attribute = new keras.Attribute(metadata.attribute(type, name), name, value);
  772. this._attributes.push(attribute);
  773. }
  774. }
  775. }
  776. const innerType = this.inner ? this.inner.type : null;
  777. const innerSchema = innerType ? metadata.type(innerType) : null;
  778. let inputIndex = 0;
  779. while (inputs.length > 0) {
  780. let list = false;
  781. let inputName = null;
  782. let visible = true;
  783. if (!innerSchema || inputIndex == 0) {
  784. if (this._type && this._type.inputs && inputIndex < this._type.inputs.length) {
  785. const input = this._type.inputs[inputIndex];
  786. inputName = input.name;
  787. if (type === 'BatchNormalization' && inputName === 'gamma' && config.scale === false) {
  788. inputIndex++;
  789. continue;
  790. }
  791. visible = input.visible == false ? false : true;
  792. if (this._type.inputs[inputIndex].list) {
  793. list = true;
  794. }
  795. }
  796. }
  797. else {
  798. switch (type) {
  799. case 'Bidirectional': {
  800. let innerIndex = inputIndex;
  801. if (innerSchema && innerSchema.inputs) {
  802. if (innerIndex < innerSchema.inputs.length) {
  803. inputName = 'forward_' + innerSchema.inputs[innerIndex].name;
  804. }
  805. else {
  806. innerIndex = innerIndex - innerSchema.inputs.length + 1;
  807. if (innerIndex < innerSchema.inputs.length) {
  808. inputName = 'backward_' + innerSchema.inputs[innerIndex].name;
  809. }
  810. }
  811. }
  812. visible = false;
  813. break;
  814. }
  815. case 'TimeDistributed':
  816. if (innerSchema && innerSchema.inputs && inputIndex < innerSchema.inputs.length) {
  817. inputName = innerSchema.inputs[inputIndex].name;
  818. }
  819. break;
  820. default:
  821. break;
  822. }
  823. }
  824. const input = !list ? [ inputs.shift() ] : inputs.splice(0, inputs.length);
  825. const inputArguments = input.map((input) => {
  826. if (input.name) {
  827. return new keras.Argument(input.name, null, initializers[input.name]);
  828. }
  829. if (input.value) {
  830. const tensor = new keras.Tensor('', input.shape, config.dtype || '?', null, undefined, input.value);
  831. return new keras.Argument('', null, tensor);
  832. }
  833. throw new keras.Error("Invalid argument '" + JSON.stringify(input.name) + "'.");
  834. });
  835. if (!inputName && inputArguments.length == 1 && inputArguments[0].initializer && inputArguments[0].initializer.name) {
  836. if (names.length === 1 && names[0] === '') {
  837. inputName = inputArguments[0].initializer.name;
  838. }
  839. else {
  840. const parts = inputArguments[0].initializer.name.split('/').pop().split(':').shift().split('_');
  841. const inputName1 = parts.pop();
  842. const inputName2 = parts.length > 0 ? [ parts.pop(), inputName1 ].join('_') : '';
  843. const inputNames = new Set([ 'recurrent_kernel', 'running_mean', 'running_std', 'moving_mean', 'moving_variance', 'depthwise_filter', 'pointwise_filter' ]);
  844. inputName = inputNames.has(inputName2) ? inputName2 : inputName1;
  845. }
  846. }
  847. this._inputs.push(new keras.Parameter(inputName || inputIndex.toString(), visible, inputArguments));
  848. inputIndex++;
  849. }
  850. for (let i = 0; i < outputs.length; i++) {
  851. const output = outputs[i];
  852. const outputName = (this._type && this._type.outputs && i < this._type.outputs.length && this._type.outputs[i] && this._type.outputs[i].name) ? this._type.outputs[i].name : i.toString();
  853. const parameter = new keras.Parameter(outputName, true, [ new keras.Argument(output, null, null) ]);
  854. this._outputs.push(parameter);
  855. }
  856. const inputTypes = new Map((this._type.inputs || []).map((input) => [ input.name, input.type ]));
  857. for (const entry of Object.entries(args)) {
  858. const name = entry[0];
  859. const value = entry[1];
  860. if (name !== 'name') {
  861. if (value.name || (inputTypes.has(name) && inputTypes.get(name) === 'Tensor' && value)) {
  862. if (value.name) {
  863. const argument = new keras.Argument(value.name, null, null);
  864. const parameter = new keras.Parameter(name, true, [ argument ]);
  865. this._inputs.push(parameter);
  866. }
  867. else {
  868. const tensor = new keras.Tensor('', value.shape, config.dtype || '?', null, undefined, value.value);
  869. const argument = new keras.Argument('', null, tensor);
  870. const parameter = new keras.Parameter(name, true, [ argument ]);
  871. this._inputs.push(parameter);
  872. }
  873. }
  874. else {
  875. const attribute = new keras.Attribute(metadata.attribute(type, name), name, value);
  876. this._attributes.push(attribute);
  877. }
  878. }
  879. }
  880. if (typeof this.type.name !== 'string' || !this.type.name.split) { // #416
  881. throw new keras.Error("Unsupported node type '" + JSON.stringify(this.type.name) + "'.");
  882. }
  883. }
  884. get type() {
  885. return this._type;
  886. }
  887. get name() {
  888. return this._name;
  889. }
  890. get inputs() {
  891. return this._inputs;
  892. }
  893. get outputs() {
  894. return this._outputs;
  895. }
  896. get attributes() {
  897. return this._attributes;
  898. }
  899. get chain() {
  900. return this._chain;
  901. }
  902. get inner() {
  903. return this._inner;
  904. }
  905. };
  906. keras.Attribute = class {
  907. constructor(metadata, name, value) {
  908. this._name = name;
  909. this._value = value;
  910. if (value && typeof value == 'object' && value.class_name && value.config) {
  911. this._value = keras.Attribute._convert(value);
  912. }
  913. switch (name) {
  914. case 'trainable':
  915. this._type = 'boolean';
  916. this._visible = false;
  917. break;
  918. case 'dtype':
  919. this._visible = false;
  920. break;
  921. default: {
  922. if (metadata) {
  923. if (metadata.type) {
  924. this._type = metadata.type;
  925. }
  926. if (Object.prototype.hasOwnProperty.call(metadata, 'visible')) {
  927. this._visible = metadata.visible;
  928. }
  929. else if (metadata.default !== undefined) {
  930. if (Array.isArray(value)) {
  931. if (Array.isArray(metadata.default)) {
  932. this._visible = value.length !== metadata.default || !this.value.every((item, index) => item == metadata.default[index]);
  933. }
  934. else {
  935. this._visible = !this.value.every((item) => item == metadata.default);
  936. }
  937. }
  938. else {
  939. this._visible = this.value !== metadata.default;
  940. }
  941. }
  942. }
  943. break;
  944. }
  945. }
  946. }
  947. get name() {
  948. return this._name;
  949. }
  950. get type() {
  951. return this._type;
  952. }
  953. get value() {
  954. return this._value;
  955. }
  956. get visible() {
  957. return this._visible == false ? false : true;
  958. }
  959. static _convert(value) {
  960. if (Array.isArray(value) || value !== Object(value)) {
  961. return value;
  962. }
  963. const obj = {};
  964. if (value.class_name) {
  965. obj.__type__ = value.class_name;
  966. }
  967. if (value.config) {
  968. for (const entry of Object.entries(value.config)) {
  969. const key = entry[0];
  970. const value = entry[1];
  971. obj[key] = keras.Attribute._convert(value);
  972. }
  973. }
  974. return obj;
  975. }
  976. };
  977. keras.Tensor = class {
  978. constructor(name, shape, type, quantization, littleEndian, data) {
  979. this._name = name;
  980. this._type = new keras.TensorType(type, new keras.TensorShape(shape));
  981. this._quantization = quantization;
  982. this._littleEndian = littleEndian;
  983. this._data = data;
  984. }
  985. get kind() {
  986. return 'Weights';
  987. }
  988. get name() {
  989. return this._name;
  990. }
  991. get type() {
  992. return this._type;
  993. }
  994. get quantization() {
  995. if (this._quantization && (this._quantization.scale !== 0 || this._quantization.min !== 0)) {
  996. const scale = this._quantization.scale || 0;
  997. const min = this._quantization.min || 0;
  998. return scale.toString() + ' * ' + (min == 0 ? 'q' : ('(q - ' + min.toString() + ')'));
  999. }
  1000. return null;
  1001. }
  1002. get state() {
  1003. if (Array.isArray(this._data)) {
  1004. return '';
  1005. }
  1006. return this._context().state;
  1007. }
  1008. get value() {
  1009. if (Array.isArray(this._data)) {
  1010. return this._data;
  1011. }
  1012. const context = this._context();
  1013. if (context.state) {
  1014. return null;
  1015. }
  1016. context.limit = Number.MAX_SAFE_INTEGER;
  1017. return this._decode(context, 0);
  1018. }
  1019. toString() {
  1020. if (Array.isArray(this._data)) {
  1021. return keras.Tensor._stringify(this._data, '', ' ');
  1022. }
  1023. const context = this._context();
  1024. if (context.state) {
  1025. return '';
  1026. }
  1027. context.limit = 10000;
  1028. const value = this._decode(context, 0);
  1029. return keras.Tensor._stringify(value, '', ' ');
  1030. }
  1031. _context() {
  1032. const context = {};
  1033. context.index = 0;
  1034. context.count = 0;
  1035. context.state = null;
  1036. if (!this._data) {
  1037. context.state = 'Tensor data is empty.';
  1038. return context;
  1039. }
  1040. switch (this._type.dataType) {
  1041. case 'boolean':
  1042. case 'float16':
  1043. case 'float32':
  1044. case 'float64':
  1045. case 'uint8':
  1046. case 'int32':
  1047. case 'int64':
  1048. context.dataType = this._type.dataType;
  1049. context.view = new DataView(this._data.buffer, this._data.byteOffset, this._data.byteLength);
  1050. context.littleEndian = this._littleEndian;
  1051. break;
  1052. case 'string':
  1053. context.dataType = this._type.dataType;
  1054. context.data = this._data;
  1055. break;
  1056. default:
  1057. context.state = 'Tensor data type is not supported.';
  1058. break;
  1059. }
  1060. context.shape = this._type.shape.dimensions;
  1061. return context;
  1062. }
  1063. _decode(context, dimension) {
  1064. const shape = context.shape.length !== 0 ? context.shape : [ 1 ];
  1065. const results = [];
  1066. const size = shape[dimension];
  1067. const littleEndian = context.littleEndian;
  1068. if (dimension == shape.length - 1) {
  1069. for (let i = 0; i < size; i++) {
  1070. if (context.count > context.limit) {
  1071. results.push(null);
  1072. return results;
  1073. }
  1074. switch (context.dataType) {
  1075. case 'float16':
  1076. results.push(context.view.getFloat16(context.index, littleEndian));
  1077. context.index += 2;
  1078. break;
  1079. case 'float32':
  1080. results.push(context.view.getFloat32(context.index, littleEndian));
  1081. context.index += 4;
  1082. break;
  1083. case 'float64':
  1084. results.push(context.view.getFloat64(context.index, littleEndian));
  1085. context.index += 8;
  1086. break;
  1087. case 'boolean':
  1088. results.push(context.view.getInt8(context.index) !== 0);
  1089. context.index += 1;
  1090. break;
  1091. case 'uint8':
  1092. results.push(context.view.getUint8(context.index));
  1093. context.index += 1;
  1094. break;
  1095. case 'int32':
  1096. results.push(context.view.getInt32(context.index, littleEndian));
  1097. context.index += 4;
  1098. break;
  1099. case 'int64':
  1100. results.push(context.view.getInt64(context.index, littleEndian));
  1101. context.index += 8;
  1102. break;
  1103. case 'string':
  1104. results.push(context.view[context.index]);
  1105. context.index++;
  1106. break;
  1107. default:
  1108. throw new keras.Error("Unsupported tensor data type '" + context.dataType + "'.");
  1109. }
  1110. context.count++;
  1111. }
  1112. }
  1113. else {
  1114. for (let j = 0; j < size; j++) {
  1115. if (context.count > context.limit) {
  1116. results.push(null);
  1117. return results;
  1118. }
  1119. results.push(this._decode(context, dimension + 1));
  1120. }
  1121. }
  1122. if (context.shape.length == 0) {
  1123. return results[0];
  1124. }
  1125. return results;
  1126. }
  1127. static _stringify(value, indentation, indent) {
  1128. if (Array.isArray(value)) {
  1129. const result = [];
  1130. result.push(indentation + '[');
  1131. const items = value.map((item) => keras.Tensor._stringify(item, indentation + indent, indent));
  1132. if (items.length > 0) {
  1133. result.push(items.join(',\n'));
  1134. }
  1135. result.push(indentation + ']');
  1136. return result.join('\n');
  1137. }
  1138. if (value === null) {
  1139. return indentation + '...';
  1140. }
  1141. if (typeof value == 'string') {
  1142. return indentation + '"' + value + '"';
  1143. }
  1144. if (value == Infinity) {
  1145. return indentation + 'Infinity';
  1146. }
  1147. if (value == -Infinity) {
  1148. return indentation + '-Infinity';
  1149. }
  1150. if (isNaN(value)) {
  1151. return indentation + 'NaN';
  1152. }
  1153. return indentation + value.toString();
  1154. }
  1155. };
  1156. keras.TensorType = class {
  1157. constructor(dataType, shape) {
  1158. this._dataType = dataType;
  1159. this._shape = shape;
  1160. }
  1161. get dataType() {
  1162. return this._dataType;
  1163. }
  1164. get shape() {
  1165. return this._shape;
  1166. }
  1167. toString() {
  1168. return this._dataType + this._shape.toString();
  1169. }
  1170. };
  1171. keras.TensorShape = class {
  1172. constructor(dimensions) {
  1173. this._dimensions = dimensions;
  1174. }
  1175. get dimensions() {
  1176. return this._dimensions;
  1177. }
  1178. toString() {
  1179. return this._dimensions ? ('[' + this._dimensions.map((dimension) => dimension.toString()).join(',') + ']') : '';
  1180. }
  1181. };
  1182. keras.GraphMetadata = class {
  1183. constructor(metadata) {
  1184. this._metadata = metadata;
  1185. this._types = new Map();
  1186. }
  1187. type(name) {
  1188. if (this._types.has(name)) {
  1189. return this._types.get(name);
  1190. }
  1191. return this._metadata.type(name);
  1192. }
  1193. attribute(type, name) {
  1194. return this._metadata.attribute(type, name);
  1195. }
  1196. add(type, metadata) {
  1197. this._types.set(type, metadata);
  1198. }
  1199. };
  1200. keras.Metadata = class {
  1201. static open(context) {
  1202. if (keras.Metadata._metadata) {
  1203. return Promise.resolve(keras.Metadata._metadata);
  1204. }
  1205. return context.request('keras-metadata.json', 'utf-8', null).then((data) => {
  1206. keras.Metadata._metadata = new keras.Metadata(data);
  1207. return keras.Metadata._metadata;
  1208. }).catch(() => {
  1209. keras.Metadata._metadata = new keras.Metadata(null);
  1210. return keras.Metadata._metadatas;
  1211. });
  1212. }
  1213. constructor(data) {
  1214. this._map = new Map();
  1215. this._attributeCache = new Map();
  1216. if (data) {
  1217. const metadata = JSON.parse(data);
  1218. this._map = new Map(metadata.map((item) => [ item.name, item ]));
  1219. }
  1220. }
  1221. type(name) {
  1222. return this._map.get(name);
  1223. }
  1224. attribute(type, name) {
  1225. const key = type + ':' + name;
  1226. if (!this._attributeCache.has(key)) {
  1227. const schema = this.type(type);
  1228. if (schema && schema.attributes && schema.attributes.length > 0) {
  1229. for (const attribute of schema.attributes) {
  1230. this._attributeCache.set(type + ':' + attribute.name, attribute);
  1231. }
  1232. }
  1233. if (!this._attributeCache.has(key)) {
  1234. this._attributeCache.set(key, null);
  1235. }
  1236. }
  1237. return this._attributeCache.get(key);
  1238. }
  1239. };
  1240. keras.Weights = class {
  1241. constructor() {
  1242. this._map = new Map();
  1243. }
  1244. add(layer_name, tensor) {
  1245. if (!this._map.has(layer_name)) {
  1246. this._map.set(layer_name, []);
  1247. }
  1248. this._map.get(layer_name).push(tensor);
  1249. }
  1250. get(group, name) {
  1251. if (group) {
  1252. const list = this._map.get(group.split('/').shift());
  1253. if (list) {
  1254. const match1 = list.filter((tensor) => tensor.name.startsWith(name + '/'));
  1255. if (match1.length > 0) {
  1256. return match1;
  1257. }
  1258. const match2 = list.filter((tensor) => tensor.name.startsWith(group + '/' + name + '/'));
  1259. if (match2.length > 0) {
  1260. return match2;
  1261. }
  1262. }
  1263. }
  1264. else {
  1265. const match1 = this._map.get(name);
  1266. if (match1 && match1.length > 0) {
  1267. return match1;
  1268. }
  1269. const match2 = this._map.get('');
  1270. if (match2 && match2.length > 0) {
  1271. const match3 = match2.filter((tensor) => tensor.name.startsWith((group ? group + '/' : '') + name + '/'));
  1272. if (match3.length > 0) {
  1273. return match3;
  1274. }
  1275. }
  1276. }
  1277. return [];
  1278. }
  1279. keys() {
  1280. return this._map.keys();
  1281. }
  1282. };
  1283. keras.Error = class extends Error {
  1284. constructor(message) {
  1285. super(message);
  1286. this.name = 'Error loading Keras model.';
  1287. }
  1288. };
  1289. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  1290. module.exports.ModelFactory = keras.ModelFactory;
  1291. }