shevchenko 3.0.0-rc.2 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/cjs/anthroponym-declension/anthroponym-inflector.js +1 -1
- package/dist/cjs/anthroponym-declension/bootstrap.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-classifier/artifacts/model.bundle.json.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-classifier/cache/incorrect-predictions.json.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-classifier/family-name-class-transformer.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-classifier/family-name-classifer.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-classifier/model-bundle-loader.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-classifier/model-config.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-classifier/word-transformer.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-inflector.js +1 -1
- package/dist/cjs/anthroponym-declension/given-name-inflector.js +1 -1
- package/dist/cjs/anthroponym-declension/name-inflector.js +1 -1
- package/dist/cjs/anthroponym-declension/patronymic-name-inflector.js +1 -1
- package/dist/cjs/gender-detection/detect-gender.js +1 -1
- package/dist/cjs/gender-detection/given-names-genders.json.js +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/input-validation.js +1 -1
- package/dist/cjs/language/alphabet.js +1 -1
- package/dist/cjs/language/grammatical-case.js +1 -1
- package/dist/cjs/language/grammatical-gender.js +1 -1
- package/dist/cjs/language/letter-case.js +5 -3
- package/dist/cjs/language/letter-case.js.map +1 -1
- package/dist/cjs/language/linguistics.js +1 -1
- package/dist/cjs/language/word-class.js +1 -1
- package/dist/cjs/shevchenko.js +1 -1
- package/dist/cjs/word-declension/append-command-runner.js +1 -1
- package/dist/cjs/word-declension/bootstrap.js +1 -1
- package/dist/cjs/word-declension/command-runner-factory.js +1 -1
- package/dist/cjs/word-declension/declension-rule-inflector.js +1 -1
- package/dist/cjs/word-declension/declension-rules.json.js +1 -1
- package/dist/cjs/word-declension/declension-types.js +1 -1
- package/dist/cjs/word-declension/replace-command-runner.js +1 -1
- package/dist/cjs/word-declension/word-inflector.js +2 -2
- package/dist/cjs/word-declension/word-inflector.js.map +1 -1
- package/dist/es/anthroponym-declension/anthroponym-inflector.js +1 -1
- package/dist/es/anthroponym-declension/bootstrap.js +1 -1
- package/dist/es/anthroponym-declension/family-name-classifier/artifacts/model.bundle.json.js +1 -1
- package/dist/es/anthroponym-declension/family-name-classifier/cache/incorrect-predictions.json.js +1 -1
- package/dist/es/anthroponym-declension/family-name-classifier/family-name-class-transformer.js +1 -1
- package/dist/es/anthroponym-declension/family-name-classifier/family-name-classifer.js +1 -1
- package/dist/es/anthroponym-declension/family-name-classifier/model-bundle-loader.js +1 -1
- package/dist/es/anthroponym-declension/family-name-classifier/model-config.js +1 -1
- package/dist/es/anthroponym-declension/family-name-classifier/word-transformer.js +1 -1
- package/dist/es/anthroponym-declension/family-name-inflector.js +1 -1
- package/dist/es/anthroponym-declension/given-name-inflector.js +1 -1
- package/dist/es/anthroponym-declension/name-inflector.js +1 -1
- package/dist/es/anthroponym-declension/patronymic-name-inflector.js +1 -1
- package/dist/es/gender-detection/detect-gender.js +1 -1
- package/dist/es/gender-detection/given-names-genders.json.js +1 -1
- package/dist/es/index.js +1 -1
- package/dist/es/input-validation.js +1 -1
- package/dist/es/language/alphabet.js +1 -1
- package/dist/es/language/grammatical-case.js +1 -1
- package/dist/es/language/grammatical-gender.js +1 -1
- package/dist/es/language/letter-case.js +5 -3
- package/dist/es/language/letter-case.js.map +1 -1
- package/dist/es/language/linguistics.js +1 -1
- package/dist/es/language/word-class.js +1 -1
- package/dist/es/shevchenko.js +1 -1
- package/dist/es/word-declension/append-command-runner.js +1 -1
- package/dist/es/word-declension/bootstrap.js +1 -1
- package/dist/es/word-declension/command-runner-factory.js +1 -1
- package/dist/es/word-declension/declension-rule-inflector.js +1 -1
- package/dist/es/word-declension/declension-rules.json.js +1 -1
- package/dist/es/word-declension/declension-types.js +1 -1
- package/dist/es/word-declension/replace-command-runner.js +1 -1
- package/dist/es/word-declension/word-inflector.d.ts.map +1 -1
- package/dist/es/word-declension/word-inflector.js +2 -2
- package/dist/es/word-declension/word-inflector.js.map +1 -1
- package/dist/umd/shevchenko.min.js +75 -75
- package/dist/umd/shevchenko.min.js.map +1 -1
- package/package.json +3 -5
- package/src/language/letter-case.ts +4 -2
- package/src/word-declension/word-inflector.ts +3 -1
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @file JavaScript library for declension of Ukrainian anthroponyms
|
|
3
3
|
* @module shevchenko
|
|
4
|
-
* @version 3.0.0
|
|
4
|
+
* @version 3.0.0
|
|
5
5
|
* @author Oleksandr Tolochko <tooleks@gmail.com>
|
|
6
6
|
* @license MIT
|
|
7
7
|
* @copyright 2017-2023 Oleksandr Tolochko <tooleks@gmail.com>
|
|
8
8
|
* @see {@link git+https://github.com/tooleks/shevchenko-js.git}
|
|
9
9
|
*/
|
|
10
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("crypto")):"function"==typeof define&&define.amd?define(["exports","crypto"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).shevchenko={},e.require$$0)}(this,(function(e,t){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=n(t);function a(e,t,n,i){return new(n||(n=Promise))((function(a,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function o(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?a(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,o)}l((i=i.apply(e,t||[])).next())}))}var s,r;!function(e){e[e["а"]=1]="а",e[e["б"]=2]="б",e[e["в"]=3]="в",e[e["г"]=4]="г",e[e["ґ"]=5]="ґ",e[e["д"]=6]="д",e[e["е"]=7]="е",e[e["є"]=8]="є",e[e["ж"]=9]="ж",e[e["з"]=10]="з",e[e["и"]=11]="и",e[e["і"]=12]="і",e[e["ї"]=13]="ї",e[e["й"]=14]="й",e[e["к"]=15]="к",e[e["л"]=16]="л",e[e["м"]=17]="м",e[e["н"]=18]="н",e[e["о"]=19]="о",e[e["п"]=20]="п",e[e["р"]=21]="р",e[e["с"]=22]="с",e[e["т"]=23]="т",e[e["у"]=24]="у",e[e["ф"]=25]="ф",e[e["х"]=26]="х",e[e["ц"]=27]="ц",e[e["ч"]=28]="ч",e[e["ш"]=29]="ш",e[e["щ"]=30]="щ",e[e["ь"]=31]="ь",e[e["ю"]=32]="ю",e[e["я"]=33]="я"}(s||(s={})),function(e){e.NOUN="noun",e.ADJECTIVE="adjective"}(r||(r={}));const o=/[аоуеиіяюєї]/gi;function l(e){return 1===function(e){const t=e.match(o);return null==t?0:t.length}(e)}var c,u,h;function p(e,t=0){return e.charAt(t)===e.charAt(t).toUpperCase()}function d(e,t=0){return e.charAt(t)===e.charAt(t).toLowerCase()}e.GrammaticalCase=void 0,(c=e.GrammaticalCase||(e.GrammaticalCase={})).NOMINATIVE="nominative",c.GENITIVE="genitive",c.DATIVE="dative",c.ACCUSATIVE="accusative",c.ABLATIVE="ablative",c.LOCATIVE="locative",c.VOCATIVE="vocative",e.GrammaticalGender=void 0,(u=e.GrammaticalGender||(e.GrammaticalGender={})).MASCULINE="masculine",u.FEMININE="feminine";class m{constructor(e){this.command=e}exec(e){return e+this.command.value}}!function(e){e.REPLACE="replace",e.APPEND="append"}(h||(h={}));class f{constructor(e){this.command=e}exec(){return this.command.value}}class g{make(e){switch(e.action){case h.APPEND:return new m(e);case h.REPLACE:return new f(e);default:throw new TypeError(`Invalid command action: ${e.action}.`)}}}class v{constructor(e){this.rule=e,this.commandRunnerFactory=new g}inflect(e,t){const[n]=this.rule.grammaticalCases[t];if(n){const t=new RegExp(this.rule.pattern.modify,"gi"),i=e.replace(t,((e,...t)=>{let i="";const a=function(e){const t=new RegExp(`${e.toString()}|`).exec("");return null==t?0:t.length-1}(this.rule.pattern.modify);for(let e=0;e<a;e+=1){let a=t[e];const s=n[e];null!=s&&(a=this.commandRunnerFactory.make(s).exec(a)),i+=a}return i}));return function(e,t){let n="";for(let i=0;i<t.length;i+=1){const a=e[i]||e[e.length-1],s=t[i];d(a)?n+=s.toLowerCase():p(a)?n+=s.toUpperCase():n+=s}return n}(e,i)}return e}}const y=[{description:"жіноче ім'я любов",examples:["любов"],wordClass:"noun",gender:["feminine"],priority:6,application:["givenName"],pattern:{find:"^любов$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"і"}}],dative:[{0:{action:"append",value:"і"}}],accusative:[],ablative:[{0:{action:"append",value:"'ю"}}],locative:[{0:{action:"append",value:"і"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"чоловічі імена федір, сидір",examples:["федір","сидір"],wordClass:"noun",gender:["masculine"],priority:6,application:["givenName"],pattern:{find:"^(федір|сидір)$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"слово суддя",examples:["суддя"],wordClass:"noun",gender:["masculine","feminine"],priority:6,application:["familyName"],pattern:{find:"^суддя$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"слово рілля",examples:["рілля"],wordClass:"noun",gender:["masculine","feminine"],priority:6,application:["familyName"],pattern:{find:"^рілля$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосна)вень",examples:["півень"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)вень$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}},{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}}],vocative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосна)лець",examples:["стрілець","білець"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)лець$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ь"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ь"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(к|п|кр|пл|др|жив)іт",examples:["кіт","кріт"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"(к|п|кр|пл|др|жив)іт$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -грім",examples:["грім"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"грім$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(дзвін|хрін)",examples:["дзвін"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"(дзвін|хрін)$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -батіг",examples:["батіг"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"батіг$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"replace",value:"зі"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"replace",value:"гу"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -сокіл",examples:["сокіл"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"сокіл$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -кріль",examples:["кріль"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"кріль$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}}]}},{description:"чоловічі імена ігор, лазар",examples:["ігор","лазар"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"^(ігор|лазар)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"я"}}],dative:[{0:{action:"append",value:"ю"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"я"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"ю"}},{0:{action:"append",value:"еві"}}],vocative:[{0:{action:"append",value:"ю"}}]}},{description:"слово сіль",examples:["сіль"],wordClass:"noun",gender:["masculine"],priority:5,application:["familyName"],pattern:{find:"^сіль$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}}],accusative:[],ablative:[{2:{action:"replace",value:"лю"}}],locative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосна)(тверда приголосна)е(ц|н)ь",examples:["половець"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)е(ц|н)ь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(тверда приголосна)(тверда приголосна)е(ц|н)ь",examples:["жнець"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)е(ц|н)ь$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(рід|плід)",examples:["рід","плід"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"(рід|плід)$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / чоловічі прізвища на -ніс, без чергування",examples:["ханіс","деніс","маніс"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"^(б|в|г|ґ|д|дз|дж|ж|з|й|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)(а|е|є|и|і|ї|о|у|ю|я)ніс$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"і"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(з|яв)ір",examples:["дивозір","явір"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"(з|яв)ір$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -орел",examples:["орел"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"орел$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"а"}}],dative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"ові"}},{0:{action:"replace",value:"л"},1:{action:"replace",value:"у"}}],accusative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"а"}}],ablative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"ом"}}],locative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"ові"}}],vocative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -якір",examples:["якір"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"якір$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"я"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ю"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"я"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ю"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -бідь",examples:["лебідь"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:".бідь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -мінь",examples:["кремінь"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:".мінь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -сіль",examples:["кисіль"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"сіль$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -кінь",examples:["кінь"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"кінь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -куліш",examples:["куліш"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"куліш$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"еві"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"жіночий рід / на -(тверда приголосна)ька",examples:["ільницька","сумська"],wordClass:"adjective",gender:["feminine"],priority:4,application:["familyName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)ька$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -ова",examples:["іванова"],wordClass:"adjective",gender:["feminine"],priority:4,application:["familyName"],pattern:{find:"ова$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -іна",examples:["зеленкіна"],wordClass:"adjective",gender:["feminine"],priority:4,application:["familyName"],pattern:{find:"іна$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосна)єць",examples:["заєць"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)єць$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"й"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"й"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -віз",examples:["узвіз"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"віз$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ків",examples:["яків"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:".ків$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(к|р)іп",examples:["прокіп"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:".(к|р)іп$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -піп",examples:["прокіп"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"піп$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ніс",examples:["кривоніс"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"ніс$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -віл",examples:["рябовіл"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"віл$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ріг",examples:["пиріг"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"ріг$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"replace",value:"зі"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -хід",examples:["прихід"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"хід$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / жіночий рід / м'яка група / на -ель",examples:["нінель","мішель"],wordClass:"noun",gender:["feminine"],priority:4,application:["givenName"],pattern:{find:"ель$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"і"}}],dative:[{1:{action:"replace",value:"і"}}],accusative:[],ablative:[{0:{action:"replace",value:"лл"},1:{action:"replace",value:"ю"}}],locative:[{1:{action:"replace",value:"і"}}],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -ишин",examples:["ковалишин"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"ишин$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"им"}}],locative:[{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(аго|ово)",examples:["живаго"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"(аго|ово)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[],dative:[],accusative:[],ablative:[],locative:[],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -тер",examples:["вітер"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"тер$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"е"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -світ",examples:["світ"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"світ$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"чоловічі імена / на -(в|д)ір",examples:["дір","вір"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"(в|д)ір$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"чоловічий рід / на -кій (помилкова транслітерація)",examples:["дідківській"],wordClass:"adjective",gender:["masculine"],priority:3,application:["familyName"],pattern:{find:"кій$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ого"}}],dative:[{0:{action:"replace",value:"ому"}}],accusative:[{0:{action:"replace",value:"ого"}}],ablative:[{0:{action:"replace",value:"им"}}],locative:[{0:{action:"replace",value:"ому"}}],vocative:[]}},{description:"множина / на -их",examples:["седих"],wordClass:"adjective",gender:["masculine"],priority:3,application:[],pattern:{find:"их$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[],dative:[],accusative:[],ablative:[],locative:[],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -га",examples:["нога"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"га$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -кіш",examples:["розкіш"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"кіш$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -ьо",examples:["іваньо","кузьо"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"ьо$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"append",value:"м"}}],locative:[{0:{action:"replace",value:"ю"}}],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -е(в|н)",examples:["семен","лев"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"е(в|н)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -пес",examples:["пес"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"пес$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ко",examples:["марко"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"ко$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"а"}}],dative:[{0:{action:"replace",value:"у"}},{0:{action:"replace",value:"ові"}}],accusative:[{0:{action:"replace",value:"а"}}],ablative:[{0:{action:"replace",value:"ом"}}],locative:[{0:{action:"replace",value:"ові"}},{0:{action:"replace",value:"у"}}],vocative:[{0:{action:"replace",value:"у"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -ий",examples:["батий"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"ий$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"єм"}}],locative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -йо",examples:["йойо"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"йо$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"append",value:"ві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"append",value:"м"}}],locative:[{0:{action:"append",value:"ві"}}],vocative:[]}},{description:"перша відміна / чоловічий рід / тверда група / на -бо",examples:["голембо"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"бо$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[]}},{description:"чоловічий рід / на -ой, -ий",examples:["толстой","сухомлинський"],wordClass:"adjective",gender:["masculine"],priority:2,application:["familyName"],pattern:{find:"(ой|ий)$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ого"}}],dative:[{0:{action:"replace",value:"ому"}}],accusative:[{0:{action:"replace",value:"ого"}}],ablative:[{0:{action:"replace",value:"им"}}],locative:[{0:{action:"replace",value:"ому"}}],vocative:[]}},{description:"чоловічий рід / на -ій",examples:["заболотній"],wordClass:"adjective",gender:["masculine"],priority:2,application:["familyName"],pattern:{find:"ій$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ього"}}],dative:[{0:{action:"replace",value:"ьому"}}],accusative:[{0:{action:"replace",value:"ього"}}],ablative:[{0:{action:"replace",value:"ім"}}],locative:[{0:{action:"replace",value:"ьому"}}],vocative:[]}},{description:"жіночий рід / на -(тверда приголосна)а",examples:["зелена"],wordClass:"adjective",gender:["feminine"],priority:2,application:["familyName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)а$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -(тверда приголосна)я",examples:["задорожня"],wordClass:"adjective",gender:["feminine"],priority:2,application:["familyName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ьої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ьою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -ая",examples:["толстая"],wordClass:"adjective",gender:["feminine"],priority:2,application:["familyName"],pattern:{find:"ая$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"ую"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -яя",examples:["заболотняя"],wordClass:"adjective",gender:["feminine"],priority:2,application:["familyName"],pattern:{find:"яя$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ьої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ьою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"чоловічі по батькові та прізвища / на -ич",examples:["валерійович","риндич"],wordClass:"noun",gender:["masculine"],priority:2,application:["patronymicName","familyName"],pattern:{find:"ич$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"чоловічі по батькові та прізвища / на -іч",examples:["ілліч"],wordClass:"noun",gender:["masculine"],priority:2,application:["patronymicName","familyName"],pattern:{find:"іч$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"і"}},{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"жіночі по батькові / на -на",examples:["юріївна"],wordClass:"noun",gender:["feminine"],priority:2,application:["patronymicName"],pattern:{find:"на$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"}}]}},{description:"жіночі імена / на -(тверда приголосна)я",examples:["неля"],wordClass:"noun",gender:["feminine"],priority:2,application:["givenName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"чоловічі імена / на -ня",examples:["женя"],wordClass:"noun",gender:["masculine"],priority:2,application:["givenName"],pattern:{find:"ня$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група/ на -ов",examples:["павлов"],wordClass:"noun",gender:["masculine"],priority:2,application:["familyName"],pattern:{find:"ов$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"им"}}],locative:[{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ів",examples:["ковалів"],wordClass:"noun",gender:["masculine"],priority:2,application:["familyName"],pattern:{find:"ів$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"им"}}],locative:[{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -яр",examples:["скляр"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"яр$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"еві"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / жіночий рід / тверда, м'яка група / на -(о|ь|тверда приголосна)",examples:["шевченко"],wordClass:"noun",gender:["feminine"],priority:2,application:[],pattern:{find:"(о|ь|(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ))$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[],dative:[],accusative:[],ablative:[],locative:[],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -ок",examples:["сашок"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"ок$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}},{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -е(тверда_прилосона)",examples:["марек"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"е(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(тверда приголосна)я",examples:["гмиря"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий, жіночий роди / м'яка група / на -(голосна|ь|й)я",examples:["юлія","майя"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"((а|е|є|и|і|ї|о|у|ю|я)|ь|й)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ї"}}],dative:[{0:{action:"replace",value:"ї"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"єю"}}],locative:[{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"є"}}]}},{description:"друга відміна / чоловічий рід / мішана група / на -(дж|ж|ч|ш)",examples:["януш","джордж"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"(дж|ж|ч|ш)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"еві"}},{0:{action:"append",value:"і"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -к",examples:["кузик","мисяк"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"к$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -х",examples:["кожух"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"х$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"перша відміна / чоловічий, жіночий роди / тверда група / на -ха",examples:["старуха"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"ха$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"с"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"с"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}},{1:{action:"replace",value:"а"}}]}},{description:"перша відміна / чоловічий, жіночий роди / тверда група / на -ка",examples:["прилука"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"ка$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"ц"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ц"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}},{1:{action:"replace",value:"а"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -(тверда приголосна)о",examples:["петро","павло"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)о$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"а"}}],dative:[{0:{action:"replace",value:"у"}}],accusative:[{0:{action:"replace",value:"а"}}],ablative:[{0:{action:"replace",value:"ом"}}],locative:[{0:{action:"replace",value:"ові"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"перша відміна / жіночий рід / тверда група / на -(г|ґ)а",examples:["ольга"],wordClass:"noun",gender:["feminine"],priority:2,application:[],pattern:{find:"(г|ґ)а$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -ле",examples:["поле"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"ле$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"е"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[]}},{description:"перша відміна / чоловічий, жіночий роди / мішана група / на -а",examples:["мойша"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"(дж|ж|ч|ш|щ)а$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(тверда приголосна)",examples:["олександр"],wordClass:"noun",gender:["masculine"],priority:1,application:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"перша відміна / чоловічий, жіночий роди / тверда група / на -а",examples:["анна"],wordClass:"noun",gender:["masculine","feminine"],priority:1,application:[],pattern:{find:"а$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -й",examples:["валерій"],wordClass:"noun",gender:["masculine"],priority:1,application:[],pattern:{find:"й$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"єві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"єм"}}],locative:[{0:{action:"replace",value:"єві"}},{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -ь",examples:["петрунь"],wordClass:"noun",gender:["masculine"],priority:1,application:[],pattern:{find:"ь$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"жіночі імена / на -('|`)я",examples:["дар'я","мар'я"],wordClass:"noun",gender:["feminine"],priority:1,application:["givenName"],pattern:{find:"('|`)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ї"}}],dative:[{0:{action:"replace",value:"ї"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"єю"}}],locative:[{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"є"}}]}}],b=new class{constructor(e){this.declensionRules=e}inflect(e,t){return a(this,void 0,void 0,(function*(){const[n]=this.declensionRules.filter((e=>e.gender.includes(t.gender))).filter((e=>!t.application||0===e.application.length||e.application.includes(t.application))).filter((t=>new RegExp(t.pattern.find,"gi").test(e))).filter((e=>!t.wordClass||e.wordClass===t.wordClass)).filter(((e,n,i)=>!t.customRuleFilter||t.customRuleFilter(e,n,i)));return null==n?e:new v(n).inflect(e,t.grammaticalCase)}))}}(y);class w{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class k{refCount(e){return x("refCount")}incRef(e){return x("incRef")}timerAvailable(){return!0}time(e){return x("time")}read(e){return x("read")}readSync(e){return x("readSync")}readToGPU(e,t){return x("readToGPU")}numDataIds(){return x("numDataIds")}disposeData(e,t){return x("disposeData")}write(e,t,n){return x("write")}move(e,t,n,i,a){return x("move")}createTensorFromGPUData(e,t,n){return x("createTensorFromGPUData")}memory(){return x("memory")}floatPrecision(){return x("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return x("dispose")}}function x(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}
|
|
10
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("crypto")):"function"==typeof define&&define.amd?define(["exports","crypto"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).shevchenko={},e.require$$0)}(this,(function(e,t){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=n(t);function a(e,t,n,i){return new(n||(n=Promise))((function(a,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function o(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?a(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,o)}l((i=i.apply(e,t||[])).next())}))}var s,r;!function(e){e[e["а"]=1]="а",e[e["б"]=2]="б",e[e["в"]=3]="в",e[e["г"]=4]="г",e[e["ґ"]=5]="ґ",e[e["д"]=6]="д",e[e["е"]=7]="е",e[e["є"]=8]="є",e[e["ж"]=9]="ж",e[e["з"]=10]="з",e[e["и"]=11]="и",e[e["і"]=12]="і",e[e["ї"]=13]="ї",e[e["й"]=14]="й",e[e["к"]=15]="к",e[e["л"]=16]="л",e[e["м"]=17]="м",e[e["н"]=18]="н",e[e["о"]=19]="о",e[e["п"]=20]="п",e[e["р"]=21]="р",e[e["с"]=22]="с",e[e["т"]=23]="т",e[e["у"]=24]="у",e[e["ф"]=25]="ф",e[e["х"]=26]="х",e[e["ц"]=27]="ц",e[e["ч"]=28]="ч",e[e["ш"]=29]="ш",e[e["щ"]=30]="щ",e[e["ь"]=31]="ь",e[e["ю"]=32]="ю",e[e["я"]=33]="я"}(s||(s={})),function(e){e.NOUN="noun",e.ADJECTIVE="adjective"}(r||(r={}));const o=/[аоуеиіяюєї]/gi;function l(e){return 1===function(e){const t=e.match(o);return null==t?0:t.length}(e)}var c,u,h;function p(e,t=0){const n=e.charAt(t);return n===n.toUpperCase()}function d(e,t=0){const n=e.charAt(t);return n===n.toLowerCase()}e.GrammaticalCase=void 0,(c=e.GrammaticalCase||(e.GrammaticalCase={})).NOMINATIVE="nominative",c.GENITIVE="genitive",c.DATIVE="dative",c.ACCUSATIVE="accusative",c.ABLATIVE="ablative",c.LOCATIVE="locative",c.VOCATIVE="vocative",e.GrammaticalGender=void 0,(u=e.GrammaticalGender||(e.GrammaticalGender={})).MASCULINE="masculine",u.FEMININE="feminine";class m{constructor(e){this.command=e}exec(e){return e+this.command.value}}!function(e){e.REPLACE="replace",e.APPEND="append"}(h||(h={}));class f{constructor(e){this.command=e}exec(){return this.command.value}}class g{make(e){switch(e.action){case h.APPEND:return new m(e);case h.REPLACE:return new f(e);default:throw new TypeError(`Invalid command action: ${e.action}.`)}}}class v{constructor(e){this.rule=e,this.commandRunnerFactory=new g}inflect(e,t){const[n]=this.rule.grammaticalCases[t];if(n){const t=new RegExp(this.rule.pattern.modify,"gi"),i=e.replace(t,((e,...t)=>{let i="";const a=function(e){const t=new RegExp(`${e.toString()}|`).exec("");return null==t?0:t.length-1}(this.rule.pattern.modify);for(let e=0;e<a;e+=1){let a=t[e];const s=n[e];null!=s&&(a=this.commandRunnerFactory.make(s).exec(a)),i+=a}return i}));return function(e,t){let n="";for(let i=0;i<t.length;i+=1){const a=e[i]||e[e.length-1],s=t[i];d(a)?n+=s.toLowerCase():p(a)?n+=s.toUpperCase():n+=s}return n}(e,i)}return e}}const y=[{description:"жіноче ім'я любов",examples:["любов"],wordClass:"noun",gender:["feminine"],priority:6,application:["givenName"],pattern:{find:"^любов$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"і"}}],dative:[{0:{action:"append",value:"і"}}],accusative:[],ablative:[{0:{action:"append",value:"'ю"}}],locative:[{0:{action:"append",value:"і"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"чоловічі імена федір, сидір",examples:["федір","сидір"],wordClass:"noun",gender:["masculine"],priority:6,application:["givenName"],pattern:{find:"^(федір|сидір)$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"слово суддя",examples:["суддя"],wordClass:"noun",gender:["masculine","feminine"],priority:6,application:["familyName"],pattern:{find:"^суддя$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"слово рілля",examples:["рілля"],wordClass:"noun",gender:["masculine","feminine"],priority:6,application:["familyName"],pattern:{find:"^рілля$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосна)вень",examples:["півень"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)вень$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}},{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}}],vocative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосна)лець",examples:["стрілець","білець"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)лець$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ь"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ь"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(к|п|кр|пл|др|жив)іт",examples:["кіт","кріт"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"(к|п|кр|пл|др|жив)іт$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -грім",examples:["грім"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"грім$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(дзвін|хрін)",examples:["дзвін"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"(дзвін|хрін)$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -батіг",examples:["батіг"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"батіг$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"replace",value:"зі"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"replace",value:"гу"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -сокіл",examples:["сокіл"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"сокіл$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -кріль",examples:["кріль"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"кріль$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}}]}},{description:"чоловічі імена ігор, лазар",examples:["ігор","лазар"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"^(ігор|лазар)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"я"}}],dative:[{0:{action:"append",value:"ю"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"я"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"ю"}},{0:{action:"append",value:"еві"}}],vocative:[{0:{action:"append",value:"ю"}}]}},{description:"слово сіль",examples:["сіль"],wordClass:"noun",gender:["masculine"],priority:5,application:["familyName"],pattern:{find:"^сіль$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}}],accusative:[],ablative:[{2:{action:"replace",value:"лю"}}],locative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосна)(тверда приголосна)е(ц|н)ь",examples:["половець"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)е(ц|н)ь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(тверда приголосна)(тверда приголосна)е(ц|н)ь",examples:["жнець"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)е(ц|н)ь$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(рід|плід)",examples:["рід","плід"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"(рід|плід)$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / чоловічі прізвища на -ніс, без чергування",examples:["ханіс","деніс","маніс"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"^(б|в|г|ґ|д|дз|дж|ж|з|й|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)(а|е|є|и|і|ї|о|у|ю|я)ніс$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"і"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(з|яв)ір",examples:["дивозір","явір"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"(з|яв)ір$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -орел",examples:["орел"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"орел$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"а"}}],dative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"ові"}},{0:{action:"replace",value:"л"},1:{action:"replace",value:"у"}}],accusative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"а"}}],ablative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"ом"}}],locative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"ові"}}],vocative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -якір",examples:["якір"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"якір$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"я"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ю"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"я"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ю"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -бідь",examples:["лебідь"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:".бідь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -мінь",examples:["кремінь"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:".мінь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -сіль",examples:["кисіль"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"сіль$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -кінь",examples:["кінь"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"кінь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -куліш",examples:["куліш"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"куліш$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"еві"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"жіночий рід / на -(тверда приголосна)ька",examples:["ільницька","сумська"],wordClass:"adjective",gender:["feminine"],priority:4,application:["familyName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)ька$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -ова",examples:["іванова"],wordClass:"adjective",gender:["feminine"],priority:4,application:["familyName"],pattern:{find:"ова$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -іна",examples:["зеленкіна"],wordClass:"adjective",gender:["feminine"],priority:4,application:["familyName"],pattern:{find:"іна$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосна)єць",examples:["заєць"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)єць$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"й"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"й"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -віз",examples:["узвіз"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"віз$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ків",examples:["яків"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:".ків$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(к|р)іп",examples:["прокіп"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:".(к|р)іп$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -піп",examples:["прокіп"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"піп$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ніс",examples:["кривоніс"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"ніс$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -віл",examples:["рябовіл"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"віл$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ріг",examples:["пиріг"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"ріг$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"replace",value:"зі"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -хід",examples:["прихід"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"хід$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / жіночий рід / м'яка група / на -ель",examples:["нінель","мішель"],wordClass:"noun",gender:["feminine"],priority:4,application:["givenName"],pattern:{find:"ель$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"і"}}],dative:[{1:{action:"replace",value:"і"}}],accusative:[],ablative:[{0:{action:"replace",value:"лл"},1:{action:"replace",value:"ю"}}],locative:[{1:{action:"replace",value:"і"}}],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -ишин",examples:["ковалишин"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"ишин$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"им"}}],locative:[{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(аго|ово)",examples:["живаго"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"(аго|ово)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[],dative:[],accusative:[],ablative:[],locative:[],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -тер",examples:["вітер"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"тер$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"е"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -світ",examples:["світ"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"світ$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"чоловічі імена / на -(в|д)ір",examples:["дір","вір"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"(в|д)ір$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"чоловічий рід / на -кій (помилкова транслітерація)",examples:["дідківській"],wordClass:"adjective",gender:["masculine"],priority:3,application:["familyName"],pattern:{find:"кій$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ого"}}],dative:[{0:{action:"replace",value:"ому"}}],accusative:[{0:{action:"replace",value:"ого"}}],ablative:[{0:{action:"replace",value:"им"}}],locative:[{0:{action:"replace",value:"ому"}}],vocative:[]}},{description:"множина / на -их",examples:["седих"],wordClass:"adjective",gender:["masculine"],priority:3,application:[],pattern:{find:"их$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[],dative:[],accusative:[],ablative:[],locative:[],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -га",examples:["нога"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"га$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -кіш",examples:["розкіш"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"кіш$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -ьо",examples:["іваньо","кузьо"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"ьо$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"append",value:"м"}}],locative:[{0:{action:"replace",value:"ю"}}],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -е(в|н)",examples:["семен","лев"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"е(в|н)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -пес",examples:["пес"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"пес$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ко",examples:["марко"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"ко$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"а"}}],dative:[{0:{action:"replace",value:"у"}},{0:{action:"replace",value:"ові"}}],accusative:[{0:{action:"replace",value:"а"}}],ablative:[{0:{action:"replace",value:"ом"}}],locative:[{0:{action:"replace",value:"ові"}},{0:{action:"replace",value:"у"}}],vocative:[{0:{action:"replace",value:"у"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -ий",examples:["батий"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"ий$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"єм"}}],locative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -йо",examples:["йойо"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"йо$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"append",value:"ві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"append",value:"м"}}],locative:[{0:{action:"append",value:"ві"}}],vocative:[]}},{description:"перша відміна / чоловічий рід / тверда група / на -бо",examples:["голембо"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"бо$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[]}},{description:"чоловічий рід / на -ой, -ий",examples:["толстой","сухомлинський"],wordClass:"adjective",gender:["masculine"],priority:2,application:["familyName"],pattern:{find:"(ой|ий)$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ого"}}],dative:[{0:{action:"replace",value:"ому"}}],accusative:[{0:{action:"replace",value:"ого"}}],ablative:[{0:{action:"replace",value:"им"}}],locative:[{0:{action:"replace",value:"ому"}}],vocative:[]}},{description:"чоловічий рід / на -ій",examples:["заболотній"],wordClass:"adjective",gender:["masculine"],priority:2,application:["familyName"],pattern:{find:"ій$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ього"}}],dative:[{0:{action:"replace",value:"ьому"}}],accusative:[{0:{action:"replace",value:"ього"}}],ablative:[{0:{action:"replace",value:"ім"}}],locative:[{0:{action:"replace",value:"ьому"}}],vocative:[]}},{description:"жіночий рід / на -(тверда приголосна)а",examples:["зелена"],wordClass:"adjective",gender:["feminine"],priority:2,application:["familyName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)а$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -(тверда приголосна)я",examples:["задорожня"],wordClass:"adjective",gender:["feminine"],priority:2,application:["familyName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ьої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ьою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -ая",examples:["толстая"],wordClass:"adjective",gender:["feminine"],priority:2,application:["familyName"],pattern:{find:"ая$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"ую"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -яя",examples:["заболотняя"],wordClass:"adjective",gender:["feminine"],priority:2,application:["familyName"],pattern:{find:"яя$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ьої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ьою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"чоловічі по батькові та прізвища / на -ич",examples:["валерійович","риндич"],wordClass:"noun",gender:["masculine"],priority:2,application:["patronymicName","familyName"],pattern:{find:"ич$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"чоловічі по батькові та прізвища / на -іч",examples:["ілліч"],wordClass:"noun",gender:["masculine"],priority:2,application:["patronymicName","familyName"],pattern:{find:"іч$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"і"}},{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"жіночі по батькові / на -на",examples:["юріївна"],wordClass:"noun",gender:["feminine"],priority:2,application:["patronymicName"],pattern:{find:"на$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"}}]}},{description:"жіночі імена / на -(тверда приголосна)я",examples:["неля"],wordClass:"noun",gender:["feminine"],priority:2,application:["givenName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"чоловічі імена / на -ня",examples:["женя"],wordClass:"noun",gender:["masculine"],priority:2,application:["givenName"],pattern:{find:"ня$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група/ на -ов",examples:["павлов"],wordClass:"noun",gender:["masculine"],priority:2,application:["familyName"],pattern:{find:"ов$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"им"}}],locative:[{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ів",examples:["ковалів"],wordClass:"noun",gender:["masculine"],priority:2,application:["familyName"],pattern:{find:"ів$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"им"}}],locative:[{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -яр",examples:["скляр"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"яр$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"еві"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / жіночий рід / тверда, м'яка група / на -(о|ь|тверда приголосна)",examples:["шевченко"],wordClass:"noun",gender:["feminine"],priority:2,application:[],pattern:{find:"(о|ь|(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ))$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[],dative:[],accusative:[],ablative:[],locative:[],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -ок",examples:["сашок"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"ок$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}},{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -е(тверда_прилосона)",examples:["марек"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"е(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(тверда приголосна)я",examples:["гмиря"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий, жіночий роди / м'яка група / на -(голосна|ь|й)я",examples:["юлія","майя"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"((а|е|є|и|і|ї|о|у|ю|я)|ь|й)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ї"}}],dative:[{0:{action:"replace",value:"ї"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"єю"}}],locative:[{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"є"}}]}},{description:"друга відміна / чоловічий рід / мішана група / на -(дж|ж|ч|ш)",examples:["януш","джордж"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"(дж|ж|ч|ш)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"еві"}},{0:{action:"append",value:"і"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -к",examples:["кузик","мисяк"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"к$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -х",examples:["кожух"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"х$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"перша відміна / чоловічий, жіночий роди / тверда група / на -ха",examples:["старуха"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"ха$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"с"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"с"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}},{1:{action:"replace",value:"а"}}]}},{description:"перша відміна / чоловічий, жіночий роди / тверда група / на -ка",examples:["прилука"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"ка$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"ц"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ц"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}},{1:{action:"replace",value:"а"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -(тверда приголосна)о",examples:["петро","павло"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)о$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"а"}}],dative:[{0:{action:"replace",value:"у"}}],accusative:[{0:{action:"replace",value:"а"}}],ablative:[{0:{action:"replace",value:"ом"}}],locative:[{0:{action:"replace",value:"ові"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"перша відміна / жіночий рід / тверда група / на -(г|ґ)а",examples:["ольга"],wordClass:"noun",gender:["feminine"],priority:2,application:[],pattern:{find:"(г|ґ)а$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -ле",examples:["поле"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"ле$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"е"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[]}},{description:"перша відміна / чоловічий, жіночий роди / мішана група / на -а",examples:["мойша"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"(дж|ж|ч|ш|щ)а$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(тверда приголосна)",examples:["олександр"],wordClass:"noun",gender:["masculine"],priority:1,application:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"перша відміна / чоловічий, жіночий роди / тверда група / на -а",examples:["анна"],wordClass:"noun",gender:["masculine","feminine"],priority:1,application:[],pattern:{find:"а$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -й",examples:["валерій"],wordClass:"noun",gender:["masculine"],priority:1,application:[],pattern:{find:"й$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"єві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"єм"}}],locative:[{0:{action:"replace",value:"єві"}},{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -ь",examples:["петрунь"],wordClass:"noun",gender:["masculine"],priority:1,application:[],pattern:{find:"ь$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"жіночі імена / на -('|`)я",examples:["дар'я","мар'я"],wordClass:"noun",gender:["feminine"],priority:1,application:["givenName"],pattern:{find:"('|`)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ї"}}],dative:[{0:{action:"replace",value:"ї"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"єю"}}],locative:[{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"є"}}]}}],b=new class{constructor(e){this.declensionRules=[...e].sort(((e,t)=>t.priority-e.priority))}inflect(e,t){return a(this,void 0,void 0,(function*(){const[n]=this.declensionRules.filter((e=>e.gender.includes(t.gender))).filter((e=>!t.application||0===e.application.length||e.application.includes(t.application))).filter((t=>new RegExp(t.pattern.find,"gi").test(e))).filter((e=>!t.wordClass||e.wordClass===t.wordClass)).filter(((e,n,i)=>!t.customRuleFilter||t.customRuleFilter(e,n,i)));return null==n?e:new v(n).inflect(e,t.grammaticalCase)}))}}(y);class w{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class k{refCount(e){return x("refCount")}incRef(e){return x("incRef")}timerAvailable(){return!0}time(e){return x("time")}read(e){return x("read")}readSync(e){return x("readSync")}readToGPU(e,t){return x("readToGPU")}numDataIds(){return x("numDataIds")}disposeData(e,t){return x("disposeData")}write(e,t,n){return x("write")}move(e,t,n,i,a){return x("move")}createTensorFromGPUData(e,t,n){return x("createTensorFromGPUData")}memory(){return x("memory")}floatPrecision(){return x("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return x("dispose")}}function x(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}
|
|
11
11
|
/**
|
|
12
12
|
* @license
|
|
13
13
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
* See the License for the specific language governing permissions and
|
|
24
24
|
* limitations under the License.
|
|
25
25
|
* =============================================================================
|
|
26
|
-
*/function S(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,N(e,t,n)}function N(e,t,n){const i=e[t];e[t]=e[n],e[n]=i}function I(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function T(e,t,n=""){I(C(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function
|
|
26
|
+
*/function S(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,N(e,t,n)}function N(e,t,n){const i=e[t];e[t]=e[n],e[n]=i}function I(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function T(e,t,n=""){I(C(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function E(e){I(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function A(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function C(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function $(e){return e%1==0}function j(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function z(e,t){const n=t.length;return I((e=null==e?t.map(((e,t)=>t)):[].concat(e)).every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),I(e.every((e=>$(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function D(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else{if("bool"!==e)throw new Error(`Unknown data type ${e}`);n=new Uint8Array(t)}return n}function F(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function _(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function R(e){return"string"==typeof e||e instanceof String}function L(e){return"number"==typeof e}function M(e){return Array.isArray(e)?M(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":L(e)?"float32":R(e)?"string":"boolean"==typeof e?"bool":"float32"}function O(e){return!!(e&&e.constructor&&e.call&&e.apply)}function P(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let i=t-3;i>=0;--i)n[i]=n[i+1]*e[i+1];return n}function B(e,t,n,i=!1){const a=new Array;if(1===t.length){const s=t[0]*(i?2:1);for(let t=0;t<s;t++)a[t]=n[e+t]}else{const s=t[0],r=t.slice(1),o=r.reduce(((e,t)=>e*t))*(i?2:1);for(let t=0;t<s;t++)a[t]=B(e+t*o,r,n,i)}return a}function U(e,t,n=!1){if(0===e.length)return t[0];const i=e.reduce(((e,t)=>e*t))*(n?2:1);if(0===i)return[];if(i!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return B(0,e,t,n)}function W(e,t){const n=G(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function G(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function V(e){e.forEach((t=>{I(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function K(e,t,n){if(0===t)return 0;if(1===t)return e[0];let i=e[e.length-1];for(let t=0;t<e.length-1;++t)i+=n[t]*e[t];return i}function q(e,t,n){if(0===t)return[];if(1===t)return[e];const i=new Array(t);for(let t=0;t<i.length-1;++t)i[t]=Math.floor(e/n[t]),e-=i[t]*n[t];return i[i.length-1]=e,i}function H(e){return e&&e.then&&"function"==typeof e.then}
|
|
27
27
|
/**
|
|
28
28
|
* @license
|
|
29
29
|
* Copyright 2017 Google LLC. All Rights Reserved.
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
* See the License for the specific language governing permissions and
|
|
40
40
|
* limitations under the License.
|
|
41
41
|
* =============================================================================
|
|
42
|
-
*/const J="tfjsflags";class Z{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=Y,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(H(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(void 0===this.global||void 0===this.global.location||void 0===this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);if(J in e){e[J].split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}(t,n)}))}}}function Y(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("=")))),t}function Q(){return ee}let X,ee=null;function te(){if(null==X){let e;if("undefined"!=typeof window)e=window;else if("undefined"!=typeof global)e=global;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}X=e}return X}function ne(e,t){const n=function(){const e=te();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const i=t();return n.set(e,i),n.get(e)}}const ie="Add",ae="ArgMax",se="AvgPool",re="AvgPool3D",oe="BatchMatMul",le="BatchToSpaceND",ce="Cast",ue="ClipByValue",he="ComplexAbs",pe="Concat",de="Conv2D",me="Conv2DBackpropInput",fe="Conv3D",ge="Cosh",ve="Cumsum",ye="DepthwiseConv2dNative",be="RealDiv",we="Elu",ke="ExpandDims",xe="Floor",Se="FloorDiv",Ne="FusedBatchNorm",Ie="GatherV2",Te="GreaterEqual",
|
|
42
|
+
*/const J="tfjsflags";class Z{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=Y,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(H(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(void 0===this.global||void 0===this.global.location||void 0===this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);if(J in e){e[J].split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}(t,n)}))}}}function Y(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("=")))),t}function Q(){return ee}let X,ee=null;function te(){if(null==X){let e;if("undefined"!=typeof window)e=window;else if("undefined"!=typeof global)e=global;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}X=e}return X}function ne(e,t){const n=function(){const e=te();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const i=t();return n.set(e,i),n.get(e)}}const ie="Add",ae="ArgMax",se="AvgPool",re="AvgPool3D",oe="BatchMatMul",le="BatchToSpaceND",ce="Cast",ue="ClipByValue",he="ComplexAbs",pe="Concat",de="Conv2D",me="Conv2DBackpropInput",fe="Conv3D",ge="Cosh",ve="Cumsum",ye="DepthwiseConv2dNative",be="RealDiv",we="Elu",ke="ExpandDims",xe="Floor",Se="FloorDiv",Ne="FusedBatchNorm",Ie="GatherV2",Te="GreaterEqual",Ee="Identity",Ae="LeakyRelu",Ce="Log1p",$e="Maximum",je="MaxPool",ze="MaxPool3D",De="Mean",Fe="Minimum",_e="Multiply",Re="OnesLike",Le="OneHot",Me="Pack",Oe="PadV2",Pe="Prelu",Be="Relu",Ue="Reshape",We="ResizeNearestNeighbor",Ge="ResizeBilinear",Ve="Relu6",Ke="Reverse",qe="Round",He="Rsqrt",Je="Select",Ze="Selu",Ye="Slice",Qe="Sinh",Xe="Sigmoid",et="Softplus",tt="Sqrt",nt="Sum",it="SpaceToBatchND",at="SplitV",st="Softmax",rt="SquaredDifference",ot="Tanh",lt="Tile",ct="Transpose",ut="Unpack",ht="UnsortedSegmentSum",pt="ZerosLike",dt="Step",mt="_FusedMatMul",ft="FusedConv2D";
|
|
43
43
|
/**
|
|
44
44
|
* @license
|
|
45
45
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -88,7 +88,7 @@ function gt(...e){Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(...e
|
|
|
88
88
|
* See the License for the specific language governing permissions and
|
|
89
89
|
* limitations under the License.
|
|
90
90
|
* =============================================================================
|
|
91
|
-
*/function It(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=$t(e)),Q().getBool("DEBUG")&&function(e,t){for(let n=0;n<e.length;n++){const i=e[n];if(isNaN(i)||!isFinite(i))throw Error(`A tensor of type ${t} being uploaded contains ${i}.`)}}(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error(`Unknown data type ${t}`)}function Tt(){return Q().platform.now()}function
|
|
91
|
+
*/function It(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=$t(e)),Q().getBool("DEBUG")&&function(e,t){for(let n=0;n<e.length;n++){const i=e[n];if(isNaN(i)||!isFinite(i))throw Error(`A tensor of type ${t} being uploaded contains ${i}.`)}}(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error(`Unknown data type ${t}`)}function Tt(){return Q().platform.now()}function Et(e,t="utf-8"){return t=t||"utf-8",Q().platform.encode(e,t)}function At(e,t="utf-8"){return t=t||"utf-8",Q().platform.decode(e,t)}function Ct(e){return Q().platform.isTypedArray(e)}function $t(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||H(e)||null==e||Ct(e)&&n)t.push(e);else if(Array.isArray(e)||Ct(e))for(let i=0;i<e.length;++i)$t(e[i],t,n);else{let i=-1;for(const t of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(t)&&(i=Math.max(i,Number(t)));for(let a=0;a<=i;a++)$t(e[a],t,n)}return t}
|
|
92
92
|
/**
|
|
93
93
|
* @license
|
|
94
94
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -120,7 +120,7 @@ function gt(...e){Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(...e
|
|
|
120
120
|
* See the License for the specific language governing permissions and
|
|
121
121
|
* limitations under the License.
|
|
122
122
|
* =============================================================================
|
|
123
|
-
*/function Ft(e,t,n,i){const a=P(t),s=function(e,t,n,i){const a=
|
|
123
|
+
*/function Ft(e,t,n,i){const a=P(t),s=function(e,t,n,i){const a=A(t),s=i[i.length-1],r=new Array(s).fill(0),o=t.length,l="complex64"===n?Mt(e):e;if(o>1)for(let e=0;e<a/s;e++){const t=e*s;for(let e=0;e<s;e++)r[e]=Math.max(r[e],_t(l[t+e],0,n).length)}return r}(e,t,n,a),r=t.length,o=Lt(e,t,n,a,s),l=["Tensor"];return i&&(l.push(` dtype: ${n}`),l.push(` rank: ${r}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(o.map((e=>" "+e)).join("\n")),l.join("\n")}function _t(e,t,n){let i;return i=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:R(e)?`'${e}'`:"bool"===n?Rt(e):parseFloat(e.toFixed(7)).toString(),j(i,t)}function Rt(e){return 0===e?"false":"true"}function Lt(e,t,n,i,a,s=!0){const r="complex64"===n?2:1,o=t[0],l=t.length;if(0===l){if("complex64"===n){return[_t(Mt(e)[0],0,n)]}return"bool"===n?[Rt(e[0])]:[e[0].toString()]}if(1===l){if(o>20){const t=3*r;let i=Array.from(e.slice(0,t)),s=Array.from(e.slice((o-3)*r,o*r));return"complex64"===n&&(i=Mt(i),s=Mt(s)),["["+i.map(((e,t)=>_t(e,a[t],n))).join(", ")+", ..., "+s.map(((e,t)=>_t(e,a[o-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?Mt(e):Array.from(e)).map(((e,t)=>_t(e,a[t],n))).join(", ")+"]"]}const c=t.slice(1),u=i.slice(1),h=i[0]*r,p=[];if(o>20){for(let t=0;t<3;t++){const i=t*h,s=i+h;p.push(...Lt(e.slice(i,s),c,n,u,a,!1))}p.push("...");for(let t=o-3;t<o;t++){const i=t*h,s=i+h;p.push(...Lt(e.slice(i,s),c,n,u,a,t===o-1))}}else for(let t=0;t<o;t++){const i=t*h,s=i+h;p.push(...Lt(e.slice(i,s),c,n,u,a,t===o-1))}const d=2===l?",":"";p[0]="["+(o>0?p[0]+d:"");for(let e=1;e<p.length-1;e++)p[e]=" "+p[e]+d;let m=",\n";for(let e=2;e<l;e++)m+="\n";return p[p.length-1]=" "+p[p.length-1]+"]"+(s?"":m),p}function Mt(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}
|
|
124
124
|
/**
|
|
125
125
|
* @license
|
|
126
126
|
* Copyright 2017 Google LLC. All Rights Reserved.
|
|
@@ -136,7 +136,7 @@ function gt(...e){Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(...e
|
|
|
136
136
|
* See the License for the specific language governing permissions and
|
|
137
137
|
* limitations under the License.
|
|
138
138
|
* =============================================================================
|
|
139
|
-
*/class Ot{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=
|
|
139
|
+
*/class Ot{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=A(e),null!=n){const e=n.length;I(e===this.size,(()=>`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`))}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||F(t,this.size),this.strides=P(e)}set(e,...t){0===t.length&&(t=[0]),I(t.length===this.rank,(()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`));const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;t<e.length-1;++t)n+=this.strides[t]*e[t];return this.values[n]}locToIndex(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(0===this.rank)return[];if(1===this.rank)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Pt().makeTensor(this.values,this.shape,this.dtype)}}let Pt=null,Bt=null;class Ut{constructor(e,t,n,i){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=A(e),this.strides=P(e),this.dataId=n,this.id=i,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Bt.buffer(this.shape,this.dtype,e)}bufferSync(){return Bt.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return U(this.shape,e,"complex64"===this.dtype)}arraySync(){return U(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=Pt().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map((e=>At(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Pt().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Pt().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>At(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await Pt().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Pt().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Bt.print(this,e)}clone(){return this.throwIfDisposed(),Bt.clone(this)}toString(e=!1){return Ft(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Bt.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Pt().makeVariable(this,e,t,n)}}Object.defineProperty(Ut,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),ne("Tensor",(()=>Ut));class Wt extends Ut{constructor(e,t,n,i){super(e.shape,e.dtype,e.dataId,i),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!C(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Pt().disposeTensor(this),this.dataId=e.dataId,Pt().incRef(this,null)}dispose(){Pt().disposeVariable(this),this.isDisposedInternal=!0}}
|
|
140
140
|
/**
|
|
141
141
|
* @license
|
|
142
142
|
* Copyright 2017 Google LLC. All Rights Reserved.
|
|
@@ -185,7 +185,7 @@ var Gt,Vt,Kt,qt,Ht;Object.defineProperty(Wt,Symbol.hasInstance,{value:e=>e insta
|
|
|
185
185
|
* See the License for the specific language governing permissions and
|
|
186
186
|
* limitations under the License.
|
|
187
187
|
* =============================================================================
|
|
188
|
-
*/const a=e;for(const e in a){const i=a[e];n.has(i)||(n.add(i),Xt(i,t,n))}}function en(e){return null!=e.kernelName}class tn{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map((e=>e.name))))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class nn{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new tn}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void await this.setBackend(n)}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(null!=this.pendingBackendInit)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(gt(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new jt(this.backendInstance),!0}setupRegisteredKernels(){kt(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){kt(e).forEach((t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])}))}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof k||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,i=n.then((n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0))).catch((n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,gt(`Initialization of backend ${e} failed`),gt(n.stack||n.message)),!1)));return this.pendingBackendInit=i,{success:i,asyncInit:!0}}}catch(t){return gt(`Initialization of backend ${e} failed`),gt(t.stack||t.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:i,asyncInit:a}=this.initializeBackend(n);if(a||i)return{name:n,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),i=n.backend,a=this.readSync(t),s=i.refCount(t);i.disposeData(t,!0),n.backend=e,e.move(t,a,n.shape,n.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,i=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");i=e}return this.scopedRun((()=>this.startScope(i)),(()=>this.endScope(n)),(()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n)))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return nn.nextTensorId++}nextVariableId(){return nn.nextVariableId++}clone(e){const t=sn.runKernel(Ae,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return sn.runKernel(ce,t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=bt(e,this.backendName)))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const i=this.backend.numDataIds();let a=0;n.forEach((e=>{a+="complex64"===e.dtype?3:1}));const s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],r=i-t-a-s;if(r>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${r} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const i=this.isTapeOn(),a=this.state.numBytes,s=this.state.numTensors;let r,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=en(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(en(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const l=bt(t,this.backendName);I(null!=l,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),r=()=>{const e=this.backend.numDataIds();o=l.kernelFunc({inputs:a,attrs:s,backend:this.backend});const r=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,r);const c=r.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(i){const e=this.getTensorsForGradient(t,a,c);n=this.saveTensorsForBackwardMode(e)}return c}}else{const{forwardFunc:t}=e,a=e=>{i&&(n=e.map((e=>this.keep(this.clone(e)))))};r=()=>{const e=this.backend.numDataIds();o=this.tidy((()=>t(this.backend,a)));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:c,attrs:u}=e,h=en(e)?null:e.backwardsFunc;let p;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(p=this.profiler.profileKernel(l,c,(()=>r())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs):t=r()})),i&&this.addTapeNode(l,c,t,h,n,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map((e=>null!=c[e]?c[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const i=wt(e);if(null!=i){const e=i.inputsToSave||[],a=i.outputsToSave||[];let s;i.saveAllInputs?(I(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),s=Object.keys(t).map((e=>t[e]))):s=e.map((e=>t[e]));const r=n.filter(((e,t)=>a[t]));return s.concat(r)}return[]}makeTensor(e,t,n,i){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",i=i||this.backend;let a=e;"string"===n&&R(e[0])&&(a=e.map((e=>At(e))));const s=i.write(a,t,n),r=new Ut(t,n,s,this.nextTensorId());if(this.trackTensor(r,i),"string"===n){const e=this.state.tensorInfo.get(s),t=function(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}(a);this.state.numBytes+=t-e.bytes,e.bytes=t}return r}makeTensorFromDataId(e,t,n,i){const a={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(a,i)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:i,dtype:a}=e,s=new Ut(i,a,n,this.nextTensorId());return this.trackTensor(s,t),s}makeVariable(e,t=!0,n,i){n=n||this.nextVariableId().toString(),null!=i&&i!==e.dtype&&(e=e.cast(i));const a=new Wt(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*_(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Wt||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*_(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((e=>e.totalBytesSnapshot))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,i,a,s){const r={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:a},o=wt(e);null!=o&&(i=o.gradFunc),null!=i&&(r.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],i=G(e.size,e.dtype);return this.makeTensor(i,e.shape,e.dtype)}return e})),i(e.length>1?e:e[0],a,s))),this.state.activeTape.push(r)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=Qt(e),n=new Set(t.map((e=>e.id)));for(let e=0;e<this.state.activeScope.track.length;e++){const t=this.state.activeScope.track[e];t.kept||n.has(t.id)||t.dispose()}const i=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach((e=>{e.kept||e.scopeId!==i.id||this.track(e)}))}gradients(e,t,n,i=!1){if(I(t.length>0,(()=>"gradients() received an empty list of xs.")),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const a=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));I(a instanceof Ut,(()=>"The result y returned by f() must be a tensor."));const s=function(e,t,n){const i={},a={};for(let e=0;e<t.length;e++)i[t[e].id]=!0;for(let n=0;n<e.length;n++){const s=e[n],r=s.inputs;for(const e in r){const n=r[e];let o=!1;for(let e=0;e<t.length;e++)if(i[n.id]){s.outputs.forEach((e=>i[e.id]=!0)),o=!0,a[s.id]=!0;break}if(o)break}}const s={};s[n.id]=!0;const r={};for(let t=e.length-1;t>=0;t--){const n=e[t],i=n.inputs;for(let e=0;e<n.outputs.length;e++)if(s[n.outputs[e].id]){for(const e in i)s[i[e].id]=!0,r[n.id]=!0;break}}const o=[];for(let t=0;t<e.length;t++){const n=e[t];if(a[n.id]&&r[n.id]){const e={};for(const t in n.inputs){const a=n.inputs[t];i[a.id]&&(e[t]=a)}const t=Object.assign({},n);t.inputs=e,t.outputs=n.outputs,o.push(t)}}return o}(this.state.activeTape,t,a);if(!i&&0===s.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(()=>{const e={};e[a.id]=null==n?function(e){const t=W(E(e),"float32");return sn.makeTensor(t,e,"float32")}(a.shape):n,function(e,t,n,i){for(let a=t.length-1;a>=0;a--){const s=t[a],r=[];if(s.outputs.forEach((t=>{const n=e[t.id];null!=n?r.push(n):r.push(null)})),null==s.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);const o=s.gradient(r);for(const t in s.inputs){if(!(t in o))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(o)}.`);const a=n((()=>o[t]()));if("float32"!==a.dtype)throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${a.dtype}'`);const r=s.inputs[t];if(!C(a.shape,r.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${t}' has shape '${a.shape}', which does not match the shape of the input '${r.shape}'`);if(null==e[r.id])e[r.id]=a;else{const t=e[r.id];e[r.id]=i(t,a),t.dispose()}}}}
|
|
188
|
+
*/const a=e;for(const e in a){const i=a[e];n.has(i)||(n.add(i),Xt(i,t,n))}}function en(e){return null!=e.kernelName}class tn{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map((e=>e.name))))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class nn{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new tn}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void await this.setBackend(n)}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(null!=this.pendingBackendInit)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(gt(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new jt(this.backendInstance),!0}setupRegisteredKernels(){kt(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){kt(e).forEach((t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])}))}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof k||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,i=n.then((n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0))).catch((n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,gt(`Initialization of backend ${e} failed`),gt(n.stack||n.message)),!1)));return this.pendingBackendInit=i,{success:i,asyncInit:!0}}}catch(t){return gt(`Initialization of backend ${e} failed`),gt(t.stack||t.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:i,asyncInit:a}=this.initializeBackend(n);if(a||i)return{name:n,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),i=n.backend,a=this.readSync(t),s=i.refCount(t);i.disposeData(t,!0),n.backend=e,e.move(t,a,n.shape,n.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,i=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");i=e}return this.scopedRun((()=>this.startScope(i)),(()=>this.endScope(n)),(()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n)))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return nn.nextTensorId++}nextVariableId(){return nn.nextVariableId++}clone(e){const t=sn.runKernel(Ee,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return sn.runKernel(ce,t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=bt(e,this.backendName)))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const i=this.backend.numDataIds();let a=0;n.forEach((e=>{a+="complex64"===e.dtype?3:1}));const s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],r=i-t-a-s;if(r>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${r} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const i=this.isTapeOn(),a=this.state.numBytes,s=this.state.numTensors;let r,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=en(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(en(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const l=bt(t,this.backendName);I(null!=l,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),r=()=>{const e=this.backend.numDataIds();o=l.kernelFunc({inputs:a,attrs:s,backend:this.backend});const r=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,r);const c=r.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(i){const e=this.getTensorsForGradient(t,a,c);n=this.saveTensorsForBackwardMode(e)}return c}}else{const{forwardFunc:t}=e,a=e=>{i&&(n=e.map((e=>this.keep(this.clone(e)))))};r=()=>{const e=this.backend.numDataIds();o=this.tidy((()=>t(this.backend,a)));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:c,attrs:u}=e,h=en(e)?null:e.backwardsFunc;let p;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(p=this.profiler.profileKernel(l,c,(()=>r())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs):t=r()})),i&&this.addTapeNode(l,c,t,h,n,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map((e=>null!=c[e]?c[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const i=wt(e);if(null!=i){const e=i.inputsToSave||[],a=i.outputsToSave||[];let s;i.saveAllInputs?(I(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),s=Object.keys(t).map((e=>t[e]))):s=e.map((e=>t[e]));const r=n.filter(((e,t)=>a[t]));return s.concat(r)}return[]}makeTensor(e,t,n,i){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",i=i||this.backend;let a=e;"string"===n&&R(e[0])&&(a=e.map((e=>Et(e))));const s=i.write(a,t,n),r=new Ut(t,n,s,this.nextTensorId());if(this.trackTensor(r,i),"string"===n){const e=this.state.tensorInfo.get(s),t=function(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}(a);this.state.numBytes+=t-e.bytes,e.bytes=t}return r}makeTensorFromDataId(e,t,n,i){const a={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(a,i)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:i,dtype:a}=e,s=new Ut(i,a,n,this.nextTensorId());return this.trackTensor(s,t),s}makeVariable(e,t=!0,n,i){n=n||this.nextVariableId().toString(),null!=i&&i!==e.dtype&&(e=e.cast(i));const a=new Wt(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*_(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Wt||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*_(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((e=>e.totalBytesSnapshot))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,i,a,s){const r={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:a},o=wt(e);null!=o&&(i=o.gradFunc),null!=i&&(r.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],i=G(e.size,e.dtype);return this.makeTensor(i,e.shape,e.dtype)}return e})),i(e.length>1?e:e[0],a,s))),this.state.activeTape.push(r)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=Qt(e),n=new Set(t.map((e=>e.id)));for(let e=0;e<this.state.activeScope.track.length;e++){const t=this.state.activeScope.track[e];t.kept||n.has(t.id)||t.dispose()}const i=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach((e=>{e.kept||e.scopeId!==i.id||this.track(e)}))}gradients(e,t,n,i=!1){if(I(t.length>0,(()=>"gradients() received an empty list of xs.")),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const a=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));I(a instanceof Ut,(()=>"The result y returned by f() must be a tensor."));const s=function(e,t,n){const i={},a={};for(let e=0;e<t.length;e++)i[t[e].id]=!0;for(let n=0;n<e.length;n++){const s=e[n],r=s.inputs;for(const e in r){const n=r[e];let o=!1;for(let e=0;e<t.length;e++)if(i[n.id]){s.outputs.forEach((e=>i[e.id]=!0)),o=!0,a[s.id]=!0;break}if(o)break}}const s={};s[n.id]=!0;const r={};for(let t=e.length-1;t>=0;t--){const n=e[t],i=n.inputs;for(let e=0;e<n.outputs.length;e++)if(s[n.outputs[e].id]){for(const e in i)s[i[e].id]=!0,r[n.id]=!0;break}}const o=[];for(let t=0;t<e.length;t++){const n=e[t];if(a[n.id]&&r[n.id]){const e={};for(const t in n.inputs){const a=n.inputs[t];i[a.id]&&(e[t]=a)}const t=Object.assign({},n);t.inputs=e,t.outputs=n.outputs,o.push(t)}}return o}(this.state.activeTape,t,a);if(!i&&0===s.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(()=>{const e={};e[a.id]=null==n?function(e){const t=W(A(e),"float32");return sn.makeTensor(t,e,"float32")}(a.shape):n,function(e,t,n,i){for(let a=t.length-1;a>=0;a--){const s=t[a],r=[];if(s.outputs.forEach((t=>{const n=e[t.id];null!=n?r.push(n):r.push(null)})),null==s.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);const o=s.gradient(r);for(const t in s.inputs){if(!(t in o))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(o)}.`);const a=n((()=>o[t]()));if("float32"!==a.dtype)throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${a.dtype}'`);const r=s.inputs[t];if(!C(a.shape,r.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${t}' has shape '${a.shape}', which does not match the shape of the input '${r.shape}'`);if(null==e[r.id])e[r.id]=a;else{const t=e[r.id];e[r.id]=i(t,a),t.dispose()}}}}
|
|
189
189
|
/**
|
|
190
190
|
* @license
|
|
191
191
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -315,7 +315,7 @@ function ln(e,t){let n=e;if(Ct(e))return"string"===t?[]:[e.length];if("object"==
|
|
|
315
315
|
* See the License for the specific language governing permissions and
|
|
316
316
|
* limitations under the License.
|
|
317
317
|
* =============================================================================
|
|
318
|
-
*/function fn(e,t,n,i){if(null==i)i=M(e);else if("complex64"===i)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if("object"==typeof e&&("texture"in e||"buffer"in e&&!(e.buffer instanceof ArrayBuffer))){if("float32"!==i&&"int32"!==i)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${i}.`);return sn.backend.createTensorFromGPUData(e,t||n,i)}if(!Ct(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){V(t);const e=
|
|
318
|
+
*/function fn(e,t,n,i){if(null==i)i=M(e);else if("complex64"===i)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if("object"==typeof e&&("texture"in e||"buffer"in e&&!(e.buffer instanceof ArrayBuffer))){if("float32"!==i&&"int32"!==i)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${i}.`);return sn.backend.createTensorFromGPUData(e,t||n,i)}if(!Ct(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){V(t);const e=A(t),i=A(n);I(e===i,(()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${i}`));for(let e=0;e<n.length;++e){const i=n[e],a=e!==n.length-1||i!==A(t.slice(e));I(n[e]===t[e]||!a,(()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return Ct(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==i?It(e,i):$t(e,[],!0),sn.makeTensor(e,t,i)}
|
|
319
319
|
/**
|
|
320
320
|
* @license
|
|
321
321
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -379,7 +379,7 @@ function ln(e,t){let n=e;if(Ct(e))return"string"===t?[]:[e.length];if("object"==
|
|
|
379
379
|
* See the License for the specific language governing permissions and
|
|
380
380
|
* limitations under the License.
|
|
381
381
|
* =============================================================================
|
|
382
|
-
*/class Tn{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==Tn.instance&&(Tn.instance=new Tn),Tn.instance}static registerSaveRouter(e){Tn.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Tn.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Tn.getHandlers(e,"save")}static getLoadHandlers(e,t){return Tn.getHandlers(e,"load",t)}static getHandlers(e,t,n){const i=[];return("load"===t?Tn.getInstance().loadRouters:Tn.getInstance().saveRouters).forEach((t=>{const a=t(e,n);null!==a&&i.push(a)})),i}}const
|
|
382
|
+
*/class Tn{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==Tn.instance&&(Tn.instance=new Tn),Tn.instance}static registerSaveRouter(e){Tn.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Tn.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Tn.getHandlers(e,"save")}static getLoadHandlers(e,t){return Tn.getHandlers(e,"load",t)}static getHandlers(e,t,n){const i=[];return("load"===t?Tn.getInstance().loadRouters:Tn.getInstance().saveRouters).forEach((t=>{const a=t(e,n);null!==a&&i.push(a)})),i}}const En="tensorflowjs",An="models_store",Cn="model_info_store";function $n(){if(!Q().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function jn(e){const t=e.result;t.createObjectStore(An,{keyPath:"modelPath"}),t.createObjectStore(Cn,{keyPath:"modelPath"})}class zn{constructor(e){if(this.indexedDB=$n(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise(((e,n)=>{const i=this.indexedDB.open(En,1);i.onupgradeneeded=()=>jn(i),i.onsuccess=()=>{const a=i.result;if(null==t){const t=a.transaction(An,"readonly"),i=t.objectStore(An).get(this.modelPath);i.onsuccess=()=>{if(null==i.result)return a.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(i.result.modelArtifacts)},i.onerror=e=>(a.close(),n(i.error)),t.oncomplete=()=>a.close()}else{const i=Nn(t),s=a.transaction(Cn,"readwrite");let r=s.objectStore(Cn);const o=r.put({modelPath:this.modelPath,modelArtifactsInfo:i});let l;o.onsuccess=()=>{l=a.transaction(An,"readwrite");const o=l.objectStore(An).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});o.onsuccess=()=>e({modelArtifactsInfo:i}),o.onerror=e=>{r=s.objectStore(Cn);const t=r.delete(this.modelPath);t.onsuccess=()=>(a.close(),n(o.error)),t.onerror=e=>(a.close(),n(o.error))}},o.onerror=e=>(a.close(),n(o.error)),s.oncomplete=()=>{null==l?a.close():l.oncomplete=()=>a.close()}}},i.onerror=e=>n(i.error)}))}}zn.URL_SCHEME="indexeddb://";const Dn=e=>{return Q().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(zn.URL_SCHEME)?(t=e.slice(zn.URL_SCHEME.length),new zn(t)):null;var t};Tn.registerSaveRouter(Dn),Tn.registerLoadRouter(Dn);class Fn{constructor(){this.indexedDB=$n()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(En,1);n.onupgradeneeded=()=>jn(n),n.onsuccess=()=>{const i=n.result,a=i.transaction(Cn,"readonly"),s=a.objectStore(Cn).getAll();s.onsuccess=()=>{const t={};for(const e of s.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},s.onerror=e=>(i.close(),t(s.error)),a.oncomplete=()=>i.close()},n.onerror=e=>t(n.error)}))}async removeModel(e){var t;return e=(t=e).startsWith(zn.URL_SCHEME)?t.slice(zn.URL_SCHEME.length):t,new Promise(((t,n)=>{const i=this.indexedDB.open(En,1);i.onupgradeneeded=()=>jn(i),i.onsuccess=()=>{const a=i.result,s=a.transaction(Cn,"readwrite"),r=s.objectStore(Cn),o=r.get(e);let l;o.onsuccess=()=>{if(null==o.result)return a.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const i=r.delete(e),s=()=>{l=a.transaction(An,"readwrite");const i=l.objectStore(An).delete(e);i.onsuccess=()=>t(o.result.modelArtifactsInfo),i.onerror=e=>n(o.error)};i.onsuccess=s,i.onerror=e=>(s(),a.close(),n(o.error))}},o.onerror=e=>(a.close(),n(o.error)),s.oncomplete=()=>{null==l?a.close():l.oncomplete=()=>a.close()}},i.onerror=e=>n(i.error)}))}}
|
|
383
383
|
/**
|
|
384
384
|
* @license
|
|
385
385
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -764,7 +764,7 @@ function(e){const t={input:hn(e,"input","imag")};return sn.runKernel("Imag",t)}}
|
|
|
764
764
|
* See the License for the specific language governing permissions and
|
|
765
765
|
* limitations under the License.
|
|
766
766
|
* =============================================================================
|
|
767
|
-
*/function
|
|
767
|
+
*/function Ei(e,t,n,i,a,s,r=!1,o="channelsLast"){let[l,c,u,h]=[-1,-1,-1,-1];if("channelsLast"===o)[l,c,u,h]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[l,h,c,u]=e}const[p,d,,m]=t,[f,g]=Ai(n),[v,y]=Ai(i),b=Ci(p,v),w=Ci(d,y),{padInfo:k,outHeight:x,outWidth:S}=function(e,t,n,i,a,s,r,o,l){let c,u,h;if("number"==typeof e){c={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const a=function(e,t,n,i,a){null==i&&(i=function(e,t,n,i=1){const a=Ci(t,i);return Math.floor((e[0]*(n-1)-n+a)/2)}(e,t,n));const s=e[0],r=e[1],o=$i((s-t+2*i)/n+1,a),l=$i((r-t+2*i)/n+1,a);return[o,l]}([t,n],s,i,e,o);u=a[0],h=a[1]}else if("same"===e){u=Math.ceil(t/i),h=Math.ceil(n/a);const e=Math.max(0,(u-1)*i+s-t),o=Math.max(0,(h-1)*a+r-n),l=Math.floor(e/2),p=e-l,d=Math.floor(o/2);c={top:l,bottom:p,left:d,right:o-d,type:"SAME"}}else if("valid"===e)c={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-s+1)/i),h=Math.ceil((n-r+1)/a);else{if("object"!=typeof e)throw Error(`Unknown padding parameter: ${e}`);{const p="channelsLast"===l?e[1][0]:e[2][0],d="channelsLast"===l?e[1][1]:e[2][1],m="channelsLast"===l?e[2][0]:e[3][0],f="channelsLast"===l?e[2][1]:e[3][1];c={top:p,bottom:d,left:m,right:f,type:0===p&&0===d&&0===m&&0===f?"VALID":"EXPLICIT"},u=$i((t-s+p+d)/i+1,o),h=$i((n-r+m+f)/a+1,o)}}return{padInfo:c,outHeight:u,outWidth:h}}(a,c,u,f,g,b,w,s,o),N=r?m*h:m;let I;return"channelsFirst"===o?I=[l,N,x,S]:"channelsLast"===o&&(I=[l,x,S,N]),{batchSize:l,dataFormat:o,inHeight:c,inWidth:u,inChannels:h,outHeight:x,outWidth:S,outChannels:N,padInfo:k,strideHeight:f,strideWidth:g,filterHeight:p,filterWidth:d,effectiveFilterHeight:b,effectiveFilterWidth:w,dilationHeight:v,dilationWidth:y,inShape:e,outShape:I,filterShape:t}}function Ai(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function Ci(e,t){return t<=1?e:e+(e-1)*(t-1)}function $i(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function ji(e){const[t,n,i]=Ai(e);return 1===t&&1===n&&1===i}function zi(e,t){return ji(e)||ji(t)}function Di(e){return Ai(e).every((e=>e>0))}function Fi(e,t,n){if(null!=n){if("string"==typeof t)throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if("number"==typeof t)I($(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`));else{if("object"!=typeof t)throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);t.forEach((t=>{t.forEach((t=>{I($(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}
|
|
768
768
|
/**
|
|
769
769
|
* @license
|
|
770
770
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -828,7 +828,7 @@ function(e){const t={input:hn(e,"input","imag")};return sn.runKernel("Imag",t)}}
|
|
|
828
828
|
* See the License for the specific language governing permissions and
|
|
829
829
|
* limitations under the License.
|
|
830
830
|
* =============================================================================
|
|
831
|
-
*/const Mi=dn({clone_:function(e){const t={x:hn(e,"x","clone","string_or_numeric")};return sn.runKernel(
|
|
831
|
+
*/const Mi=dn({clone_:function(e){const t={x:hn(e,"x","clone","string_or_numeric")};return sn.runKernel(Ee,t)}});
|
|
832
832
|
/**
|
|
833
833
|
* @license
|
|
834
834
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -1294,7 +1294,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
|
|
|
1294
1294
|
* See the License for the specific language governing permissions and
|
|
1295
1295
|
* limitations under the License.
|
|
1296
1296
|
* =============================================================================
|
|
1297
|
-
*/const
|
|
1297
|
+
*/const Ea=dn({pow_:function(e,t){let n=hn(e,"base","pow"),i=hn(t,"exp","pow");[n,i]=Yt(n,i);const a={a:n,b:i};return sn.runKernel("Pow",a)}});
|
|
1298
1298
|
/**
|
|
1299
1299
|
* @license
|
|
1300
1300
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -1310,7 +1310,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
|
|
|
1310
1310
|
* See the License for the specific language governing permissions and
|
|
1311
1311
|
* limitations under the License.
|
|
1312
1312
|
* =============================================================================
|
|
1313
|
-
*/function
|
|
1313
|
+
*/function Aa(e,t){if((Ct(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&Ct(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return fn(e,[],[],t)}
|
|
1314
1314
|
/**
|
|
1315
1315
|
* @license
|
|
1316
1316
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -1374,7 +1374,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
|
|
|
1374
1374
|
* See the License for the specific language governing permissions and
|
|
1375
1375
|
* limitations under the License.
|
|
1376
1376
|
* =============================================================================
|
|
1377
|
-
*/function za(e,t,n=null){if(0===e.rank)return Si(e);if(1!==e.rank&&null===n)return za(_i(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return ja(Si(e),n);if(t===1/0)return Ia(Si(e),n);if(t===-1/0)return Ta(Si(e),n);if("euclidean"===t||2===t)return Ca(ja(
|
|
1377
|
+
*/function za(e,t,n=null){if(0===e.rank)return Si(e);if(1!==e.rank&&null===n)return za(_i(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return ja(Si(e),n);if(t===1/0)return Ia(Si(e),n);if(t===-1/0)return Ta(Si(e),n);if("euclidean"===t||2===t)return Ca(ja(Ea(Si(e),Aa(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return Ia(ja(Si(e),n[0]),n[1]-1);if(t===1/0)return Ia(ja(Si(e),n[1]),n[0]);if(t===-1/0)return Ta(ja(Si(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return Ca(ja($a(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Da=dn({norm_:function(e,t="euclidean",n=null,i=!1){const a=za(e=hn(e,"x","norm"),t,n);let s=a.shape;if(i){const t=z(n,e.shape);s=xa(a.shape,t)}return _i(a,s)}});
|
|
1378
1378
|
/**
|
|
1379
1379
|
* @license
|
|
1380
1380
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -1518,7 +1518,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
|
|
|
1518
1518
|
* See the License for the specific language governing permissions and
|
|
1519
1519
|
* limitations under the License.
|
|
1520
1520
|
* =============================================================================
|
|
1521
|
-
*/const Ua=dn({leakyRelu_:function(e,t=.2){const n={x:hn(e,"x","leakyRelu")},i={alpha:t};return sn.runKernel(
|
|
1521
|
+
*/const Ua=dn({leakyRelu_:function(e,t=.2){const n={x:hn(e,"x","leakyRelu")},i={alpha:t};return sn.runKernel(Ae,n,i)}});
|
|
1522
1522
|
/**
|
|
1523
1523
|
* @license
|
|
1524
1524
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -1775,7 +1775,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
|
|
|
1775
1775
|
* See the License for the specific language governing permissions and
|
|
1776
1776
|
* limitations under the License.
|
|
1777
1777
|
* =============================================================================
|
|
1778
|
-
*/function is(e,t="float32"){if(V(e),"complex64"===t){const t=is(e,"float32"),n=is(e,"float32");return mn(t,n)}const n=G(
|
|
1778
|
+
*/function is(e,t="float32"){if(V(e),"complex64"===t){const t=is(e,"float32"),n=is(e,"float32");return mn(t,n)}const n=G(A(e),t);return sn.makeTensor(n,e,t)}
|
|
1779
1779
|
/**
|
|
1780
1780
|
* @license
|
|
1781
1781
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -1791,7 +1791,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
|
|
|
1791
1791
|
* See the License for the specific language governing permissions and
|
|
1792
1792
|
* limitations under the License.
|
|
1793
1793
|
* =============================================================================
|
|
1794
|
-
*/function as(e,t="float32"){if(V(e),"complex64"===t){const t=as(e,"float32"),n=is(e,"float32");return mn(t,n)}const n=W(
|
|
1794
|
+
*/function as(e,t="float32"){if(V(e),"complex64"===t){const t=as(e,"float32"),n=is(e,"float32");return mn(t,n)}const n=W(A(e),t);return sn.makeTensor(n,e,t)}
|
|
1795
1795
|
/**
|
|
1796
1796
|
* @license
|
|
1797
1797
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -1999,7 +1999,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
|
|
|
1999
1999
|
* See the License for the specific language governing permissions and
|
|
2000
2000
|
* limitations under the License.
|
|
2001
2001
|
* =============================================================================
|
|
2002
|
-
*/const
|
|
2002
|
+
*/const Es=dn({relu_:function(e){const t={x:hn(e,"x","relu")};return sn.runKernel(Be,t)}});
|
|
2003
2003
|
/**
|
|
2004
2004
|
* @license
|
|
2005
2005
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -2015,7 +2015,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
|
|
|
2015
2015
|
* See the License for the specific language governing permissions and
|
|
2016
2016
|
* limitations under the License.
|
|
2017
2017
|
* =============================================================================
|
|
2018
|
-
*/const
|
|
2018
|
+
*/const As=dn({relu6_:function(e){const t={x:hn(e,"x","relu6")};return sn.runKernel(Ve,t)}});
|
|
2019
2019
|
/**
|
|
2020
2020
|
* @license
|
|
2021
2021
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -2305,7 +2305,7 @@ function(e,t){const n=hn(e,"x","squeeze","string_or_numeric");return _i(n,functi
|
|
|
2305
2305
|
* See the License for the specific language governing permissions and
|
|
2306
2306
|
* limitations under the License.
|
|
2307
2307
|
* =============================================================================
|
|
2308
|
-
*/function Vs(e,t){
|
|
2308
|
+
*/function Vs(e,t){E(e);const n=ln(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return fn(e,null,n,t)}
|
|
2309
2309
|
/**
|
|
2310
2310
|
* @license
|
|
2311
2311
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -2321,7 +2321,7 @@ function(e,t){const n=hn(e,"x","squeeze","string_or_numeric");return _i(n,functi
|
|
|
2321
2321
|
* See the License for the specific language governing permissions and
|
|
2322
2322
|
* limitations under the License.
|
|
2323
2323
|
* =============================================================================
|
|
2324
|
-
*/function Ks(e,t,n){if(
|
|
2324
|
+
*/function Ks(e,t,n){if(E(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const i=ln(e,n);if(2!==i.length&&1!==i.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===i.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return fn(e,t,i,n)}
|
|
2325
2325
|
/**
|
|
2326
2326
|
* @license
|
|
2327
2327
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -2468,7 +2468,7 @@ function(e,t,n,i,a,s="NHWC",r){let o=e;3===e.rank&&(o=_i(e,[1,e.shape[0],e.shape
|
|
|
2468
2468
|
* See the License for the specific language governing permissions and
|
|
2469
2469
|
* limitations under the License.
|
|
2470
2470
|
* =============================================================================
|
|
2471
|
-
*/function Qs(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return xi(e,Gs(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Xs(e,t){let n=t;const i=di(e.shape,t.shape);return i.length>0&&(n=ja(n,i)),_i(n,e.shape)}function er(e,t,n,i){if("linear"===t)return e;if("relu"===t)return
|
|
2471
|
+
*/function Qs(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return xi(e,Gs(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Xs(e,t){let n=t;const i=di(e.shape,t.shape);return i.length>0&&(n=ja(n,i)),_i(n,e.shape)}function er(e,t,n,i){if("linear"===t)return e;if("relu"===t)return Es(e);if("elu"===t)return ba(e);if("relu6"===t)return As(e);if("prelu"===t)return hs(e,n);if("leakyrelu"===t)return Ua(e,i);if("sigmoid"===t)return Pi(e);throw new Error(`Unknown fused activation ${t}.`)}const tr=(e,t)=>!(e>0)||"linear"===t;
|
|
2472
2472
|
/**
|
|
2473
2473
|
* @license
|
|
2474
2474
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
@@ -2484,7 +2484,7 @@ function(e,t,n,i,a,s="NHWC",r){let o=e;3===e.rank&&(o=_i(e,[1,e.shape[0],e.shape
|
|
|
2484
2484
|
* See the License for the specific language governing permissions and
|
|
2485
2485
|
* limitations under the License.
|
|
2486
2486
|
* =============================================================================
|
|
2487
|
-
*/const nr=dn({fusedConv2d_:function({x:e,filter:t,strides:n,pad:i,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:r,bias:o,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(l=l||"linear",!1===tr(sn.state.gradientDepth,l)){I("NHWC"===a,(()=>`Error in fused conv2d: got dataFormat of ${a} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`));let h=ia(e,t,n,i,a,s,r);return null!=o&&(h=bi(h,o)),er(h,l,c,u)}const h=hn(e,"x","conv2d","float32"),p=hn(t,"filter","conv2d","float32");let d=h,m=!1;3===h.rank&&(m=!0,d=_i(h,[1,h.shape[0],h.shape[1],h.shape[2]])),I(4===d.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`)),I(4===p.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`)),Fi("fused conv2d",i,r);const f="NHWC"===a?d.shape[3]:d.shape[1];I(p.shape[2]===f,(()=>`Error in conv2d: depth of input (${f}) must match input depth for filter ${p.shape[2]}.`)),I(zi(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`));const g=
|
|
2487
|
+
*/const nr=dn({fusedConv2d_:function({x:e,filter:t,strides:n,pad:i,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:r,bias:o,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(l=l||"linear",!1===tr(sn.state.gradientDepth,l)){I("NHWC"===a,(()=>`Error in fused conv2d: got dataFormat of ${a} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`));let h=ia(e,t,n,i,a,s,r);return null!=o&&(h=bi(h,o)),er(h,l,c,u)}const h=hn(e,"x","conv2d","float32"),p=hn(t,"filter","conv2d","float32");let d=h,m=!1;3===h.rank&&(m=!0,d=_i(h,[1,h.shape[0],h.shape[1],h.shape[2]])),I(4===d.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`)),I(4===p.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`)),Fi("fused conv2d",i,r);const f="NHWC"===a?d.shape[3]:d.shape[1];I(p.shape[2]===f,(()=>`Error in conv2d: depth of input (${f}) must match input depth for filter ${p.shape[2]}.`)),I(zi(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`));const g=Ei(d.shape,p.shape,n,s,i,r);let v,y;if(null!=o&&(v=hn(o,"bias","fused conv2d"),[v]=Yt(v,h),"NHWC"===a?mi(g.outShape,v.shape):(I(v.shape.length<=1,(()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${v.shape.length}.`)),I(0===v.shape.length||v.shape[0]===g.outChannels||1===v.shape[0],(()=>`Error in fused conv2d: bias shape (${v.shape}) is not compatible with the number of output channels (${g.outChannels})`)))),null!=c){const e=c.shape;if(I(e.length<=1||3===e.length,(()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${e.length}.`)),1===e.length)I(1===e[0]||e[0]===g.outChannels,(()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${g.outChannels}).`));else if(3===e.length)try{mi(e,g.outShape)}catch(t){const n=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(n)}y=hn(c,"prelu weights","fused conv2d")}const b=(e,t)=>{I("NHWC"===a,(()=>`Error in gradient of fused conv2D: got dataFormat of ${a} but only NHWC is currently supported.`));const[r,o,c,u]=t,h=Qs(e,c,l);I(ji(s),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`));const p=[sa(o.shape,h,r,n,i),Ys(o,h,r.shape,n,i)];if(null!=u){const e=Xs(u,h);p.push(e)}return p},w={x:d,filter:p,bias:v,preluActivationWeights:y},k={strides:n,pad:i,dataFormat:a,dilations:s,dimRoundingMode:r,activation:l,leakyreluAlpha:u};if(null==o){const e=qa(((e,t,n)=>{let i=sn.runKernel(ft,w,k);return n([t,e,i]),m&&(i=_i(i,[i.shape[1],i.shape[2],i.shape[3]])),{value:i,gradFunc:b}}));return e(d,p)}{const e=qa(((e,t,n,i)=>{let a=sn.runKernel(ft,w,k);return i([t,e,a,n]),m&&(a=_i(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:b}}));return e(d,p,v)}}});
|
|
2488
2488
|
/**
|
|
2489
2489
|
* @license
|
|
2490
2490
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -2532,7 +2532,7 @@ function(e,t,n,i,a,s="NHWC",r){let o=e;3===e.rank&&(o=_i(e,[1,e.shape[0],e.shape
|
|
|
2532
2532
|
* See the License for the specific language governing permissions and
|
|
2533
2533
|
* limitations under the License.
|
|
2534
2534
|
* =============================================================================
|
|
2535
|
-
*/const sr=dn({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:i=!1,bias:a,activation:s="linear",preluActivationWeights:r,leakyreluAlpha:o=.2}){if(!1===tr(sn.state.gradientDepth,s)){let l=ti(e,t,n,i);return null!=a&&(l=bi(l,a)),er(l,s,r,o)}let l=hn(e,"a","fused matMul"),c=hn(t,"b","fused matMul");[l,c]=Yt(l,c);const u=n?l.shape[l.rank-2]:l.shape[l.rank-1],h=i?c.shape[c.rank-1]:c.shape[c.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],d=i?c.shape[c.rank-2]:c.shape[c.rank-1],m=l.shape.slice(0,-2),f=c.shape.slice(0,-2),g=
|
|
2535
|
+
*/const sr=dn({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:i=!1,bias:a,activation:s="linear",preluActivationWeights:r,leakyreluAlpha:o=.2}){if(!1===tr(sn.state.gradientDepth,s)){let l=ti(e,t,n,i);return null!=a&&(l=bi(l,a)),er(l,s,r,o)}let l=hn(e,"a","fused matMul"),c=hn(t,"b","fused matMul");[l,c]=Yt(l,c);const u=n?l.shape[l.rank-2]:l.shape[l.rank-1],h=i?c.shape[c.rank-1]:c.shape[c.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],d=i?c.shape[c.rank-2]:c.shape[c.rank-1],m=l.shape.slice(0,-2),f=c.shape.slice(0,-2),g=A(m),v=A(f);I(u===h,(()=>`Error in fused matMul: inner shapes (${u}) and (${h}) of Tensors with shapes ${l.shape} and ${c.shape} and transposeA=${n} and transposeB=${i} must match.`));const y=mi(l.shape.slice(0,-2),c.shape.slice(0,-2)).concat([p,d]),b=_i(l,n?[g,u,p]:[g,p,u]),w=_i(c,i?[v,d,h]:[v,h,d]);let k,x;null!=a&&(k=hn(a,"bias","fused matMul"),[k]=Yt(k,l),mi(y,k.shape)),null!=r&&(x=hn(r,"prelu weights","fused matMul"));const S=(e,t)=>{const[r,o,l,c]=t,u=Qs(_i(e,l.shape),l,s);let h,p;if(n||i?!n&&i?(h=ti(u,o,!1,!1),p=ti(u,r,!0,!1)):n&&!i?(h=ti(o,u,!1,!0),p=ti(r,u,!1,!1)):(h=ti(o,u,!0,!0),p=ti(u,r,!0,!0)):(h=ti(u,o,!1,!0),p=ti(r,u,!0,!1)),null!=a){return[h,p,Xs(c,u)]}return[h,p]},N={a:b,b:w,bias:k,preluActivationWeights:x},T={transposeA:n,transposeB:i,activation:s,leakyreluAlpha:o};if(null==a){const e=qa(((e,t,n)=>{const i=sn.runKernel(mt,N,T);return n([e,t,i]),{value:_i(i,y),gradFunc:S}}));return e(b,w)}{const e=qa(((e,t,n,i)=>{const a=sn.runKernel(mt,N,T);return i([e,t,a,n]),{value:_i(a,y),gradFunc:S}}));return e(b,w,k)}}});
|
|
2536
2536
|
/**
|
|
2537
2537
|
* @license
|
|
2538
2538
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
@@ -2757,7 +2757,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
|
|
|
2757
2757
|
* See the License for the specific language governing permissions and
|
|
2758
2758
|
* limitations under the License.
|
|
2759
2759
|
* =============================================================================
|
|
2760
|
-
*/const xr=async function(e,t,n,i=.5,a=Number.NEGATIVE_INFINITY,s=!1){const r=hn(e,"boxes","nonMaxSuppressionAsync"),o=hn(t,"scores","nonMaxSuppressionAsync"),l=ur(r,o,n,i,a,null),c=l.maxOutputSize,u=l.iouThreshold,h=l.scoreThreshold,[p,d]=await Promise.all([r.data(),o.data()]),{selectedIndices:m,validOutputs:f}=function(e,t,n,i,a,s){return mr(e,t,n,i,a,0,!1,s,!0)}(p,d,c,u,h,s);return r!==e&&r.dispose(),o!==t&&o.dispose(),{selectedIndices:Vs(m,"int32"),validOutputs:
|
|
2760
|
+
*/const xr=async function(e,t,n,i=.5,a=Number.NEGATIVE_INFINITY,s=!1){const r=hn(e,"boxes","nonMaxSuppressionAsync"),o=hn(t,"scores","nonMaxSuppressionAsync"),l=ur(r,o,n,i,a,null),c=l.maxOutputSize,u=l.iouThreshold,h=l.scoreThreshold,[p,d]=await Promise.all([r.data(),o.data()]),{selectedIndices:m,validOutputs:f}=function(e,t,n,i,a,s){return mr(e,t,n,i,a,0,!1,s,!0)}(p,d,c,u,h,s);return r!==e&&r.dispose(),o!==t&&o.dispose(),{selectedIndices:Vs(m,"int32"),validOutputs:Aa(f,"int32")}};
|
|
2761
2761
|
/**
|
|
2762
2762
|
* @license
|
|
2763
2763
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -2837,7 +2837,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
|
|
|
2837
2837
|
* See the License for the specific language governing permissions and
|
|
2838
2838
|
* limitations under the License.
|
|
2839
2839
|
* =============================================================================
|
|
2840
|
-
*/const
|
|
2840
|
+
*/const Er=dn({bandPart_:function(e,t,n){I(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),I(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`));const i=hn(e,"a","bandPart");I(i.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${i.rank}.`));const a=i.shape,[s,r]=i.shape.slice(-2);if(!(t<=s))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`);if(!(n<=r))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${r}).`);t<0&&(t=s),n<0&&(n=r);const o=_i(Ts(0,s,1,"int32"),[-1,1]),l=Ts(0,r,1,"int32"),c=Ja(o,l),u=Ya(Ga(c,Aa(+t,"int32")),Ba(c,Aa(-n,"int32"))),h=is([s,r],i.dtype);return _i(Ws(Js(_i(i,[-1,s,r])).map((e=>va(u,e,h)))),a)}});
|
|
2841
2841
|
/**
|
|
2842
2842
|
* @license
|
|
2843
2843
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -2853,7 +2853,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
|
|
|
2853
2853
|
* See the License for the specific language governing permissions and
|
|
2854
2854
|
* limitations under the License.
|
|
2855
2855
|
* =============================================================================
|
|
2856
|
-
*/const
|
|
2856
|
+
*/const Ar=dn({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,I(null!=e&&e.length>0,(()=>"Gram-Schmidt process: input must not be null, undefined, or empty"));const n=e[0].shape[0];for(let t=1;t<e.length;++t)I(e[t].shape[0]===n,(()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`))}else t=!0,e=Bs(e,e.shape[0],0).map((e=>Us(e,[0])));I(e.length<=e[0].shape[0],(()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`));const n=[],i=e;for(let t=0;t<e.length;++t)n.push(sn.tidy((()=>{let e=i[t];if(t>0)for(let i=0;i<t;++i){const t=xi(ja(xi(n[i],e)),n[i]);e=Ja(e,t)}return ki(e,Da(e,"euclidean"))})));return t?Ws(n,0):n}});
|
|
2857
2857
|
/**
|
|
2858
2858
|
* @license
|
|
2859
2859
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -2885,7 +2885,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
|
|
|
2885
2885
|
* See the License for the specific language governing permissions and
|
|
2886
2886
|
* limitations under the License.
|
|
2887
2887
|
* =============================================================================
|
|
2888
|
-
*/var jr;!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(jr||(jr={}));const zr={flipLeftRight:or,grayscaleToRGB:lr,resizeNearestNeighbor:Nr,resizeBilinear:Sr,rotateWithOffset:cr,cropAndResize:rr,nonMaxSuppression:hr,nonMaxSuppressionAsync:yr,nonMaxSuppressionWithScore:br,nonMaxSuppressionWithScoreAsync:wr,nonMaxSuppressionPadded:kr,nonMaxSuppressionPaddedAsync:xr,threshold:Ir,transform:Tr},Dr={bandPart:
|
|
2888
|
+
*/var jr;!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(jr||(jr={}));const zr={flipLeftRight:or,grayscaleToRGB:lr,resizeNearestNeighbor:Nr,resizeBilinear:Sr,rotateWithOffset:cr,cropAndResize:rr,nonMaxSuppression:hr,nonMaxSuppressionAsync:yr,nonMaxSuppressionWithScore:br,nonMaxSuppressionWithScoreAsync:wr,nonMaxSuppressionPadded:kr,nonMaxSuppressionPaddedAsync:xr,threshold:Ir,transform:Tr},Dr={bandPart:Er,gramSchmidt:Ar,qr:$r};
|
|
2889
2889
|
/**
|
|
2890
2890
|
* @license
|
|
2891
2891
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -2918,7 +2918,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
|
|
|
2918
2918
|
* limitations under the License.
|
|
2919
2919
|
* =============================================================================
|
|
2920
2920
|
*/
|
|
2921
|
-
class Fr extends gi{minimize(e,t=!1,n){const{value:i,grads:a}=this.computeGradients(e,n);if(null!=n){const e=n.map((e=>({name:e.name,tensor:a[e.name]})));this.applyGradients(e)}else this.applyGradients(a);return ri(a),t?i:(i.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return function(e,t){I(O(e),(()=>"The f passed in variableGrads(f) must be a function")),I(null==t||Array.isArray(t)&&t.every((e=>e instanceof Wt)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in sn.registeredVariables)t.push(sn.registeredVariables[e])}const i=n?t.filter((e=>!e.trainable)):null,a=t.length;t=t.filter((e=>e.trainable)),I(t.length>0,(()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${a} variables is trainable.`));const{value:s,grads:r}=sn.gradients(e,t,null,!0);I(r.some((e=>null!=e)),(()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().")),I(0===s.rank,(()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${s.rank} tensor`));const o={};return t.forEach(((e,t)=>{null!=r[t]&&(o[e.name]=r[t])})),null!=i&&i.forEach((e=>o[e.name]=null)),{value:s,grads:o}}(e,t)}dispose(){null!=this.iterations_&&ri(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:
|
|
2921
|
+
class Fr extends gi{minimize(e,t=!1,n){const{value:i,grads:a}=this.computeGradients(e,n);if(null!=n){const e=n.map((e=>({name:e.name,tensor:a[e.name]})));this.applyGradients(e)}else this.applyGradients(a);return ri(a),t?i:(i.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return function(e,t){I(O(e),(()=>"The f passed in variableGrads(f) must be a function")),I(null==t||Array.isArray(t)&&t.every((e=>e instanceof Wt)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in sn.registeredVariables)t.push(sn.registeredVariables[e])}const i=n?t.filter((e=>!e.trainable)):null,a=t.length;t=t.filter((e=>e.trainable)),I(t.length>0,(()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${a} variables is trainable.`));const{value:s,grads:r}=sn.gradients(e,t,null,!0);I(r.some((e=>null!=e)),(()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().")),I(0===s.rank,(()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${s.rank} tensor`));const o={};return t.forEach(((e,t)=>{null!=r[t]&&(o[e.name]=r[t])})),null!=i&&i.forEach((e=>o[e.name]=null)),{value:s,grads:o}}(e,t)}dispose(){null!=this.iterations_&&ri(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:Aa(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(Fr,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});
|
|
2922
2922
|
/**
|
|
2923
2923
|
* @license
|
|
2924
2924
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -2967,7 +2967,7 @@ class _r extends Fr{constructor(e,t,n=null){super(),this.learningRate=e,this.rho
|
|
|
2967
2967
|
* See the License for the specific language governing permissions and
|
|
2968
2968
|
* limitations under the License.
|
|
2969
2969
|
* =============================================================================
|
|
2970
|
-
*/class Lr extends Fr{constructor(e,t,n,i=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=i,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],si((()=>{this.accBeta1=
|
|
2970
|
+
*/class Lr extends Fr{constructor(e,t,n,i=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=i,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],si((()=>{this.accBeta1=Aa(t).variable(),this.accBeta2=Aa(n).variable()})),null==i&&(this.epsilon=sn.backend.epsilon())}static get className(){return"Adam"}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);si((()=>{const n=Ja(1,this.accBeta1),i=Ja(1,this.accBeta2);t.forEach(((t,a)=>{const s=sn.registeredVariables[t];null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:si((()=>ya(s).variable(false)))}),null==this.accumulatedSecondMoment[a]&&(this.accumulatedSecondMoment[a]={originalName:`${t}/v`,variable:si((()=>ya(s).variable(false)))});const r=Array.isArray(e)?e[a].tensor:e[t];if(null==r)return;const o=this.accumulatedFirstMoment[a].variable,l=this.accumulatedSecondMoment[a].variable,c=bi(xi(o,this.beta1),xi(r,1-this.beta1)),u=bi(xi(l,this.beta2),xi($a(r),1-this.beta2)),h=ki(c,n),p=ki(u,i);o.assign(c),l.assign(u);const d=bi(xi(ki(h,bi(Ca(p),this.epsilon)),-this.learningRate),s);s.assign(d)})),this.accBeta1.assign(xi(this.accBeta1,this.beta1)),this.accBeta2.assign(xi(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&ri(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&ri(this.accumulatedSecondMoment.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e),si((()=>{this.accBeta1.assign(Ea(this.beta1,this.iterations_+1)),this.accBeta2.assign(Ea(this.beta2,this.iterations_+1))}));const t=e.length/2;this.accumulatedFirstMoment=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)}))),this.accumulatedSecondMoment=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}
|
|
2971
2971
|
/**
|
|
2972
2972
|
* @license
|
|
2973
2973
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -2983,7 +2983,7 @@ class _r extends Fr{constructor(e,t,n=null){super(),this.learningRate=e,this.rho
|
|
|
2983
2983
|
* See the License for the specific language governing permissions and
|
|
2984
2984
|
* limitations under the License.
|
|
2985
2985
|
* =============================================================================
|
|
2986
|
-
*/class Mr extends Fr{constructor(e,t,n,i=null,a=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=i,this.decay=a,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],si((()=>{this.iteration=
|
|
2986
|
+
*/class Mr extends Fr{constructor(e,t,n,i=null,a=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=i,this.decay=a,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],si((()=>{this.iteration=Aa(0).variable(),this.accBeta1=Aa(t).variable()})),null==i&&(this.epsilon=sn.backend.epsilon())}static get className(){return"Adamax"}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);si((()=>{const n=Ja(1,this.accBeta1),i=ki(-this.learningRate,bi(xi(this.iteration,this.decay),1));t.forEach(((t,a)=>{const s=sn.registeredVariables[t];null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:ya(s).variable(false)}),null==this.accumulatedWeightedInfNorm[a]&&(this.accumulatedWeightedInfNorm[a]={originalName:`${t}/v`,variable:ya(s).variable(false)});const r=Array.isArray(e)?e[a].tensor:e[t];if(null==r)return;const o=this.accumulatedFirstMoment[a].variable,l=this.accumulatedWeightedInfNorm[a].variable,c=bi(xi(o,this.beta1),xi(r,1-this.beta1)),u=xi(l,this.beta2),h=Si(r),p=ts(u,h);o.assign(c),l.assign(p);const d=bi(xi(ki(i,n),ki(c,bi(p,this.epsilon))),s);s.assign(d)})),this.iteration.assign(bi(this.iteration,1)),this.accBeta1.assign(xi(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&ri(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&ri(this.accumulatedWeightedInfNorm.map((e=>e.variable)))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}
|
|
2987
2987
|
/**
|
|
2988
2988
|
* @license
|
|
2989
2989
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -2999,7 +2999,7 @@ class _r extends Fr{constructor(e,t,n=null){super(),this.learningRate=e,this.rho
|
|
|
2999
2999
|
* See the License for the specific language governing permissions and
|
|
3000
3000
|
* limitations under the License.
|
|
3001
3001
|
* =============================================================================
|
|
3002
|
-
*/class Or extends Fr{constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}static get className(){return"SGD"}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=Array.isArray(e)?e[n].tensor:e[t];if(null==i)return;const a=sn.registeredVariables[t];si((()=>{const e=bi(xi(this.c,i),a);a.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=oi(
|
|
3002
|
+
*/class Or extends Fr{constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}static get className(){return"SGD"}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=Array.isArray(e)?e[n].tensor:e[t];if(null==i)return;const a=sn.registeredVariables[t];si((()=>{const e=bi(xi(this.c,i),a);a.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=oi(Aa(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(0!==(e=await this.extractIterations(e)).length)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}
|
|
3003
3003
|
/**
|
|
3004
3004
|
* @license
|
|
3005
3005
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -3015,7 +3015,7 @@ class _r extends Fr{constructor(e,t,n=null){super(),this.learningRate=e,this.rho
|
|
|
3015
3015
|
* See the License for the specific language governing permissions and
|
|
3016
3016
|
* limitations under the License.
|
|
3017
3017
|
* =============================================================================
|
|
3018
|
-
*/class Pr extends Or{constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=
|
|
3018
|
+
*/class Pr extends Or{constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Aa(this.momentum)}static get className(){return"Momentum"}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=sn.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:si((()=>ya(i).variable(e)))}}const a=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];null!=s&&si((()=>{let e;const t=bi(xi(this.m,a),s);e=this.useNesterov?bi(xi(this.c,bi(s,xi(t,this.m))),i):bi(xi(this.c,t),i),a.assign(t),i.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&ri(this.accumulations.map((e=>e.variable)))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);this.accumulations=e.map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}
|
|
3019
3019
|
/**
|
|
3020
3020
|
* @license
|
|
3021
3021
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -3146,7 +3146,7 @@ function Vr(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and i
|
|
|
3146
3146
|
* limitations under the License.
|
|
3147
3147
|
* =============================================================================
|
|
3148
3148
|
*/
|
|
3149
|
-
function Kr(e){try{return e.map((e=>
|
|
3149
|
+
function Kr(e){try{return e.map((e=>At(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}
|
|
3150
3150
|
/**
|
|
3151
3151
|
* @license
|
|
3152
3152
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
@@ -3263,7 +3263,7 @@ function Xr(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&I("complex64"
|
|
|
3263
3263
|
* limitations under the License.
|
|
3264
3264
|
* =============================================================================
|
|
3265
3265
|
*/
|
|
3266
|
-
function(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const i=Zi(e,"int32"),a=Zi([n.length,e.length],"int32");for(let t=0;t<n.length;t++){const s=i.indexToLoc(n[t]),r=t*e.length;a.values.set(s,r)}return a.toTensor()};class to extends k{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new w(this,ii())}nextDataId(){return to.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,Q().get("IS_NODE")&>("\n============================\nHi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. \n============================"));const i={id:this.nextDataId()};return this.data.set(i,{values:e,dtype:n,refCount:1}),i}makeTensorInfo(e,t,n){let i;if("string"===t&&null!=n&&n.length>0&&R(n[0])){const a=n.map((e=>
|
|
3266
|
+
function(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const i=Zi(e,"int32"),a=Zi([n.length,e.length],"int32");for(let t=0;t<n.length;t++){const s=i.indexToLoc(n[t]),r=t*e.length;a.values.set(s,r)}return a.toTensor()};class to extends k{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new w(this,ii())}nextDataId(){return to.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,Q().get("IS_NODE")&>("\n============================\nHi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. \n============================"));const i={id:this.nextDataId()};return this.data.set(i,{values:e,dtype:n,refCount:1}),i}makeTensorInfo(e,t,n){let i;if("string"===t&&null!=n&&n.length>0&&R(n[0])){const a=n.map((e=>Et(e)));i=this.write(a,e,t)}else i=this.write(n,e,t);return{dataId:i,shape:e,dtype:t}}refCount(e){if(this.data.has(e)){return this.data.get(e).refCount}return 0}incRef(e){this.data.get(e).refCount++}decRef(e){if(this.data.has(e)){this.data.get(e).refCount--}}move(e,t,n,i,a){this.data.set(e,{values:t,dtype:i,refCount:a})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);if("complex64"===t){return Vr(this.readSync(n.real.dataId),this.readSync(n.imag.dataId))}return function(e,t){if(Array.isArray(e))return e;if("float32"===t)return e instanceof Float32Array?e:new Float32Array(e);if("int32"===t)return e instanceof Int32Array?e:new Int32Array(e);if("bool"===t||"string"===t)return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}(this.data.get(e).values,t)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>At(e)));return Zi(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Zi(e.shape,e.dtype,t)}makeOutput(e,t,n){return ii().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:n}=this.data.get(e);null!=n&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=Tt();e();return{kernelMs:Tt()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){Xr([e],"where");const t=this.readSync(e.dataId);return eo(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}
|
|
3267
3267
|
/**
|
|
3268
3268
|
* @license
|
|
3269
3269
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3280,7 +3280,7 @@ function(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const i=Zi(e
|
|
|
3280
3280
|
* limitations under the License.
|
|
3281
3281
|
* =============================================================================
|
|
3282
3282
|
*/
|
|
3283
|
-
function no(e){return(t,n,i,a,s)=>{const r=mi(t,n),o=r.length,l=P(r),c=D(s,
|
|
3283
|
+
function no(e){return(t,n,i,a,s)=>{const r=mi(t,n),o=r.length,l=P(r),c=D(s,A(r)),u=t.length,h=n.length,p=P(t),d=P(n),m=pi(t,r),f=pi(n,r);if(m.length+f.length===0)for(let t=0;t<c.length;++t)c[t]=e(i[t%i.length],a[t%a.length]);else for(let t=0;t<c.length;++t){const n=q(t,o,l),s=n.slice(-u);m.forEach((e=>s[e]=0));const r=K(s,u,p),g=n.slice(-h);f.forEach((e=>g[e]=0));const v=K(g,h,d);c[t]=e(i[r],a[v])}return[c,r]}}
|
|
3284
3284
|
/**
|
|
3285
3285
|
* @license
|
|
3286
3286
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3312,7 +3312,7 @@ function no(e){return(t,n,i,a,s)=>{const r=mi(t,n),o=r.length,l=P(r),c=D(s,E(r))
|
|
|
3312
3312
|
* See the License for the specific language governing permissions and
|
|
3313
3313
|
* limitations under the License.
|
|
3314
3314
|
* =============================================================================
|
|
3315
|
-
*/function ao(e,t,n="float32"){if("complex64"===n){return io({inputs:{real:ao(e,t,"float32"),imag:ao(e,t,"float32")},backend:e})}const i=G(
|
|
3315
|
+
*/function ao(e,t,n="float32"){if("complex64"===n){return io({inputs:{real:ao(e,t,"float32"),imag:ao(e,t,"float32")},backend:e})}const i=G(A(t),n);return e.makeTensorInfo(t,n,i)}
|
|
3316
3316
|
/**
|
|
3317
3317
|
* @license
|
|
3318
3318
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3328,7 +3328,7 @@ function no(e){return(t,n,i,a,s)=>{const r=mi(t,n),o=r.length,l=P(r),c=D(s,E(r))
|
|
|
3328
3328
|
* See the License for the specific language governing permissions and
|
|
3329
3329
|
* limitations under the License.
|
|
3330
3330
|
* =============================================================================
|
|
3331
|
-
*/function so(e){const{inputs:t,backend:n}=e,{x:i}=t;return n.incRef(i.dataId),{dataId:i.dataId,shape:i.shape,dtype:i.dtype}}to.nextDataId=0;const ro={kernelName:
|
|
3331
|
+
*/function so(e){const{inputs:t,backend:n}=e,{x:i}=t;return n.incRef(i.dataId),{dataId:i.dataId,shape:i.shape,dtype:i.dtype}}to.nextDataId=0;const ro={kernelName:Ee,backendName:"cpu",kernelFunc:so};
|
|
3332
3332
|
/**
|
|
3333
3333
|
* @license
|
|
3334
3334
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3393,7 +3393,7 @@ function no(e){return(t,n,i,a,s)=>{const r=mi(t,n),o=r.length,l=P(r),c=D(s,E(r))
|
|
|
3393
3393
|
* limitations under the License.
|
|
3394
3394
|
* =============================================================================
|
|
3395
3395
|
*/
|
|
3396
|
-
const co=no(((e,t)=>e+t)),uo=function(e){return(t,n,i,a,s,r)=>{const o=mi(t,n),l=
|
|
3396
|
+
const co=no(((e,t)=>e+t)),uo=function(e){return(t,n,i,a,s,r)=>{const o=mi(t,n),l=A(o),c=o.length,u=P(o),h=D("float32",l),p=D("float32",l),d=pi(t,o),m=pi(n,o),f=Vr(i,a),g=Vr(s,r),v=t.length,y=P(t),b=n.length,w=P(n);if(d.length+m.length===0)for(let t=0;t<h.length;t++){const n=t%f.length,i=t%g.length,a=e(f[2*n],f[2*n+1],g[2*i],g[2*i+1]);h[t]=a.real,p[t]=a.imag}else for(let t=0;t<h.length;t++){const n=q(t,c,u),i=n.slice(-v);d.forEach((e=>i[e]=0));const a=K(i,v,y),s=n.slice(-b);m.forEach((e=>s[e]=0));const r=K(s,b,w),o=e(f[2*a],f[2*a+1],g[2*r],g[2*r+1]);h[t]=o.real,p[t]=o.imag}return[h,p,o]}}(((e,t,n,i)=>({real:e+n,imag:t+i}))),ho=(po=ie,mo=co,null==(fo=uo)?({inputs:e,backend:t})=>{const{a:n,b:i}=e,a=t;Xr([n,i],po);const s=a.data.get(n.dataId).values,r=a.data.get(i.dataId).values,o="string"===n.dtype?Kr(s):s,l="string"===n.dtype?Kr(r):r,c=go||n.dtype,[u,h]=mo(n.shape,i.shape,o,l,c);return a.makeTensorInfo(h,c,u)}:({inputs:e,backend:t})=>{const{a:n,b:i}=e,a=t;if("complex64"===n.dtype||"complex64"===i.dtype){const e=oo({inputs:{x:n},backend:a,attrs:{dtype:"complex64"}}),t=a.data.get(e.dataId),s=t.complexTensorInfos.real,r=t.complexTensorInfos.imag,o=a.data.get(s.dataId).values,l=a.data.get(r.dataId).values,c=oo({inputs:{x:i},backend:a,attrs:{dtype:"complex64"}}),u=a.data.get(c.dataId),h=u.complexTensorInfos.real,p=u.complexTensorInfos.imag,d=a.data.get(h.dataId).values,m=a.data.get(p.dataId).values,[f,g,v]=fo(n.shape,i.shape,o,l,d,m),y=a.makeTensorInfo(v,"float32",f),b=a.makeTensorInfo(v,"float32",g),w=io({inputs:{real:y,imag:b},backend:a});return a.disposeIntermediateTensorInfo(e),a.disposeIntermediateTensorInfo(c),a.disposeIntermediateTensorInfo(y),a.disposeIntermediateTensorInfo(b),w}{const e=a.data.get(n.dataId).values,t=a.data.get(i.dataId).values,s=go||n.dtype,[r,o]=mo(n.shape,i.shape,e,t,s);return a.makeTensorInfo(o,s,r)}});var po,mo,fo,go;const vo={kernelName:ie,backendName:"cpu",kernelFunc:ho};
|
|
3397
3397
|
/**
|
|
3398
3398
|
* @license
|
|
3399
3399
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3409,7 +3409,7 @@ const co=no(((e,t)=>e+t)),uo=function(e){return(t,n,i,a,s,r)=>{const o=mi(t,n),l
|
|
|
3409
3409
|
* See the License for the specific language governing permissions and
|
|
3410
3410
|
* limitations under the License.
|
|
3411
3411
|
* =============================================================================
|
|
3412
|
-
*/function yo(e,t,n){return({inputs:i,attrs:a,backend:s})=>{const{x:r}=i;if(Xr(r,e),"string"===r.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const o=s,l=o.data.get(r.dataId).values,c=
|
|
3412
|
+
*/function yo(e,t,n){return({inputs:i,attrs:a,backend:s})=>{const{x:r}=i;if(Xr(r,e),"string"===r.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const o=s,l=o.data.get(r.dataId).values,c=A(r.shape),u=n||r.dtype,h=F(u,c);for(let e=0;e<c;++e)h[e]=t(l[e],a);return o.makeTensorInfo(r.shape,u,h)}}
|
|
3413
3413
|
/**
|
|
3414
3414
|
* @license
|
|
3415
3415
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3459,7 +3459,7 @@ function bo(e){const{inputs:t,attrs:n,backend:i}=e,{x:a}=t,{perm:s}=n;Xr(a,"tran
|
|
|
3459
3459
|
* limitations under the License.
|
|
3460
3460
|
* =============================================================================
|
|
3461
3461
|
*/
|
|
3462
|
-
function(e,t,n,i,a){const s=t.length,r=
|
|
3462
|
+
function(e,t,n,i,a){const s=t.length,r=A(t),o=P(t),l=P(a),c=D(n,A(a));for(let t=0;t<r;++t){const n=q(t,s,o),a=new Array(n.length);for(let e=0;e<a.length;e++)a[e]=n[i[e]];c[K(a,s,l)]=e[t]}return c}(i.data.get(a.dataId).values,a.shape,a.dtype,s,o);return{dataId:i.write(l,o,a.dtype),shape:o,dtype:a.dtype}}const wo={kernelName:ct,backendName:"cpu",kernelFunc:bo},ko=yo(Xe,(e=>1/(1+Math.exp(-e)))),xo={kernelName:Xe,backendName:"cpu",kernelFunc:ko};
|
|
3463
3463
|
/**
|
|
3464
3464
|
* @license
|
|
3465
3465
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3492,7 +3492,7 @@ function(e,t,n,i,a){const s=t.length,r=E(t),o=P(t),l=P(a),c=D(n,E(a));for(let t=
|
|
|
3492
3492
|
* limitations under the License.
|
|
3493
3493
|
* =============================================================================
|
|
3494
3494
|
*/
|
|
3495
|
-
function So(e,t,n,i,a){const s=function(e,t,n){let i=n.length;for(let e=0;e<n.length;e++)if(n[e]>1){i=e;break}for(let a=i+1;a<n.length;a++)if(t[a]>0||n[a]!==e[a])return!1;return!0}(i,t,n),r=
|
|
3495
|
+
function So(e,t,n,i,a){const s=function(e,t,n){let i=n.length;for(let e=0;e<n.length;e++)if(n[e]>1){i=e;break}for(let a=i+1;a<n.length;a++)if(t[a]>0||n[a]!==e[a])return!1;return!0}(i,t,n),r=A(n),o=P(i);if(s){const n=function(e,t){let n=e.length>0?e[e.length-1]:1;for(let i=0;i<e.length-1;i++)n+=e[i]*t[i];return n}(t,o);return"string"===a?e.slice(n,n+r):e.subarray(n,n+r)}const l=Zi(i,a,"string"===a?Kr(e):e),c=Zi(n,a);for(let e=0;e<c.size;++e){const n=c.indexToLoc(e),i=n.map(((e,n)=>e+t[n]));c.set(l.get(...i),...n)}return"string"===a?c.values.map((e=>Et(e))):c.values}function No(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{begin:s,size:r}=i;Xr(a,"slice");const[o,l]=fi(a,s,r);!function(e,t,n){const i=e.shape.length;I(i===t.length,(()=>`Error in slice${i}D: Length of begin ${t} must match the rank of the array (${i}).`)),I(i===n.length,(()=>`Error in slice${i}D: Length of size ${n} must match the rank of the array (${i}).`));for(let a=0;a<i;++a)I(t[a]+n[a]<=e.shape[a],(()=>`Error in slice${i}D: begin[${a}] + size[${a}] (${t[a]+n[a]}) would overflow input.shape[${a}] (${e.shape[a]})`))}(a,o,l);const c=So(n.data.get(a.dataId).values,o,l,a.shape,a.dtype);return n.makeTensorInfo(l,a.dtype,c)}const Io={kernelName:Ye,backendName:"cpu",kernelFunc:No};
|
|
3496
3496
|
/**
|
|
3497
3497
|
* @license
|
|
3498
3498
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
@@ -3525,7 +3525,7 @@ function So(e,t,n,i,a){const s=function(e,t,n){let i=n.length;for(let e=0;e<n.le
|
|
|
3525
3525
|
* limitations under the License.
|
|
3526
3526
|
* =============================================================================
|
|
3527
3527
|
*/
|
|
3528
|
-
function To(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{shape:s}=i,r=
|
|
3528
|
+
function To(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{shape:s}=i,r=A(a.shape),o=function(e,t){let n=1,i=-1;for(let t=0;t<e.length;++t)if(e[t]>=0)n*=e[t];else if(-1===e[t]){if(-1!==i)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${i} and dim ${t}`);i=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===i){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const a=e.slice();return a[i]=t/n,a}(s,r),l=A(o);I(r===l,(()=>`The new shape (${o}) has ${l} elements and the old shape (${a.shape}) has ${r} elements. The new shape and old shape must have the same number of elements.`)),n.incRef(a.dataId);const c=n.data.get(a.dataId);if(null!=c.complexTensorInfos){const e=c.complexTensorInfos.real,t=c.complexTensorInfos.imag;e.shape=o,t.shape=o}return{dataId:a.dataId,shape:o,dtype:a.dtype}}
|
|
3529
3529
|
/**
|
|
3530
3530
|
* @license
|
|
3531
3531
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3542,7 +3542,7 @@ function To(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{shape:s}=i,r=E(a.sha
|
|
|
3542
3542
|
* limitations under the License.
|
|
3543
3543
|
* =============================================================================
|
|
3544
3544
|
*/
|
|
3545
|
-
!function(e,t,n=1){sn.registerBackend(e,t,n)}("cpu",(()=>new to),1);const
|
|
3545
|
+
!function(e,t,n=1){sn.registerBackend(e,t,n)}("cpu",(()=>new to),1);const Eo={kernelName:Ue,backendName:"cpu",kernelFunc:To};
|
|
3546
3546
|
/**
|
|
3547
3547
|
* @license
|
|
3548
3548
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3558,7 +3558,7 @@ function To(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{shape:s}=i,r=E(a.sha
|
|
|
3558
3558
|
* See the License for the specific language governing permissions and
|
|
3559
3559
|
* limitations under the License.
|
|
3560
3560
|
* =============================================================================
|
|
3561
|
-
*/const
|
|
3561
|
+
*/const Ao={kernelName:Ie,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a,indices:s}=t,{axis:r,batchDims:o}=i;Xr([a,s],"gatherV2");const l=z(r,a.shape)[0],c=n.data.get(s.dataId).values,u=a.shape[l];for(let e=0;e<c.length;++e){const t=c[e];I(t<=u-1&&t>=0,(()=>`GatherV2: the index value ${t} is not in [0, ${u-1}]`))}let h=o;null==o&&(h=0);const p=A(s.shape),d=function(e,t,n,i){const a=t.shape.length,s=e.shape.length;if(0!==i&&(i<-a||i>a))throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${i}`);if(i<0&&(i+=a),i>s)throw new Error(`batchDims (${i}) must be less than rank(x) (\n ${s}).`);if(n<i)throw new Error(`batchDims (${i}) must be less than or equal to axis (${n}).`);for(let n=0;n<i;++n)if(e.shape[n]!==t.shape[n])throw new Error(`x.shape[${n}]: ${e.shape[n]} should be equal to indices.shape[${n}]: ${t.shape[n]}.`);const r=e.shape[n],o=[];let l=1,c=1,u=1;for(let t=0;t<i;++t)o.push(e.shape[t]),l*=e.shape[t];for(let t=i;t<n;t++)o.push(e.shape[t]),c*=e.shape[t];for(let e=i;e<a;e++)o.push(t.shape[e]);for(let t=n+1;t<s;t++)o.push(e.shape[t]),u*=e.shape[t];return{batchSize:l,sliceSize:u,outerSize:c,dimSize:r,outputShape:o}}(a,s,l,h),m=To({inputs:{x:a},backend:n,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),f=To({inputs:{x:s},backend:n,attrs:{shape:[d.batchSize,p/d.batchSize]}}),g=[d.batchSize,d.outerSize,p/d.batchSize,d.sliceSize],v=n.bufferSync(f),y=function(e,t,n){const i=Zi(n,e.dtype);for(let n=0;n<i.size;++n){const a=i.indexToLoc(n).slice(),s=a[0],r=a[2],o=t.locToIndex([s,r]);a[2]=t.values[o];const l=e.locToIndex(a);0<=l&&l<e.values.length&&(i.values[n]=e.values[l])}return i}(n.bufferSync(m),v,g);return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),n.makeTensorInfo(d.outputShape,y.dtype,y.values)}};
|
|
3562
3562
|
/**
|
|
3563
3563
|
* @license
|
|
3564
3564
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3574,7 +3574,7 @@ function To(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{shape:s}=i,r=E(a.sha
|
|
|
3574
3574
|
* See the License for the specific language governing permissions and
|
|
3575
3575
|
* limitations under the License.
|
|
3576
3576
|
* =============================================================================
|
|
3577
|
-
*/const Co={kernelName:nt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{axis:s,keepDims:r}=i;let o;Xr(a,"sum"),o="bool"===a.dtype?oo({inputs:{x:a},backend:n,attrs:{dtype:"int32"}}):so({inputs:{x:a},backend:n});const l=o.shape.length,c=z(s,o.shape),u=Sa(c,l);let h=c,p=o;null!=u&&(p=bo({inputs:{x:o},backend:n,attrs:{perm:u}}),h=function(e,t){const n=[];for(let i=t-e;i<t;++i)n.push(i);return n}(h.length,l)),function(e,t,n){I(wa(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}("sum",h,p.shape.length);const[d,m]=ka(p.shape,h);let f=ao(n,d,Zt(p.dtype,"int32"));const g=
|
|
3577
|
+
*/const Co={kernelName:nt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{axis:s,keepDims:r}=i;let o;Xr(a,"sum"),o="bool"===a.dtype?oo({inputs:{x:a},backend:n,attrs:{dtype:"int32"}}):so({inputs:{x:a},backend:n});const l=o.shape.length,c=z(s,o.shape),u=Sa(c,l);let h=c,p=o;null!=u&&(p=bo({inputs:{x:o},backend:n,attrs:{perm:u}}),h=function(e,t){const n=[];for(let i=t-e;i<t;++i)n.push(i);return n}(h.length,l)),function(e,t,n){I(wa(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}("sum",h,p.shape.length);const[d,m]=ka(p.shape,h);let f=ao(n,d,Zt(p.dtype,"int32"));const g=A(m),v=n.data.get(f.dataId).values,y=n.data.get(p.dataId).values;for(let e=0;e<v.length;++e){const t=e*g;let n=0;for(let e=0;e<g;++e)n+=y[t+e];v[e]=n}if(r){const e=f;f=To({inputs:{x:f},backend:n,attrs:{shape:xa(f.shape,c)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(o),null!=u&&n.disposeIntermediateTensorInfo(p),f}};
|
|
3578
3578
|
/**
|
|
3579
3579
|
* @license
|
|
3580
3580
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3690,7 +3690,7 @@ function Lo(e,t,n,i,a){if("linear"===n)return so({inputs:{x:t},backend:e});if("r
|
|
|
3690
3690
|
* limitations under the License.
|
|
3691
3691
|
* =============================================================================
|
|
3692
3692
|
*/
|
|
3693
|
-
return function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{alpha:s}=i;Xr([a],"leakyRelu");const r=
|
|
3693
|
+
return function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{alpha:s}=i;Xr([a],"leakyRelu");const r=A(a.shape),o=n.data.get(a.dataId).values,l=D("float32",r);for(let e=0;e<o.length;e++)l[e]=o[e]<0?s*o[e]:o[e];return n.makeTensorInfo(a.shape,"float32",l)}({inputs:{x:t},backend:e,attrs:{alpha:a}});if("sigmoid"===n)return ko({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}
|
|
3694
3694
|
/**
|
|
3695
3695
|
* @license
|
|
3696
3696
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3723,7 +3723,7 @@ return function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{alpha:s}=i;Xr([a
|
|
|
3723
3723
|
* limitations under the License.
|
|
3724
3724
|
* =============================================================================
|
|
3725
3725
|
*/
|
|
3726
|
-
function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s,bias:r,preluActivationWeights:o}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:h}=i;let p,d,m;const f=[],g=function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s}=t,{transposeA:r,transposeB:o}=i;Xr([a,s],"matMul");const l=a.shape.length,c=s.shape.length,u=r?a.shape[l-2]:a.shape[l-1],h=o?s.shape[c-1]:s.shape[c-2],p=r?a.shape[l-1]:a.shape[l-2],d=o?s.shape[c-2]:s.shape[c-1],m=a.shape.slice(0,-2),f=s.shape.slice(0,-2),g=
|
|
3726
|
+
function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s,bias:r,preluActivationWeights:o}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:h}=i;let p,d,m;const f=[],g=function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s}=t,{transposeA:r,transposeB:o}=i;Xr([a,s],"matMul");const l=a.shape.length,c=s.shape.length,u=r?a.shape[l-2]:a.shape[l-1],h=o?s.shape[c-1]:s.shape[c-2],p=r?a.shape[l-1]:a.shape[l-2],d=o?s.shape[c-2]:s.shape[c-1],m=a.shape.slice(0,-2),f=s.shape.slice(0,-2),g=A(m),v=A(f),y=mi(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([p,d]);I(u===h,(()=>`Error in matMul: inner shapes (${u}) and (${h}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${r} and transposeB=${o} must match.`));const b=o?[v,d,h]:[v,h,d],w=To({inputs:{x:a},backend:n,attrs:{shape:r?[g,u,p]:[g,p,u]}}),k=To({inputs:{x:s},backend:n,attrs:{shape:b}}),x=r?w.shape[1]:w.shape[2],S=r?w.shape[2]:w.shape[1],N=o?k.shape[1]:k.shape[2],T=Math.max(g,v),E=n.data.get(w.dataId).values,C=n.data.get(k.dataId).values,$=P(w.shape),j=P(k.shape),[z,D,F]=r?[$[0],1,$[1]]:[$[0],$[1],1],[_,R,L]=o?[1,j[1],j[0]]:[j[1],1,j[0]],M=S*N,O=Zi([T,S,N],w.dtype),B=O.values,U=n.blockSize;for(let e=0;e<T;e++){const t=e%g,n=e%v;for(let i=0;i<S;i+=U){const a=Math.min(i+U,S);for(let s=0;s<N;s+=U){const r=Math.min(s+U,N);for(let o=0;o<x;o+=U){const l=Math.min(o+U,x);for(let c=i;c<a;c++)for(let i=s;i<r;i++){let a=0;for(let e=o;e<l;e++)a+=E[t*z+c*D+e*F]*C[e*_+i*R+n*L];B[e*M+(c*N+i)]+=a}}}}}return n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(k),n.makeTensorInfo(y,O.dtype,O.values)}({inputs:{a:a,b:s},attrs:{transposeA:l,transposeB:c},backend:n});p=g,r&&(d=ho({inputs:{a:p,b:r},backend:n}),f.push(p),p=d),u&&(m=Lo(n,p,u,o,h),f.push(p),p=m);for(const e of f)n.disposeIntermediateTensorInfo(e);return p}};
|
|
3727
3727
|
/**
|
|
3728
3728
|
* @license
|
|
3729
3729
|
* Copyright 2018 Google LLC
|
|
@@ -3768,7 +3768,7 @@ function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s,bias:r,preluActivationW
|
|
|
3768
3768
|
* license that can be found in the LICENSE file or at
|
|
3769
3769
|
* https://opensource.org/licenses/MIT.
|
|
3770
3770
|
* =============================================================================
|
|
3771
|
-
*/const ml=["channelsFirst","channelsLast"],fl=["nearest","bilinear"],gl=["valid","same","causal"],vl=["max","avg"],yl=["sum","mul","concat","ave"],bl=new Map;function wl(e){sl(ml,"DataFormat",e)}function kl(e){sl(gl,"PaddingMode",e)}function xl(e){sl(vl,"PoolMode",e)}const Sl=[];function Nl(e,t){Sl.push(e);try{const e=t();return Sl.pop(),e}catch(e){throw Sl.pop(),e}}function Il(e){if(!
|
|
3771
|
+
*/const ml=["channelsFirst","channelsLast"],fl=["nearest","bilinear"],gl=["valid","same","causal"],vl=["max","avg"],yl=["sum","mul","concat","ave"],bl=new Map;function wl(e){sl(ml,"DataFormat",e)}function kl(e){sl(gl,"PaddingMode",e)}function xl(e){sl(vl,"PoolMode",e)}const Sl=[];function Nl(e,t){Sl.push(e);try{const e=t();return Sl.pop(),e}catch(e){throw Sl.pop(),e}}function Il(e){if(!Al(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===Sl.length?"":Sl.join("/")+"/")+e}function Tl(e){if(!Al(e))throw new Error("Not a valid tensor name: '"+e+"'");bl.has(e)||bl.set(e,0);const t=bl.get(e);if(bl.set(e,bl.get(e)+1),t>0){const n=`${e}_${t}`;return bl.set(n,1),n}return e}const El=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Al(e){return!!e.match(El)}
|
|
3772
3772
|
/**
|
|
3773
3773
|
* @license
|
|
3774
3774
|
* Copyright 2018 Google LLC
|
|
@@ -3805,7 +3805,7 @@ function _l(e,t){return ei(e,t)}function Rl(e,t=-1){const n=e.shape.slice();retu
|
|
|
3805
3805
|
* license that can be found in the LICENSE file or at
|
|
3806
3806
|
* https://opensource.org/licenses/MIT.
|
|
3807
3807
|
* =============================================================================
|
|
3808
|
-
*/const Yl=["fanIn","fanOut","fanAvg"],Ql=["normal","uniform","truncatedNormal"];class Xl extends gi{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class ec extends Xl{apply(e,t){return is(e,t)}}ec.className="Zeros",yi(ec);class tc extends Xl{apply(e,t){return as(e,t)}}tc.className="Ones",yi(tc);class nc extends Xl{constructor(e){if(super(),"object"!=typeof e)throw new Bo(`Expected argument of type ConstantConfig but got ${e}`);if(void 0===e.value)throw new Bo(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return si((()=>xi(
|
|
3808
|
+
*/const Yl=["fanIn","fanOut","fanAvg"],Ql=["normal","uniform","truncatedNormal"];class Xl extends gi{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class ec extends Xl{apply(e,t){return is(e,t)}}ec.className="Zeros",yi(ec);class tc extends Xl{apply(e,t){return as(e,t)}}tc.className="Ones",yi(tc);class nc extends Xl{constructor(e){if(super(),"object"!=typeof e)throw new Bo(`Expected argument of type ConstantConfig but got ${e}`);if(void 0===e.value)throw new Bo(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return si((()=>xi(Aa(this.value),as(e,t))))}getConfig(){return{value:this.value}}}nc.className="Constant",yi(nc);class ic extends Xl{constructor(e){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return Is(e,this.minval,this.maxval,t,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}ic.className="RandomUniform",yi(ic);class ac extends Xl{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Uo(`randomNormal does not support dType ${t}.`);return Wl(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}ac.className="RandomNormal",yi(ac);class sc extends Xl{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Uo(`truncatedNormal does not support dType ${t}.`);return qs(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}sc.className="TruncatedNormal",yi(sc);class rc extends Xl{constructor(e){super(),this.gain=null!=e.gain?e.gain:1}apply(e,t){return si((()=>{if(2!==e.length||e[0]!==e[1])throw new Bo("Identity matrix initializer can only be used for 2D square matrices.");return xi(this.gain,La(e[0]))}))}getConfig(){return{gain:this.gain}}}rc.className="Identity",yi(rc);class oc extends Xl{constructor(e){if(super(),e.scale<0)throw new Bo(`scale must be a positive float. Got: ${e.scale}`);
|
|
3809
3809
|
/**
|
|
3810
3810
|
* @license
|
|
3811
3811
|
* Copyright 2018 Google LLC
|
|
@@ -3842,7 +3842,7 @@ var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t
|
|
|
3842
3842
|
* license that can be found in the LICENSE file or at
|
|
3843
3843
|
* https://opensource.org/licenses/MIT.
|
|
3844
3844
|
* =============================================================================
|
|
3845
|
-
*/const Nc="Variable";class Ic{constructor(e,t="float32",n=Nc,i=!0,a=null){this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=hl(),n=null==n?Nc:n,this.originalName=Il(n),this.name=Tl(this.originalName),this.trainable_=i,this.constraint=a,this.val=function(e,t=!0,n,i){return sn.makeVariable(e,t,n,i)}(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),function(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}(this.val,e),this.val.id!==e.id&&(this.val.assign(e),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}}function Tc(e){return e.map((e=>e.read()))}function
|
|
3845
|
+
*/const Nc="Variable";class Ic{constructor(e,t="float32",n=Nc,i=!0,a=null){this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=hl(),n=null==n?Nc:n,this.originalName=Il(n),this.name=Tl(this.originalName),this.trainable_=i,this.constraint=a,this.val=function(e,t=!0,n,i){return sn.makeVariable(e,t,n,i)}(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),function(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}(this.val,e),this.val.id!==e.id&&(this.val.assign(e),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}}function Tc(e){return e.map((e=>e.read()))}function Ec(e){e.forEach((e=>{e[0].write(e[1])}))}
|
|
3846
3846
|
/**
|
|
3847
3847
|
* @license
|
|
3848
3848
|
* Copyright 2018 Google LLC
|
|
@@ -3851,7 +3851,7 @@ var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t
|
|
|
3851
3851
|
* license that can be found in the LICENSE file or at
|
|
3852
3852
|
* https://opensource.org/licenses/MIT.
|
|
3853
3853
|
* =============================================================================
|
|
3854
|
-
*/class Ec{constructor(e){this.dtype=e.dtype,this.shape=e.shape,null!=e.shape?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class Cc{constructor(e,t,n,i,a,s,r){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=i,this.callArgs=a,this.outputTensorIndex=r,this.id=hl(),null!=s&&(this.originalName=Il(s),this.name=Tl(this.originalName)),this.rank=t.length}}let $c=0;class jc{constructor(e,t){this.callArgs=t,this.id=$c++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const t of e.inboundLayers)null!=t&&t.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)null!=t?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let zc=0;class Dc extends gi{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=zc++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const e=this.getClassName();t=Zo(e)+"_"+dl(e)}if(this.name=t,this.trainable_=null==e.trainable||e.trainable,null!=e.inputShape||null!=e.batchInputShape){let t;if(null!=e.batchInputShape)t=e.batchInputShape;else if(null!=e.inputShape){let n=null;null!=e.batchSize&&(n=e.batchSize),t=[n].concat(e.inputShape)}this.batchInputShape=t;let n=e.dtype;null==n&&(n=e.inputDType),null==n&&(n="float32"),this.dtype=n}null!=e.weights?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(0===this.inboundNodes.length)throw new Po(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new Bo(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Ho(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Ho(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Oo(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(0===this.inboundNodes.length)throw new Oo(`Layer ${this.name} is not connected, no input to return.`);return Ho(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new Oo(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Oo(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Ho(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map((e=>e()))}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach((t=>t.trainable=e)),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter((e=>e.trainable)):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter((e=>!e.trainable)).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=Jo(e),null==this.inputSpec||0===this.inputSpec.length)return;const t=Jo(this.inputSpec);if(e.length!==t.length)throw new Bo(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;n<e.length;n++){const i=e[n],a=t[n];if(null==a)continue;const s=i.rank;if(null!=a.ndim&&s!==a.ndim)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${a.ndim}, found ndim=${s}`);if(null!=a.maxNDim&&s>a.maxNDim)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${a.maxNDim}, found ndim=${s}`);if(null!=a.minNDim&&s<a.minNDim)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${a.minNDim}, found ndim=${s}.`);if(null!=a.dtype&&i.dtype!==a.dtype)throw new Bo(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${a.dtype}, found dtype=${i.dtype}.`);if(a.axes){const e=i.shape;for(const t in a.axes){const i=Number(t),s=a.axes[t],r=i>=0?e[i]:e[e.length+i];if(null!=s&&-1===[s,null].indexOf(r))throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected axis ${i} of input shape to have value ${s} but got shape ${e}.`)}}if(null!=a.shape)for(let e=0;e<a.shape.length;++e){const t=a.shape[e],s=i.shape[e];if(null!=t&&null!=s&&t!==s)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected shape=${a.shape}, found shape=${i.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){null!=this._callHook&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();const n=Jo(e);let i=!0;for(const e of n)if(!(e instanceof Cc)){i=!1;break}let a=!0;for(const e of n)if(e instanceof Cc){a=!1;break}if(i===a)throw new Bo("Arguments to apply() must be all SymbolicTensors or all Tensors");return Nl(this.name,(()=>{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of Jo(e))t.push(n.shape);this.build(Ho(t)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),null===this._refCount&&a&&(this._refCount=1)}if(this.assertInputCompatibility(e),a){let i=this.call(e,t);const a=Jo(i),s=[];for(let e of a)-1!==n.indexOf(e)&&(e=e.clone()),s.push(e);if(i=Ho(s),null!=this.activityRegularizer)throw new Uo("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}{const n=function(e){e=Jo(e);const t=[];for(const n of e)t.push(n.shape);return Ho(t)}(e),i=this.computeOutputShape(n);let a;const s="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(e)?n[0]:n),a=null!=i&&i.length>0&&Array.isArray(i[0])?i.map(((n,i)=>new Cc(s,n,this,Jo(e),t,this.name,i))):new Cc(s,i,this,Jo(e),t,this.name),this.addInboundNode(e,a,null,null,n,i,t),this._refCount++,null!=this.activityRegularizer)throw new Uo("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}}))}warnOnIncompatibleInputShape(e){if(null!=this.batchInputShape)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach(((n,i)=>{null!=n&&null!=e[i]&&e[i]!==n&&(t=!0)})),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new Oo(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const n=JSON.stringify(t.outputShapes);-1===e.indexOf(n)&&e.push(n)}if(1===e.length){const e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&1===e.length?e[0]:e}throw new Oo(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new Po(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Sc(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Tc(e?this.trainableWeights:this.weights)}setWeights(e){si((()=>{const t=this.weights;if(t.length!==e.length)throw new Bo(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(0===t.length)return;const n=[],i=Tc(t);for(let a=0;a<i.length;++a){const s=i[a],r=t[a],o=e[a];if(!C(s.shape,o.shape))throw new Bo(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);n.push([r,o])}Ac(n)}))}addWeight(e,t,n,i,a,s,r,o){if(-1!==this._addedWeightNames.indexOf(e))throw new Bo(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(i=null!=o?o():yc("zeros"));const l=i.apply(t,n),c=new Ic(l,n,e,s,r);return l.dispose(),null!=a&&this.addLoss((()=>a.apply(c.read()))),null==s&&(s=!0),s?this._trainableWeights.push(c):this._nonTrainableWeights.push(c),c}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){null==e||Array.isArray(e)&&0===e.length||(e=Jo(e),void 0!==this._losses&&null!==this._losses&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(null!=t){if(!Array.isArray(t))throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);t.forEach((e=>{if(null!=e)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)}))}return null}return t}addInboundNode(e,t,n,i,a,s,r=null){const o=Jo(e);t=Jo(t),n=Jo(n),i=Jo(i),a=wc(a),s=wc(s);const l=[],c=[],u=[];for(const e of o)l.push(e.sourceLayer),c.push(e.nodeIndex),u.push(e.tensorIndex);new jc({outboundLayer:this,inboundLayers:l,nodeIndices:c,tensorIndices:u,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:i,inputShapes:a,outputShapes:s},r);for(let e=0;e<t.length;e++)t[e].sourceLayer=this,t[e].nodeIndex=this.inboundNodes.length-1,t[e].tensorIndex=e}getConfig(){const e={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(e.batchInputShape=this.batchInputShape),null!=this.dtype&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach((e=>e.dispose())),this.weights.length}assertNotDisposed(){if(0===this._refCount)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(null===this._refCount)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return 0==--this._refCount&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function Fc(e,t,n){if((null==t||null!=n&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),0===t.inboundNodes.length)return[e];{const e=t.inboundNodes[n];if(0===e.inboundLayers.length)return e.inputTensors;{const t=[];for(let n=0;n<e.inboundLayers.length;n++){const i=Fc(e.inputTensors[n],e.inboundLayers[n],e.nodeIndices[n]);for(const e of i)-1===t.indexOf(e)&&t.push(e)}return t}}}
|
|
3854
|
+
*/class Ac{constructor(e){this.dtype=e.dtype,this.shape=e.shape,null!=e.shape?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class Cc{constructor(e,t,n,i,a,s,r){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=i,this.callArgs=a,this.outputTensorIndex=r,this.id=hl(),null!=s&&(this.originalName=Il(s),this.name=Tl(this.originalName)),this.rank=t.length}}let $c=0;class jc{constructor(e,t){this.callArgs=t,this.id=$c++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const t of e.inboundLayers)null!=t&&t.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)null!=t?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let zc=0;class Dc extends gi{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=zc++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const e=this.getClassName();t=Zo(e)+"_"+dl(e)}if(this.name=t,this.trainable_=null==e.trainable||e.trainable,null!=e.inputShape||null!=e.batchInputShape){let t;if(null!=e.batchInputShape)t=e.batchInputShape;else if(null!=e.inputShape){let n=null;null!=e.batchSize&&(n=e.batchSize),t=[n].concat(e.inputShape)}this.batchInputShape=t;let n=e.dtype;null==n&&(n=e.inputDType),null==n&&(n="float32"),this.dtype=n}null!=e.weights?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(0===this.inboundNodes.length)throw new Po(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new Bo(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Ho(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Ho(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Oo(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(0===this.inboundNodes.length)throw new Oo(`Layer ${this.name} is not connected, no input to return.`);return Ho(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new Oo(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Oo(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Ho(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map((e=>e()))}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach((t=>t.trainable=e)),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter((e=>e.trainable)):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter((e=>!e.trainable)).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=Jo(e),null==this.inputSpec||0===this.inputSpec.length)return;const t=Jo(this.inputSpec);if(e.length!==t.length)throw new Bo(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;n<e.length;n++){const i=e[n],a=t[n];if(null==a)continue;const s=i.rank;if(null!=a.ndim&&s!==a.ndim)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${a.ndim}, found ndim=${s}`);if(null!=a.maxNDim&&s>a.maxNDim)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${a.maxNDim}, found ndim=${s}`);if(null!=a.minNDim&&s<a.minNDim)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${a.minNDim}, found ndim=${s}.`);if(null!=a.dtype&&i.dtype!==a.dtype)throw new Bo(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${a.dtype}, found dtype=${i.dtype}.`);if(a.axes){const e=i.shape;for(const t in a.axes){const i=Number(t),s=a.axes[t],r=i>=0?e[i]:e[e.length+i];if(null!=s&&-1===[s,null].indexOf(r))throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected axis ${i} of input shape to have value ${s} but got shape ${e}.`)}}if(null!=a.shape)for(let e=0;e<a.shape.length;++e){const t=a.shape[e],s=i.shape[e];if(null!=t&&null!=s&&t!==s)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected shape=${a.shape}, found shape=${i.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){null!=this._callHook&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();const n=Jo(e);let i=!0;for(const e of n)if(!(e instanceof Cc)){i=!1;break}let a=!0;for(const e of n)if(e instanceof Cc){a=!1;break}if(i===a)throw new Bo("Arguments to apply() must be all SymbolicTensors or all Tensors");return Nl(this.name,(()=>{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of Jo(e))t.push(n.shape);this.build(Ho(t)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),null===this._refCount&&a&&(this._refCount=1)}if(this.assertInputCompatibility(e),a){let i=this.call(e,t);const a=Jo(i),s=[];for(let e of a)-1!==n.indexOf(e)&&(e=e.clone()),s.push(e);if(i=Ho(s),null!=this.activityRegularizer)throw new Uo("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}{const n=function(e){e=Jo(e);const t=[];for(const n of e)t.push(n.shape);return Ho(t)}(e),i=this.computeOutputShape(n);let a;const s="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(e)?n[0]:n),a=null!=i&&i.length>0&&Array.isArray(i[0])?i.map(((n,i)=>new Cc(s,n,this,Jo(e),t,this.name,i))):new Cc(s,i,this,Jo(e),t,this.name),this.addInboundNode(e,a,null,null,n,i,t),this._refCount++,null!=this.activityRegularizer)throw new Uo("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}}))}warnOnIncompatibleInputShape(e){if(null!=this.batchInputShape)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach(((n,i)=>{null!=n&&null!=e[i]&&e[i]!==n&&(t=!0)})),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new Oo(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const n=JSON.stringify(t.outputShapes);-1===e.indexOf(n)&&e.push(n)}if(1===e.length){const e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&1===e.length?e[0]:e}throw new Oo(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new Po(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Sc(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Tc(e?this.trainableWeights:this.weights)}setWeights(e){si((()=>{const t=this.weights;if(t.length!==e.length)throw new Bo(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(0===t.length)return;const n=[],i=Tc(t);for(let a=0;a<i.length;++a){const s=i[a],r=t[a],o=e[a];if(!C(s.shape,o.shape))throw new Bo(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);n.push([r,o])}Ec(n)}))}addWeight(e,t,n,i,a,s,r,o){if(-1!==this._addedWeightNames.indexOf(e))throw new Bo(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(i=null!=o?o():yc("zeros"));const l=i.apply(t,n),c=new Ic(l,n,e,s,r);return l.dispose(),null!=a&&this.addLoss((()=>a.apply(c.read()))),null==s&&(s=!0),s?this._trainableWeights.push(c):this._nonTrainableWeights.push(c),c}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){null==e||Array.isArray(e)&&0===e.length||(e=Jo(e),void 0!==this._losses&&null!==this._losses&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(null!=t){if(!Array.isArray(t))throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);t.forEach((e=>{if(null!=e)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)}))}return null}return t}addInboundNode(e,t,n,i,a,s,r=null){const o=Jo(e);t=Jo(t),n=Jo(n),i=Jo(i),a=wc(a),s=wc(s);const l=[],c=[],u=[];for(const e of o)l.push(e.sourceLayer),c.push(e.nodeIndex),u.push(e.tensorIndex);new jc({outboundLayer:this,inboundLayers:l,nodeIndices:c,tensorIndices:u,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:i,inputShapes:a,outputShapes:s},r);for(let e=0;e<t.length;e++)t[e].sourceLayer=this,t[e].nodeIndex=this.inboundNodes.length-1,t[e].tensorIndex=e}getConfig(){const e={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(e.batchInputShape=this.batchInputShape),null!=this.dtype&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach((e=>e.dispose())),this.weights.length}assertNotDisposed(){if(0===this._refCount)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(null===this._refCount)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return 0==--this._refCount&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function Fc(e,t,n){if((null==t||null!=n&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),0===t.inboundNodes.length)return[e];{const e=t.inboundNodes[n];if(0===e.inboundLayers.length)return e.inputTensors;{const t=[];for(let n=0;n<e.inboundLayers.length;n++){const i=Fc(e.inputTensors[n],e.inboundLayers[n],e.nodeIndices[n]);for(const e of i)-1===t.indexOf(e)&&t.push(e)}return t}}}
|
|
3855
3855
|
/**
|
|
3856
3856
|
* @license
|
|
3857
3857
|
* Copyright 2018 Google LLC
|
|
@@ -3903,7 +3903,7 @@ function(e,t){if(null==e.dtype||e.dtype===t.dtype)return t;try{return ei(t,e.dty
|
|
|
3903
3903
|
* limitations under the License.
|
|
3904
3904
|
* =============================================================================
|
|
3905
3905
|
*/
|
|
3906
|
-
const Wc={kernelName:"Abs",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,Gs(ei(n,"float32"),-1))}}},Gc={kernelName:"Acos",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=$a(ei(n,"float32")),i=Ca(Ja(
|
|
3906
|
+
const Wc={kernelName:"Abs",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,Gs(ei(n,"float32"),-1))}}},Gc={kernelName:"Acos",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=$a(ei(n,"float32")),i=Ca(Ja(Aa(1),t));return ci(ki(e,i))}}}},Vc={kernelName:"Acosh",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Ca(Ja($a(ei(n,"float32")),1));return ki(e,t)}}}},Kc={kernelName:ie,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{let t=e;const i=di(n.shape,a);return i.length>0&&(t=ja(t,i)),_i(t,n.shape)},b:()=>{let t=e;const n=di(i.shape,a);return n.length>0&&(t=ja(t,n)),_i(t,i.shape)}}}},qc={kernelName:"AddN",saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach(((t,i)=>{n[i]=()=>e.clone()})),n}},Hc={kernelName:ae,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ya(n)}}},Jc={kernelName:"ArgMin",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ya(n)}}},Zc={kernelName:"Asin",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,Ca(Ja(Aa(1),$a(ei(n,"float32")))))}}},Yc={kernelName:"Asinh",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Ca(bi(Aa(1),$a(ei(n,"float32"))));return ki(e,t)}}}},Qc={kernelName:"Atan2",inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=bi($a(n),$a(i));let s=xi(e,ki(i,t));const r=di(n.shape,a);return r.length>0&&(s=ja(s,r)),_i(s,n.shape)},b:()=>{const t=bi($a(n),$a(i));let s=ci(xi(e,ki(n,t)));const r=di(i.shape,a);return r.length>0&&(s=ja(s,r)),_i(s,i.shape)}}}},Xc={kernelName:"Atan",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,bi($a(ei(n,"float32")),1))}}},eu={kernelName:"Atanh",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,Ja(Aa(1),$a(ei(n,"float32"))))}}};
|
|
3907
3907
|
/**
|
|
3908
3908
|
* @license
|
|
3909
3909
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -4002,7 +4002,7 @@ function(e,t,n,i,a){const s=hn(e,"dy","avgPoolGrad"),r=hn(t,"input","avgPoolGrad
|
|
|
4002
4002
|
* limitations under the License.
|
|
4003
4003
|
* =============================================================================
|
|
4004
4004
|
*/
|
|
4005
|
-
function(e,t,n,i,a){let s=e;4===e.rank&&(s=_i(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let r=t;4===r.rank&&(r=_i(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),I(5===s.rank,(()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`)),I(5===r.rank,(()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${r.shape}.`)),I(5===n.length,(()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`)),I(s.shape[4]===n[3],(()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${n[3]}.`)),I(r.shape[4]===n[4],(()=>`Error in conv3dDerFilter: depth of dy (${r.shape[4]}) must match output depth for filter (${n[4]}).`));const o={x:s,dy:r},l={strides:i,pad:a,filterShape:n};return sn.runKernel("Conv3DBackpropFilterV2",o,l)}}),gu={kernelName:fe,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:i,strides:a,pad:s}=n;I(ji(i),(()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${i}'`));const[r,o]=t;return{x:()=>la(r.shape,e,o,a,s),filter:()=>fu(r,e,o.shape,a,s)}}},vu={kernelName:"Cos",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(ci(Fs(ei(n,"float32"))),e)}}},yu={kernelName:ge,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(_s(ei(n,"float32")),e)}}},bu={kernelName:ve,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{axis:a,exclusive:s,reverse:r}=n;return{x:()=>{const t=Sa([a],i.rank);let n=da(e,a,s,!r);return null!=t&&(n=hi(n,t)),n}}}},wu={kernelName:ye,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:i,strides:a,pad:s,dimRoundingMode:r}=n,o=null==i?[1,1]:i;I(ji(o),(()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`));const[l,c]=t;return I(4===l.rank,(()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`)),I(4===c.rank,(()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`)),I(l.shape[3]===c.shape[2],(()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`)),I(zi(a,o),(()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${o}'.`)),Fi("depthwiseConv2d",s,r),{x:()=>ar(l.shape,e,c,a,s,o,r),filter:()=>ir(l,e,c.shape,a,s,o,r)}}},ku={kernelName:"Dilation2D",inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[i,a]=t,s={x:i,filter:a,dy:e},r={x:i,filter:a,dy:e};return{x:()=>sn.runKernel("Dilation2DBackpropInput",s,n),filter:()=>sn.runKernel("Dilation2DBackpropFilter",r,n)}}},xu={kernelName:we,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,i={dy:e,y:n};return{x:()=>sn.runKernel("EluGrad",i)}}},Su={kernelName:"Erf",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,i=xi(Fa(ci($a(n))),2/Math.sqrt(Math.PI));return{x:()=>xi(e,i)}}},Nu={kernelName:"Exp",outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,n)}}},Iu={kernelName:ke,inputsToSave:["input"],gradFunc:(e,t)=>{const[n]=t;return{input:()=>_i(e,n.shape)}}},Tu={kernelName:"Expm1",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,Fa(n))}}},
|
|
4005
|
+
function(e,t,n,i,a){let s=e;4===e.rank&&(s=_i(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let r=t;4===r.rank&&(r=_i(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),I(5===s.rank,(()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`)),I(5===r.rank,(()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${r.shape}.`)),I(5===n.length,(()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`)),I(s.shape[4]===n[3],(()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${n[3]}.`)),I(r.shape[4]===n[4],(()=>`Error in conv3dDerFilter: depth of dy (${r.shape[4]}) must match output depth for filter (${n[4]}).`));const o={x:s,dy:r},l={strides:i,pad:a,filterShape:n};return sn.runKernel("Conv3DBackpropFilterV2",o,l)}}),gu={kernelName:fe,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:i,strides:a,pad:s}=n;I(ji(i),(()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${i}'`));const[r,o]=t;return{x:()=>la(r.shape,e,o,a,s),filter:()=>fu(r,e,o.shape,a,s)}}},vu={kernelName:"Cos",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(ci(Fs(ei(n,"float32"))),e)}}},yu={kernelName:ge,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(_s(ei(n,"float32")),e)}}},bu={kernelName:ve,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{axis:a,exclusive:s,reverse:r}=n;return{x:()=>{const t=Sa([a],i.rank);let n=da(e,a,s,!r);return null!=t&&(n=hi(n,t)),n}}}},wu={kernelName:ye,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:i,strides:a,pad:s,dimRoundingMode:r}=n,o=null==i?[1,1]:i;I(ji(o),(()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`));const[l,c]=t;return I(4===l.rank,(()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`)),I(4===c.rank,(()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`)),I(l.shape[3]===c.shape[2],(()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`)),I(zi(a,o),(()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${o}'.`)),Fi("depthwiseConv2d",s,r),{x:()=>ar(l.shape,e,c,a,s,o,r),filter:()=>ir(l,e,c.shape,a,s,o,r)}}},ku={kernelName:"Dilation2D",inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[i,a]=t,s={x:i,filter:a,dy:e},r={x:i,filter:a,dy:e};return{x:()=>sn.runKernel("Dilation2DBackpropInput",s,n),filter:()=>sn.runKernel("Dilation2DBackpropFilter",r,n)}}},xu={kernelName:we,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,i={dy:e,y:n};return{x:()=>sn.runKernel("EluGrad",i)}}},Su={kernelName:"Erf",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,i=xi(Fa(ci($a(n))),2/Math.sqrt(Math.PI));return{x:()=>xi(e,i)}}},Nu={kernelName:"Exp",outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,n)}}},Iu={kernelName:ke,inputsToSave:["input"],gradFunc:(e,t)=>{const[n]=t;return{input:()=>_i(e,n.shape)}}},Tu={kernelName:"Expm1",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,Fa(n))}}},Eu={kernelName:xe,gradFunc:e=>({x:()=>ya(e)})},Au={kernelName:Se,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=ki(e,ei(i,"float32")),s=di(n.shape,a);return s.length>0?_i(ja(t,s),n.shape):t},b:()=>{let t=xi(e,ei(n,"float32"));const s=di(i.shape,a);s.length>0&&(t=_i(ja(t,s),i.shape));const r=$a(i);return ci(ki(t,ei(r,"float32")))}}}},Cu={kernelName:Ne,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:i}=n,[a,s,r,o]=t,l=null==o?Aa(1):o,c=di(s.shape,a.shape),u=[];if(1===s.rank){for(let e=0;e<a.shape.length-1;++e)u.push(a.shape[e]);u.push(1)}const h=Ja(a,s),p=xi(e,l),d=js(bi(r,Aa(i))),m=xi(xi(xi(d,d),d),Aa(-.5));return{x:()=>1===s.rank?_i(xi(xi(e,Ra(_i(d,[1,1,1,s.shape[0]]),u)),l),a.shape):_i(xi(xi(e,d),l),a.shape),mean:()=>{let e=xi(xi(d,Aa(-1)),p);return 1===s.rank&&(e=ja(e,c)),_i(e,s.shape)},variance:()=>{let e=xi(xi(m,h),p);return 1===s.rank&&(e=ja(e,c)),_i(e,s.shape)},scale:()=>{const t=xi(h,d);let n=xi(e,t);return 1===s.rank&&(n=ja(n,c)),_i(n,s.shape)},offset:()=>{let t=e;return 1===s.rank&&(t=ja(t,c)),_i(t,s.shape)}}}},$u={kernelName:Ie,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[i,a]=t,{axis:s}=n,r=z(s,i.shape)[0];return{x:()=>{const t=i.shape,n=a.size,o=t.slice(0,r),l=o.length,c=t.slice(s,t.length).slice(1),u=c.length,h=ju(0,l),p=ju(l+1,l+1+u),d=zu([o,[n],c]),m=_i(e,d),f=_i(a,[n]),g=zu([[l],h,p]),v=hi(m,g);let y=Hs(v,f,i.shape[r]);const b=Na(g);return y=hi(y,b),y},indices:()=>a}}};
|
|
4006
4006
|
/**
|
|
4007
4007
|
* @license
|
|
4008
4008
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -4034,7 +4034,7 @@ function(e,t,n,i,a){let s=e;4===e.rank&&(s=_i(e,[1,e.shape[0],e.shape[1],e.shape
|
|
|
4034
4034
|
* See the License for the specific language governing permissions and
|
|
4035
4035
|
* limitations under the License.
|
|
4036
4036
|
* =============================================================================
|
|
4037
|
-
*/const Du={kernelName:Te,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t;return{a:()=>ya(n),b:()=>ya(i)}}},Fu={kernelName:
|
|
4037
|
+
*/const Du={kernelName:Te,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t;return{a:()=>ya(n),b:()=>ya(i)}}},Fu={kernelName:Ee,gradFunc:e=>({x:()=>ei(e,"float32")})},_u={kernelName:"IsFinite",gradFunc:e=>({x:()=>ya(e)})},Ru={kernelName:"IsInf",gradFunc:e=>({x:()=>ya(e)})},Lu={kernelName:"IsNan",gradFunc:e=>({x:()=>ya(e)})},Mu={kernelName:Ae,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{alpha:a}=n,s=Pa(i,0);return{x:()=>va(s,e,xi(e,a))}}},Ou={kernelName:Ce,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,bi(n,1))}}},Pu={kernelName:"Log",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,ei(n,"float32"))}}},Bu={kernelName:"LogSoftmax",inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[i]=t,{axis:a}=n;return{logits:()=>{const t=Fa(i);return Ja(e,xi(ja(e,a,!0),t))}}}};
|
|
4038
4038
|
/**
|
|
4039
4039
|
* @license
|
|
4040
4040
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -4182,7 +4182,7 @@ function(e,t,n,i,a,s,r){const o=hn(e,"dy","maxPool3dGrad"),l=hn(t,"input","maxPo
|
|
|
4182
4182
|
* limitations under the License.
|
|
4183
4183
|
* =============================================================================
|
|
4184
4184
|
*/
|
|
4185
|
-
function(e,t,n,i,a,s,r){const o=hn(e,"dy","maxPoolGrad"),l=hn(t,"input","maxPoolGrad"),c=hn(n,"output","maxPoolGrad");I(l.rank===o.rank,(()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`)),I(4===o.rank,(()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`)),I(4===l.rank,(()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`)),Fi("maxPoolGrad",s,r);const u={dy:o,input:l,output:c},h={filterSize:i,strides:a,pad:s,dimRoundingMode:r};return sn.runKernel("MaxPoolGrad",u,h)}}),Zu={kernelName:je,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[i,a]=t,{filterSize:s,strides:r,pad:o}=n;return{x:()=>Ju(e,i,a,s,r,o)}}},Yu={kernelName:Oe,inputsToSave:["x"],gradFunc:(e,t,n)=>{const i=t[0],{paddings:a}=n,s=a.map((e=>e[0]));return{x:()=>Bi(e,s,i.shape)}}},Qu={kernelName:"Pow",inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,i,a]=t,s=n,r=i,o=mi(s.shape,r.shape);return{a:()=>{const t=ei(r,"float32");let n=xi(e,xi(t,
|
|
4185
|
+
function(e,t,n,i,a,s,r){const o=hn(e,"dy","maxPoolGrad"),l=hn(t,"input","maxPoolGrad"),c=hn(n,"output","maxPoolGrad");I(l.rank===o.rank,(()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`)),I(4===o.rank,(()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`)),I(4===l.rank,(()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`)),Fi("maxPoolGrad",s,r);const u={dy:o,input:l,output:c},h={filterSize:i,strides:a,pad:s,dimRoundingMode:r};return sn.runKernel("MaxPoolGrad",u,h)}}),Zu={kernelName:je,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[i,a]=t,{filterSize:s,strides:r,pad:o}=n;return{x:()=>Ju(e,i,a,s,r,o)}}},Yu={kernelName:Oe,inputsToSave:["x"],gradFunc:(e,t,n)=>{const i=t[0],{paddings:a}=n,s=a.map((e=>e[0]));return{x:()=>Bi(e,s,i.shape)}}},Qu={kernelName:"Pow",inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,i,a]=t,s=n,r=i,o=mi(s.shape,r.shape);return{a:()=>{const t=ei(r,"float32");let n=xi(e,xi(t,Ea(s,Ja(t,Aa(1)))));const i=di(s.shape,o);return i.length>0&&(n=ja(n,i)),_i(n,s.shape)},b:()=>{const t=Pa(s,0),n=va(t,Va(s),ya(s));let i=xi(e,xi(a,n));const l=di(r.shape,o);return l.length>0&&(i=ja(i,l)),_i(i,r.shape)}}}};
|
|
4186
4186
|
/**
|
|
4187
4187
|
* @license
|
|
4188
4188
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -4248,7 +4248,7 @@ function(e,t,n){const i=e.shape.slice();i[n]=1;const a=_i(t,i),s=pa(e,n,!0,!1),r
|
|
|
4248
4248
|
* limitations under the License.
|
|
4249
4249
|
* =============================================================================
|
|
4250
4250
|
*/
|
|
4251
|
-
const nh=[Wc,Gc,Vc,Kc,qc,Hc,Jc,Zc,Yc,Qc,Xc,eu,nu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,du,gu,vu,yu,bu,wu,ku,{kernelName:be,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=ki(e,ei(i,"float32")),s=di(n.shape,a);return s.length>0?_i(ja(t,s),n.shape):t},b:()=>{let t=xi(e,ei(n,"float32"));const s=di(i.shape,a);s.length>0&&(t=_i(ja(t,s),i.shape));const r=$a(i);return ci(ki(t,ei(r,"float32")))}}}},xu,Su,Nu,Iu,Tu,Eu,
|
|
4251
|
+
const nh=[Wc,Gc,Vc,Kc,qc,Hc,Jc,Zc,Yc,Qc,Xc,eu,nu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,du,gu,vu,yu,bu,wu,ku,{kernelName:be,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=ki(e,ei(i,"float32")),s=di(n.shape,a);return s.length>0?_i(ja(t,s),n.shape):t},b:()=>{let t=xi(e,ei(n,"float32"));const s=di(i.shape,a);s.length>0&&(t=_i(ja(t,s),i.shape));const r=$a(i);return ci(ki(t,ei(r,"float32")))}}}},xu,Su,Nu,Iu,Tu,Au,Eu,Cu,$u,Du,Fu,_u,Ru,Lu,Mu,Ou,Pu,Bu,Wu,Vu,Vu,Ku,Hu,Zu,{kernelName:De,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{axis:a}=n,s=z(a,i.shape),r=A(ka(i.shape,s)[1]);return{x:()=>{const t=i.shape.slice();s.forEach((e=>{t[e]=1}));const n=_i(e,t);return ki(xi(n,as(i.shape,"float32")),r)}}}},{kernelName:"Min",inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const i=n,{axis:a}=i,[s,r]=t,o=Gu(e,r,s,z(a,s.shape));return{x:()=>o.x()}}},{kernelName:Fe,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t;return{a:()=>xi(e,ei(Ga(n,i),"float32")),b:()=>xi(e,ei(Pa(n,i),"float32"))}}},{kernelName:"MirrorPad",inputsToSave:["x"],gradFunc:(e,t,n)=>{const i=t[0],{paddings:a}=n,s=a.map((e=>e[0]));return{x:()=>Bi(e,s,i.shape)}}},{kernelName:"Mod",inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=di(n.shape,a);return t.length>0?_i(ja(e,t),n.shape):e},b:()=>{const t=xi(e,ci(Ma(ki(n,i)))),s=di(i.shape,a);return s.length>0?_i(ja(t,s),i.shape):t}}}},{kernelName:_e,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=xi(e,ei(i,"float32")),s=di(n.shape,a);return s.length>0?_i(ja(t,s),n.shape):t},b:()=>{const t=xi(e,ei(n,"float32")),s=di(i.shape,a);return s.length>0?_i(ja(t,s),i.shape):t}}}},{kernelName:"Neg",gradFunc:e=>({x:()=>ci(e)})},{kernelName:Le,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>is(n.shape,"float32")}}},{kernelName:Re,gradFunc:e=>({x:()=>ya(e)})},{kernelName:Me,saveAllInputs:!0,gradFunc:(e,t,n)=>{const{axis:i}=n;return Js(e,i).map((e=>()=>e))}},Yu,Yu,Qu,{kernelName:Pe,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,i]=t,a=Pa(n,0);return{x:()=>va(a,e,xi(e,i)),alpha:()=>{let t=va(a,ya(e),xi(e,n));const s=di(i.shape,e.shape);return s.length>0&&(t=ja(t,s)),_i(t,i.shape)}}}},{kernelName:"Prod",inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{axis:a}=n;let s=[];return s=null==a?i.shape.map(((e,t)=>t)):"number"==typeof a?[a]:a,{x:()=>Xu(i,e,s)}}},{kernelName:"Reciprocal",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,ci($a(n)))}}},{kernelName:Ve,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,i=xi(Ga(n,6),Gs(n));return{x:()=>xi(e,ei(i,"float32"))}}},{kernelName:Be,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,ei(Gs(n),"float32"))}}},{kernelName:Ue,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(e,n.shape)}}},{kernelName:Ge,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[i]=t,a={dy:e,images:i};return{images:()=>sn.runKernel("ResizeBilinearGrad",a,n)}}},{kernelName:We,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[i]=t,a={dy:e,images:i};return{images:()=>sn.runKernel("ResizeNearestNeighborGrad",a,n)}}},{kernelName:Ke,gradFunc:(e,t,n)=>{const{dims:i}=n,a=z(i,e.shape);return{x:()=>Cs(e,a)}}},{kernelName:qe,gradFunc:e=>({x:()=>ya(e)})},{kernelName:He,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ci(ki(e,xi(Ea(n,1.5),2)))}}},{kernelName:Je,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>ei(ya(n),"float32"),t:()=>xi(e,ei(n,e.dtype)),e:()=>xi(e,ei(Qa(n),e.dtype))}}},{kernelName:Ze,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Pa(n,Aa(0)),i=Aa(1.7580993408473768),a=Aa(1.0507009873554805),s=xi(e,a),r=xi(xi(e,i),Fa(ei(n,"float32")));return va(t,s,r)}}}},{kernelName:Xe,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,xi(n,Ja(Aa(1),n)))}}},{kernelName:"Sign",gradFunc:e=>({x:()=>ya(e)})},{kernelName:"Sin",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(ua(ei(n,"float32")),e)}}},{kernelName:Qe,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(ha(ei(n,"float32")),e)}}},{kernelName:Ye,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{begin:a,size:s}=n,r=i.shape,[o,l]=fi(i,a,s),c=[];for(let t=0;t<e.rank;t++)c.push([o[t],r[t]-o[t]-l[t]]);return{x:()=>cs(e,c)}}},{kernelName:st,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[i]=t,{dim:a}=n,s=xi(e,i);return{logits:()=>Ja(s,xi(ja(s,[a],true),i))}}},{kernelName:et,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,Pi(n))}}},eh,eh,th,th,{kernelName:tt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,xi(Ca(ei(n,"float32")),2))}}},{kernelName:rt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=Aa(2);return{a:()=>xi(e,xi(a,Ja(n,i))),b:()=>xi(e,xi(a,Ja(i,n)))}}},{kernelName:"Square",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,xi(ei(n,"float32"),2))}}},{kernelName:dt,gradFunc:e=>({x:()=>ya(e)})},{kernelName:"Sub",inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{let t=e;const i=di(n.shape,a);return i.length>0&&(t=ja(t,i)),_i(t,n.shape)},b:()=>{let t=e;const n=di(i.shape,a);return n.length>0&&(t=ja(t,n)),_i(ci(t),i.shape)}}}},{kernelName:nt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,a=i.shape.slice(),{axis:s}=n;z(s,i.shape).forEach((e=>{a[e]=1}));const r=_i(e,a),o=xi(r,as(i.shape,"float32"));return{x:()=>o}}},{kernelName:"Tan",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,$a(ua(n)))}}},{kernelName:ot,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(Ja(Aa(1),$a(n)),e)}}},{kernelName:lt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{reps:a}=n;return{x:()=>{let t=ya(i);if(1===i.rank)for(let n=0;n<a[0];++n)t=bi(t,Bi(e,[n*i.shape[0]],[i.shape[0]]));else if(2===i.rank)for(let n=0;n<a[0];++n)for(let s=0;s<a[1];++s)t=bi(t,Bi(e,[n*i.shape[0],s*i.shape[1]],[i.shape[0],i.shape[1]]));else if(3===i.rank)for(let n=0;n<a[0];++n)for(let s=0;s<a[1];++s)for(let r=0;r<a[2];++r)t=bi(t,Bi(e,[n*i.shape[0],s*i.shape[1],r*i.shape[2]],[i.shape[0],i.shape[1],i.shape[2]]));else{if(4!==i.rank)throw new Error(`Gradient for tile operation is not implemented for rank-${i.rank} tensors yet.`);for(let n=0;n<a[0];++n)for(let s=0;s<a[1];++s)for(let r=0;r<a[2];++r)for(let o=0;o<a[3];++o)t=bi(t,Bi(e,[n*i.shape[0],s*i.shape[1],r*i.shape[2],o*i.shape[3]],[i.shape[0],i.shape[1],i.shape[2],i.shape[3]]))}return t}}}},{kernelName:ct,gradFunc:(e,t,n)=>{const i=n,{perm:a}=i,s=Na(a);return{x:()=>hi(e,s)}}},{kernelName:ut,gradFunc:(e,t,n)=>{const i=n,{axis:a}=i;return{value:()=>Ws(e,a)}}},{kernelName:ht,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>function(e,t){const n=ts(t,ya(t)),i=Oa(e,n);let a=Ba(t,Aa(0,"int32"));const s=i.rank-a.rank;for(let e=0;e<s;++e)a=_a(a,e+1);a=Ya(a,as(i.shape,"bool"));const r=ya(i);return va(a,i,r)}(e,n)}}},{kernelName:pt,gradFunc:e=>({x:()=>ya(e)})}];
|
|
4252
4252
|
/**
|
|
4253
4253
|
* @license
|
|
4254
4254
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -4273,7 +4273,7 @@ const nh=[Wc,Gc,Vc,Kc,qc,Hc,Jc,Zc,Yc,Qc,Xc,eu,nu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,d
|
|
|
4273
4273
|
* license that can be found in the LICENSE file or at
|
|
4274
4274
|
* https://opensource.org/licenses/MIT.
|
|
4275
4275
|
* =============================================================================
|
|
4276
|
-
*/function ih(e,t){return si((()=>Ca(ja(xi(e,e),t,!0))))}class ah extends gi{getConfig(){return{}}}class sh extends ah{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return si((()=>{const t=ih(e,this.axis),n=Qi(t,0,this.maxValue);return xi(e,ki(n,bi(Fl(),t)))}))}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}sh.className="MaxNorm",yi(sh);class rh extends ah{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return si((()=>ki(e,bi(Fl(),ih(e,this.axis)))))}getConfig(){return{axis:this.axis}}}rh.className="UnitNorm",yi(rh);class oh extends ah{apply(e){return
|
|
4276
|
+
*/function ih(e,t){return si((()=>Ca(ja(xi(e,e),t,!0))))}class ah extends gi{getConfig(){return{}}}class sh extends ah{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return si((()=>{const t=ih(e,this.axis),n=Qi(t,0,this.maxValue);return xi(e,ki(n,bi(Fl(),t)))}))}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}sh.className="MaxNorm",yi(sh);class rh extends ah{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return si((()=>ki(e,bi(Fl(),ih(e,this.axis)))))}getConfig(){return{axis:this.axis}}}rh.className="UnitNorm",yi(rh);class oh extends ah{apply(e){return Es(e)}}oh.className="NonNeg",yi(oh);class lh extends ah{constructor(e){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=null!=e.minValue?e.minValue:this.defaultMinValue,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.rate=null!=e.rate?e.rate:this.defaultRate,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return si((()=>{const t=ih(e,this.axis),n=bi(xi(this.rate,Qi(t,this.minValue,this.maxValue)),xi(1-this.rate,t));return xi(e,ki(n,bi(Fl(),t)))}))}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}lh.className="MinMaxNorm",yi(lh);const ch={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function uh(e){return Xo(e)}function hh(e,t={}){return tl(e,vi.getMap().classNameMap,t,"constraint")}function ph(e){if(null==e)return null;if("string"==typeof e){return hh({className:e in ch?ch[e]:e,config:{}})}return e instanceof ah?e:hh(e)}
|
|
4277
4277
|
/**
|
|
4278
4278
|
* @license
|
|
4279
4279
|
* Copyright 2018 Google LLC
|
|
@@ -4309,7 +4309,7 @@ const nh=[Wc,Gc,Vc,Kc,qc,Hc,Jc,Zc,Yc,Qc,Xc,eu,nu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,d
|
|
|
4309
4309
|
* license that can be found in the LICENSE file or at
|
|
4310
4310
|
* https://opensource.org/licenses/MIT.
|
|
4311
4311
|
* =============================================================================
|
|
4312
|
-
*/function Ih(e,t){return si((()=>{"float32"!==e.dtype&&(e=ei(e,"float32"));const n=ja(Kl(e),t,!0),i=Yi(n.shape,Fl()),a=Ca(ts(n,i));return ki(e,a)}))}function Th(e,t){return si((()=>ns(Kl(Ja(t,e)),-1)))}function
|
|
4312
|
+
*/function Ih(e,t){return si((()=>{"float32"!==e.dtype&&(e=ei(e,"float32"));const n=ja(Kl(e),t,!0),i=Yi(n.shape,Fl()),a=Ca(ts(n,i));return ki(e,a)}))}function Th(e,t){return si((()=>ns(Kl(Ja(t,e)),-1)))}function Eh(e,t){return si((()=>ns(Si(Ja(t,e)),-1)))}function Ah(e,t){return si((()=>{const n=Ja(e,t),i=Qi(Si(e),Fl(),Number.MAX_VALUE),a=Si(ki(n,i));return xi(100,ns(a,-1))}))}function Ch(e,t,n=!1){return si((()=>{if(n)t=Ps(t);else{const e=ja(t,t.shape.length-1,!0);t=ki(t,e)}return t=Qi(t,Fl(),1-Fl()),ci(ja(xi(ei(e,"float32"),Va(t)),t.shape.length-1))}))}function $h(e,t,n=!1){return si((()=>{const i=ei(Ma(function(e){const t=[Cl(e.shape)];return _i(e,t)}(e)),"int32"),a=(t=Qi(t,Fl(),1-Fl())).shape;return Ch(_i(ni(i,a[a.length-1]),a),t,n)}))}function jh(e,t){return si((()=>{let n;return n=Qi(t,Fl(),1-Fl()),n=Va(ki(n,Ja(1,n))),ns(function(e,t){if(!C(e.shape,t.shape))throw new Bo(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return si((()=>{const n=Es(t),i=ci(Si(t));return bi(Ja(n,xi(t,e)),Ka(Fa(i)))}))}(e,n),-1)}))}function zh(e,t){return si((()=>{const n=Ih(e,-1),i=Ih(t,-1),a=xi(n,i);return ci(ja(a,-1))}))}xh.constructors={};const Dh={meanSquaredError:Th,meanAbsoluteError:Eh,meanAbsolutePercentageError:Ah,meanSquaredLogarithmicError:function(e,t){return si((()=>{const n=Qi(t,Fl(),Number.MAX_VALUE),i=Va(bi(1,n)),a=Qi(e,Fl(),Number.MAX_VALUE),s=Va(bi(1,a));return ns(Kl(Ja(i,s)),-1)}))},squaredHinge:function(e,t){return si((()=>{const n=ts(0,Ja(1,xi(e,t)));return ns(Kl(n),-1)}))},hinge:function(e,t){return si((()=>{const n=ts(0,Ja(1,xi(e,t)));return ns(n,-1)}))},categoricalHinge:function(e,t){return si((()=>{const n=ja(xi(e,t),-1),i=Ia(xi(Ja(1,e),t),-1);return ts(0,bi(1,Ja(i,n)))}))},logcosh:function(e,t){return si((()=>{const n=Math.log(2),i=Ja(t,e),a=Ja(bi(i,Ha(xi(-2,i))),n);return ns(a,-1)}))},categoricalCrossentropy:Ch,sparseCategoricalCrossentropy:$h,binaryCrossentropy:jh,kullbackLeiblerDivergence:function(e,t){return si((()=>{const n=Qi(e,Fl(),1),i=Qi(t,Fl(),1);return ja(xi(e,Va(ki(n,i))),-1)}))},poisson:function(e,t){return si((()=>{const n=Va(bi(Fl(),t));return ns(Ja(t,xi(e,n)),-1)}))},cosineProximity:zh};function Fh(e){if("string"==typeof e){if(e in Dh)return Dh[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new Bo(t)}return e}
|
|
4313
4313
|
/**
|
|
4314
4314
|
* @license
|
|
4315
4315
|
* Copyright 2018 Google LLC
|
|
@@ -4318,7 +4318,7 @@ const nh=[Wc,Gc,Vc,Kc,qc,Hc,Jc,Zc,Yc,Qc,Xc,eu,nu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,d
|
|
|
4318
4318
|
* license that can be found in the LICENSE file or at
|
|
4319
4319
|
* https://opensource.org/licenses/MIT.
|
|
4320
4320
|
* =============================================================================
|
|
4321
|
-
*/function _h(e,t){return si((()=>{const n=xi(.5,ls(t)),i=_l(Pa(t,n),e.dtype);return ns(ga(e,i),-1)}))}function Rh(e,t){return si((()=>_l(ga(Ti(e,-1),Ti(t,-1)),"float32")))}function Lh(e,t){return jh(e,t)}function Mh(e,t){return e.rank===t.rank&&(e=Us(e,[e.rank-1])),(t=Ti(t,-1)).dtype!==e.dtype&&(t=ei(t,e.dtype)),ei(ga(e,t),"float32")}const Oh=Ch,Ph=$h,Bh={binaryAccuracy:_h,categoricalAccuracy:Rh,precision:function(e,t){return si((()=>{const n=function(e,t){return si((()=>ei(ja(Ya(ga(e,1),ga(t,1))),"float32")))}(e,t),i=function(e,t){return si((()=>ei(ja(Ya(ga(e,0),ga(t,1))),"float32")))}(e,t),a=bi(n,i);return ei(va(Pa(a,0),ki(n,a),0),"float32")}))},categoricalCrossentropy:Oh,sparseCategoricalCrossentropy:Ph,mse:Th,MSE:Th,mae:
|
|
4321
|
+
*/function _h(e,t){return si((()=>{const n=xi(.5,ls(t)),i=_l(Pa(t,n),e.dtype);return ns(ga(e,i),-1)}))}function Rh(e,t){return si((()=>_l(ga(Ti(e,-1),Ti(t,-1)),"float32")))}function Lh(e,t){return jh(e,t)}function Mh(e,t){return e.rank===t.rank&&(e=Us(e,[e.rank-1])),(t=Ti(t,-1)).dtype!==e.dtype&&(t=ei(t,e.dtype)),ei(ga(e,t),"float32")}const Oh=Ch,Ph=$h,Bh={binaryAccuracy:_h,categoricalAccuracy:Rh,precision:function(e,t){return si((()=>{const n=function(e,t){return si((()=>ei(ja(Ya(ga(e,1),ga(t,1))),"float32")))}(e,t),i=function(e,t){return si((()=>ei(ja(Ya(ga(e,0),ga(t,1))),"float32")))}(e,t),a=bi(n,i);return ei(va(Pa(a,0),ki(n,a),0),"float32")}))},categoricalCrossentropy:Oh,sparseCategoricalCrossentropy:Ph,mse:Th,MSE:Th,mae:Eh,MAE:Eh,mape:Ah,MAPE:Ah,cosine:zh};function Uh(e){if("string"==typeof e&&e in Bh)return Bh[e];if("string"!=typeof e&&null!=e)return e;throw new Bo(`Unknown metric ${e}`)}function Wh(e){if(Ko(null!==e,`Unknown LossOrMetricFn ${e}`),"string"==typeof e)return e;{let t;for(const n of Object.keys(Dh))if(Dh[n]===e){t=n;break}if(void 0!==t)return t;for(const n of Object.keys(Bh))if(Bh[n]===e){t=n;break}return void 0!==t?t:e.name}}
|
|
4322
4322
|
/**
|
|
4323
4323
|
* @license
|
|
4324
4324
|
* Copyright 2018 Google LLC
|
|
@@ -4365,7 +4365,7 @@ const Gh=1048576;function Vh(e,t,n=!1){if(null==e||"object"!=typeof e||Object.ge
|
|
|
4365
4365
|
* license that can be found in the LICENSE file or at
|
|
4366
4366
|
* https://opensource.org/licenses/MIT.
|
|
4367
4367
|
* =============================================================================
|
|
4368
|
-
*/class tp extends Dc{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,null==this.name){const e=this.getClassName().toLowerCase();this.name=dl(e)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],il(this.inputs).length!==this.inputs.length)throw new Bo(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map((e=>e.name))}`);il(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map((e=>e.name))}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const e of this.outputs){const t=e.sourceLayer,n=e.nodeIndex,i=e.tensorIndex;this.outputLayers.push(t),this.outputLayersNodeIndices.push(n),this.outputLayersTensorIndices.push(i)}for(const e of this.inputs){const t=e.sourceLayer,n=e.nodeIndex,i=e.tensorIndex;Ko(0===n,"input layer has >1 nodes"),Ko(0===i,"input layer has >1 tensors"),this.inputLayers.push(t),this.inputLayersNodeIndices.push(n),this.inputLayersTensorIndices.push(i)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let t=0;t<this.inputLayers.length;t++){const n=this.inputLayers[t];if(!(n instanceof _c))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${t} (0-based) originates from layer type ${n.getClassName()}.`);this.inputNames.push(n.name),this.feedInputShapes.push(n.batchInputShape),this.feedInputNames.push(n.name)}for(const e of this.outputLayers)this.outputNames.push(e.name);this.internalInputShapes=this.inputs.map((e=>e.shape)),this.internalOutputShapes=this.outputs.map((e=>e.shape));const t={},n={},i={},a={},s={},r=[],o=(e,t,n,i,a,l)=>{null!=i&&null!=a&&null!=l||(i=e.sourceLayer,a=e.nodeIndex,l=e.tensorIndex);const c=i.inboundNodes[a];if(-1!==n.indexOf(c))throw new Po(`The tensor ${e.name} at layer "${i.name}" is part of a cycle.`);if(-1!==t.indexOf(c))return;this.containerNodes.add(tp.nodeKey(i,a)),i.id in s||(s[i.id]=Object.keys(s).length),-1===n.indexOf(c)&&n.push(c);const u=c.inboundLayers.length;for(let e=0;e<u;e++){const i=c.inputTensors[e],a=c.inboundLayers[e],s=c.nodeIndices[e],r=c.tensorIndices[e];o(i,t,n,a,s,r)}for(t.push(c);n.indexOf(c)>=0;)n.splice(n.indexOf(c),1);r.push(c)},l=[],c=[];for(const e of this.outputs)o(e,l,c);const u=r.slice().reverse();for(const e of u){n[e.id]=e,e.id in t||(t[e.id]=0);let s=t[e.id];const r=null==i[e.outboundLayer.id]?0:i[e.outboundLayer.id];s=Math.max(s,r),i[e.outboundLayer.id]=s,a[e.outboundLayer.id]=e.outboundLayer,t[e.id]=s;for(let i=0;i<e.inboundLayers.length;i++){const a=e.inboundLayers[i],r=e.nodeIndices[i],o=a.inboundNodes[r],l=null==t[o.id]?0:t[o.id];t[o.id]=Math.max(s+1,l),n[o.id]=o}}const h={};for(const e in t){const i=t[e];i in h||(h[i]=[]),h[i].push(n[e])}const p={};for(const e in i){const t=i[e];t in p||(p[t]=[]),p[t].push(a[e])}let d=Object.keys(p).map((e=>parseInt(e,10))).sort(nl);this.layers=[];for(const e of d){const t=p[e];t.sort(((e,t)=>{const n=s[e.id],i=s[t.id];return n<i?-1:n>i?1:0}));for(const e of t)e instanceof tp&&this.internalContainerRefs.push(e),this.layers.push(e)}this.layersByDepth=p,d=Object.keys(h).map((e=>parseInt(e,10))).sort(nl);const m=this.inputs.slice(),f=[];for(const e of d)for(const t of h[e]){const e=t.outboundLayer;if(null!=e){for(const n of t.inputTensors)if(-1===m.indexOf(n))throw new Po(`Graph disconnected: cannot obtain value for tensor ${n} at layer "${e.name}". The following previous layers were accessed without issue: ${f}`);for(const e of t.outputTensors)m.push(e);f.push(e.name)}}this.nodesByDepth=h;const g=this.layers.map((e=>e.name));for(const e of g){const t=g.filter((t=>t===e)).length;if(1!==t)throw new Po(`The name "${e}" is used ${t} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new jc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map((e=>null)),outputMasks:this.outputs.map((e=>null)),inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs.map((e=>e.shape))}),this.built=!0,this._refCount=1}assertNotDisposed(){if(0===this._refCount)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach((t=>{t._trainableWeights.forEach((t=>t.trainable=e))})),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new Bo("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.layers)t.push(...e.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const n={};let i=0;for(const e of this.layers)for(const t of e.weights){if(null!=n[t.originalName])throw new Bo(`Duplicate weight name: ${t.originalName}`);n[t.originalName]=t,i++}const a=[];for(const i in e){let s=i;if(null==n[i]){const e=i.split("/");s=e.slice(0,-2).concat([e[e.length-1]]).join("/")}if(null!=n[s])a.push([n[s],e[i]]);else if(t)throw new Bo(`Provided weight data has no target variable: ${i}`);delete n[s]}if(t){const e=[];for(const t in n)e.push(t);if(e.length>0)throw new Bo(`${e.length} of ${i} weights are not set: ${e}`)}Ac(a)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${ep}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=Xh(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return si((()=>{e=Jo(e);const n=new Rc;for(let t=0;t<this.inputs.length;++t)n.add(this.inputs[t],e[t]);return Oc(this.outputs,n,t)}))}computeMask(e,t){return si((()=>{let n;return e=Jo(e),n=null==t?Vo(null,e.length):Jo(t),this.runInternalGraph(e,n)[1]}))}computeOutputShape(e){const t=wc(e);if(t.length!==this.inputLayers.length)throw new Bo(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let e=0;e<t.length;e++){const i=this.inputLayers[e],a=t[e];n[i.name+"_0_0"]=a}const i=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(nl);if(i.length>1)for(const e of i){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer;if(-1!==this.inputLayers.map((e=>e.id)).indexOf(t.id))continue;const i=[];for(let t=0;t<e.inboundLayers.length;t++){const a=e.inboundLayers[t],s=e.nodeIndices[t],r=e.tensorIndices[t],o=n[`${a.name}_${s}_${r}`];i.push(o)}const a=wc(t.computeOutputShape(Ho(i))),s=t.inboundNodes.indexOf(e);for(let e=0;e<a.length;e++){n[`${t.name}_${s}_${e}`]=a[e]}}}const a=[],s=[];for(let e=0;e<this.outputLayers.length;e++){const t=this.outputLayers[e],n=this.outputLayersNodeIndices[e],i=this.outputLayersTensorIndices[e],a=`${t.name}_${n}_${i}`;s.push(a)}for(let e=0;e<s.length;e++){const t=s[e];Ko(t in n),a.push(n[t])}return Ho(a)}runInternalGraph(e,t){null==t&&(t=Vo(null,e.length));const n={};for(let i=0;i<this.inputs.length;++i){const a=this.inputs[i],s=e[i],r=t[i];n[a.id]=[s,r]}const i=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(nl);for(const e of i){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer,i=e.inputTensors,a=e.outputTensors,s=new Array;for(const e of i)e.id in n&&s.push(n[e.id]);if(s.length===i.length){let i,r,o,l,c={};if(null!=e.callArgs&&(c=e.callArgs),1===s.length){const[e,n]=s[0];null==c.mask&&(c.mask=n),o=Jo(t.call(e,c)),l=Jo(t.computeMask(e,n)),i=[e],r=[n]}else i=s.map((e=>e[0])),r=s.map((e=>e[1])),null==c.mask&&(c.mask=r),o=Jo(t.call(i,c)),l=Jo(t.computeMask(i,r));if(t.activityRegularizer)throw new Uo("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let e=0;e<a.length;++e){const t=a[e],i=o[e],s=l[e];n[t.id]=[i,s]}}}}const a=[],s=[],r=[];for(const e of this.outputs){Ko(e.id in n,`Could not compute output ${e.name} : ${e.id}`);const[t,i]=n[e.id];r.push(t.shape),a.push(t),s.push(i)}return[a,s,r]}buildNodeConversionMap(e){const t={};let n;for(const e of this.layers){n=e instanceof tp?1:0;for(let i=0;i<e.inboundNodes.length;i++){const a=tp.nodeKey(e,i);this.containerNodes.has(a)&&(t[a]=n,n+=1)}}return t}getLayer(e,t){if(null!=t){if(this.layers.length<=t)throw new Bo(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}if(null==e)throw new Bo("Provide either a layer name or layer index");for(const t of this.layers)if(t.name===e)return t;throw new Bo(`No such layer: ${e}`)}calculateLosses(){return si((()=>{const e=[];for(const t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){const i=tp.nodeKey(t,n);this.containerNodes.has(i)&&e.push(...t.calculateLosses())}return e}))}getConfig(){const e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(const e of this.layers){const i=e.getClassName(),a=e.getConfig(),s=[];for(let n=0;n<e.inboundNodes.length;n++){const i=e.inboundNodes[n],a=tp.nodeKey(e,n);let r={};if(this.containerNodes.has(a)){if(i.callArgs)try{JSON.stringify(i.callArgs),r=i.callArgs}catch(t){console.warn(`Layer ${e.name} was passed non-serializable keyword arguments: ${i.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),r={}}if(i.inboundLayers.length>0){const e=[];for(let n=0;n<i.inboundLayers.length;n++){const a=i.inboundLayers[n],s=i.nodeIndices[n],o=i.tensorIndices[n];let l=t[tp.nodeKey(a,s)];null==l&&(l=0),e.push([a.name,l,o,r])}s.push(e)}}}const r={};r.name=e.name,r.className=i,r.config=a,r.inboundNodes=s,n.push(r)}e.layers=n;const i=[];for(let e=0;e<this.inputLayers.length;e++){const n=this.inputLayers[e],a=this.inputLayersNodeIndices[e],s=tp.nodeKey(n,a);if(!this.containerNodes.has(s))continue;let r=t[s];null==r&&(r=0);const o=this.inputLayersTensorIndices[e];i.push([n.name,r,o])}e.inputLayers=i;const a=[];for(let e=0;e<this.outputLayers.length;e++){const n=this.outputLayers[e],i=this.outputLayersNodeIndices[e],s=tp.nodeKey(n,i);if(!this.containerNodes.has(s))continue;let r=t[s];null==r&&(r=0);const o=this.outputLayersTensorIndices[e];a.push([n.name,r,o])}return e.outputLayers=a,e}static fromConfig(e,t,n={},i=!1){const a={},s={};function r(e,t){e.name in s?s[e.name].push(t):s[e.name]=[t]}function o(e,t){const n=[];let i;for(const s of t){const o=s[0],l=s[1],c=s[2];if(i=null==s[3]?{}:s[3],!(o in a))return void r(e,t);const u=a[o];if(u.inboundNodes.length<=l)return void r(e,t);const h=u.inboundNodes[l];n.push(h.outputTensors[c])}n.length>0&&e.apply(Ho(n),i)}function l(e){const n=e.name,s=Nh(e,null!=t.customObjects?t.customObjects:{});s.setFastWeightInitDuringBuild(i),a[n]=s;e.inboundNodes.forEach((e=>{if(!(e instanceof Array))throw new Bo(`Corrupted configuration, expected array for nodeData: ${e}`);r(s,e)}))}const c=t.name,u=t.layers;for(const e of u)l(e);for(;!al(s);)for(const e of u){const t=a[e.name];if(t.name in s){const e=s[t.name];delete s[t.name];for(const n of e)o(t,n)}}const h=[],p=[],d=t.inputLayers;for(const e of d){const t=e[0],n=e[1],i=e[2];Ko(t in a);const s=a[t].inboundNodes[n].outputTensors;h.push(s[i])}const m=t.outputLayers;for(const e of m){const t=e[0],n=e[1],i=e[2];Ko(t in a);const s=a[t].inboundNodes[n].outputTensors;p.push(s[i])}return new e({inputs:h,outputs:p,name:c})}get stateful(){if(this._stateful)throw new Bo("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){si((()=>{this.layers.forEach((e=>{e.stateful&&e.resetStates()}))}))}}
|
|
4368
|
+
*/class tp extends Dc{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,null==this.name){const e=this.getClassName().toLowerCase();this.name=dl(e)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],il(this.inputs).length!==this.inputs.length)throw new Bo(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map((e=>e.name))}`);il(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map((e=>e.name))}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const e of this.outputs){const t=e.sourceLayer,n=e.nodeIndex,i=e.tensorIndex;this.outputLayers.push(t),this.outputLayersNodeIndices.push(n),this.outputLayersTensorIndices.push(i)}for(const e of this.inputs){const t=e.sourceLayer,n=e.nodeIndex,i=e.tensorIndex;Ko(0===n,"input layer has >1 nodes"),Ko(0===i,"input layer has >1 tensors"),this.inputLayers.push(t),this.inputLayersNodeIndices.push(n),this.inputLayersTensorIndices.push(i)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let t=0;t<this.inputLayers.length;t++){const n=this.inputLayers[t];if(!(n instanceof _c))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${t} (0-based) originates from layer type ${n.getClassName()}.`);this.inputNames.push(n.name),this.feedInputShapes.push(n.batchInputShape),this.feedInputNames.push(n.name)}for(const e of this.outputLayers)this.outputNames.push(e.name);this.internalInputShapes=this.inputs.map((e=>e.shape)),this.internalOutputShapes=this.outputs.map((e=>e.shape));const t={},n={},i={},a={},s={},r=[],o=(e,t,n,i,a,l)=>{null!=i&&null!=a&&null!=l||(i=e.sourceLayer,a=e.nodeIndex,l=e.tensorIndex);const c=i.inboundNodes[a];if(-1!==n.indexOf(c))throw new Po(`The tensor ${e.name} at layer "${i.name}" is part of a cycle.`);if(-1!==t.indexOf(c))return;this.containerNodes.add(tp.nodeKey(i,a)),i.id in s||(s[i.id]=Object.keys(s).length),-1===n.indexOf(c)&&n.push(c);const u=c.inboundLayers.length;for(let e=0;e<u;e++){const i=c.inputTensors[e],a=c.inboundLayers[e],s=c.nodeIndices[e],r=c.tensorIndices[e];o(i,t,n,a,s,r)}for(t.push(c);n.indexOf(c)>=0;)n.splice(n.indexOf(c),1);r.push(c)},l=[],c=[];for(const e of this.outputs)o(e,l,c);const u=r.slice().reverse();for(const e of u){n[e.id]=e,e.id in t||(t[e.id]=0);let s=t[e.id];const r=null==i[e.outboundLayer.id]?0:i[e.outboundLayer.id];s=Math.max(s,r),i[e.outboundLayer.id]=s,a[e.outboundLayer.id]=e.outboundLayer,t[e.id]=s;for(let i=0;i<e.inboundLayers.length;i++){const a=e.inboundLayers[i],r=e.nodeIndices[i],o=a.inboundNodes[r],l=null==t[o.id]?0:t[o.id];t[o.id]=Math.max(s+1,l),n[o.id]=o}}const h={};for(const e in t){const i=t[e];i in h||(h[i]=[]),h[i].push(n[e])}const p={};for(const e in i){const t=i[e];t in p||(p[t]=[]),p[t].push(a[e])}let d=Object.keys(p).map((e=>parseInt(e,10))).sort(nl);this.layers=[];for(const e of d){const t=p[e];t.sort(((e,t)=>{const n=s[e.id],i=s[t.id];return n<i?-1:n>i?1:0}));for(const e of t)e instanceof tp&&this.internalContainerRefs.push(e),this.layers.push(e)}this.layersByDepth=p,d=Object.keys(h).map((e=>parseInt(e,10))).sort(nl);const m=this.inputs.slice(),f=[];for(const e of d)for(const t of h[e]){const e=t.outboundLayer;if(null!=e){for(const n of t.inputTensors)if(-1===m.indexOf(n))throw new Po(`Graph disconnected: cannot obtain value for tensor ${n} at layer "${e.name}". The following previous layers were accessed without issue: ${f}`);for(const e of t.outputTensors)m.push(e);f.push(e.name)}}this.nodesByDepth=h;const g=this.layers.map((e=>e.name));for(const e of g){const t=g.filter((t=>t===e)).length;if(1!==t)throw new Po(`The name "${e}" is used ${t} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new jc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map((e=>null)),outputMasks:this.outputs.map((e=>null)),inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs.map((e=>e.shape))}),this.built=!0,this._refCount=1}assertNotDisposed(){if(0===this._refCount)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach((t=>{t._trainableWeights.forEach((t=>t.trainable=e))})),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new Bo("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.layers)t.push(...e.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const n={};let i=0;for(const e of this.layers)for(const t of e.weights){if(null!=n[t.originalName])throw new Bo(`Duplicate weight name: ${t.originalName}`);n[t.originalName]=t,i++}const a=[];for(const i in e){let s=i;if(null==n[i]){const e=i.split("/");s=e.slice(0,-2).concat([e[e.length-1]]).join("/")}if(null!=n[s])a.push([n[s],e[i]]);else if(t)throw new Bo(`Provided weight data has no target variable: ${i}`);delete n[s]}if(t){const e=[];for(const t in n)e.push(t);if(e.length>0)throw new Bo(`${e.length} of ${i} weights are not set: ${e}`)}Ec(a)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${ep}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=Xh(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return si((()=>{e=Jo(e);const n=new Rc;for(let t=0;t<this.inputs.length;++t)n.add(this.inputs[t],e[t]);return Oc(this.outputs,n,t)}))}computeMask(e,t){return si((()=>{let n;return e=Jo(e),n=null==t?Vo(null,e.length):Jo(t),this.runInternalGraph(e,n)[1]}))}computeOutputShape(e){const t=wc(e);if(t.length!==this.inputLayers.length)throw new Bo(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let e=0;e<t.length;e++){const i=this.inputLayers[e],a=t[e];n[i.name+"_0_0"]=a}const i=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(nl);if(i.length>1)for(const e of i){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer;if(-1!==this.inputLayers.map((e=>e.id)).indexOf(t.id))continue;const i=[];for(let t=0;t<e.inboundLayers.length;t++){const a=e.inboundLayers[t],s=e.nodeIndices[t],r=e.tensorIndices[t],o=n[`${a.name}_${s}_${r}`];i.push(o)}const a=wc(t.computeOutputShape(Ho(i))),s=t.inboundNodes.indexOf(e);for(let e=0;e<a.length;e++){n[`${t.name}_${s}_${e}`]=a[e]}}}const a=[],s=[];for(let e=0;e<this.outputLayers.length;e++){const t=this.outputLayers[e],n=this.outputLayersNodeIndices[e],i=this.outputLayersTensorIndices[e],a=`${t.name}_${n}_${i}`;s.push(a)}for(let e=0;e<s.length;e++){const t=s[e];Ko(t in n),a.push(n[t])}return Ho(a)}runInternalGraph(e,t){null==t&&(t=Vo(null,e.length));const n={};for(let i=0;i<this.inputs.length;++i){const a=this.inputs[i],s=e[i],r=t[i];n[a.id]=[s,r]}const i=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(nl);for(const e of i){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer,i=e.inputTensors,a=e.outputTensors,s=new Array;for(const e of i)e.id in n&&s.push(n[e.id]);if(s.length===i.length){let i,r,o,l,c={};if(null!=e.callArgs&&(c=e.callArgs),1===s.length){const[e,n]=s[0];null==c.mask&&(c.mask=n),o=Jo(t.call(e,c)),l=Jo(t.computeMask(e,n)),i=[e],r=[n]}else i=s.map((e=>e[0])),r=s.map((e=>e[1])),null==c.mask&&(c.mask=r),o=Jo(t.call(i,c)),l=Jo(t.computeMask(i,r));if(t.activityRegularizer)throw new Uo("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let e=0;e<a.length;++e){const t=a[e],i=o[e],s=l[e];n[t.id]=[i,s]}}}}const a=[],s=[],r=[];for(const e of this.outputs){Ko(e.id in n,`Could not compute output ${e.name} : ${e.id}`);const[t,i]=n[e.id];r.push(t.shape),a.push(t),s.push(i)}return[a,s,r]}buildNodeConversionMap(e){const t={};let n;for(const e of this.layers){n=e instanceof tp?1:0;for(let i=0;i<e.inboundNodes.length;i++){const a=tp.nodeKey(e,i);this.containerNodes.has(a)&&(t[a]=n,n+=1)}}return t}getLayer(e,t){if(null!=t){if(this.layers.length<=t)throw new Bo(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}if(null==e)throw new Bo("Provide either a layer name or layer index");for(const t of this.layers)if(t.name===e)return t;throw new Bo(`No such layer: ${e}`)}calculateLosses(){return si((()=>{const e=[];for(const t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){const i=tp.nodeKey(t,n);this.containerNodes.has(i)&&e.push(...t.calculateLosses())}return e}))}getConfig(){const e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(const e of this.layers){const i=e.getClassName(),a=e.getConfig(),s=[];for(let n=0;n<e.inboundNodes.length;n++){const i=e.inboundNodes[n],a=tp.nodeKey(e,n);let r={};if(this.containerNodes.has(a)){if(i.callArgs)try{JSON.stringify(i.callArgs),r=i.callArgs}catch(t){console.warn(`Layer ${e.name} was passed non-serializable keyword arguments: ${i.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),r={}}if(i.inboundLayers.length>0){const e=[];for(let n=0;n<i.inboundLayers.length;n++){const a=i.inboundLayers[n],s=i.nodeIndices[n],o=i.tensorIndices[n];let l=t[tp.nodeKey(a,s)];null==l&&(l=0),e.push([a.name,l,o,r])}s.push(e)}}}const r={};r.name=e.name,r.className=i,r.config=a,r.inboundNodes=s,n.push(r)}e.layers=n;const i=[];for(let e=0;e<this.inputLayers.length;e++){const n=this.inputLayers[e],a=this.inputLayersNodeIndices[e],s=tp.nodeKey(n,a);if(!this.containerNodes.has(s))continue;let r=t[s];null==r&&(r=0);const o=this.inputLayersTensorIndices[e];i.push([n.name,r,o])}e.inputLayers=i;const a=[];for(let e=0;e<this.outputLayers.length;e++){const n=this.outputLayers[e],i=this.outputLayersNodeIndices[e],s=tp.nodeKey(n,i);if(!this.containerNodes.has(s))continue;let r=t[s];null==r&&(r=0);const o=this.outputLayersTensorIndices[e];a.push([n.name,r,o])}return e.outputLayers=a,e}static fromConfig(e,t,n={},i=!1){const a={},s={};function r(e,t){e.name in s?s[e.name].push(t):s[e.name]=[t]}function o(e,t){const n=[];let i;for(const s of t){const o=s[0],l=s[1],c=s[2];if(i=null==s[3]?{}:s[3],!(o in a))return void r(e,t);const u=a[o];if(u.inboundNodes.length<=l)return void r(e,t);const h=u.inboundNodes[l];n.push(h.outputTensors[c])}n.length>0&&e.apply(Ho(n),i)}function l(e){const n=e.name,s=Nh(e,null!=t.customObjects?t.customObjects:{});s.setFastWeightInitDuringBuild(i),a[n]=s;e.inboundNodes.forEach((e=>{if(!(e instanceof Array))throw new Bo(`Corrupted configuration, expected array for nodeData: ${e}`);r(s,e)}))}const c=t.name,u=t.layers;for(const e of u)l(e);for(;!al(s);)for(const e of u){const t=a[e.name];if(t.name in s){const e=s[t.name];delete s[t.name];for(const n of e)o(t,n)}}const h=[],p=[],d=t.inputLayers;for(const e of d){const t=e[0],n=e[1],i=e[2];Ko(t in a);const s=a[t].inboundNodes[n].outputTensors;h.push(s[i])}const m=t.outputLayers;for(const e of m){const t=e[0],n=e[1],i=e[2];Ko(t in a);const s=a[t].inboundNodes[n].outputTensors;p.push(s[i])}return new e({inputs:h,outputs:p,name:c})}get stateful(){if(this._stateful)throw new Bo("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){si((()=>{this.layers.forEach((e=>{e.stateful&&e.resetStates()}))}))}}
|
|
4369
4369
|
/**
|
|
4370
4370
|
* @license
|
|
4371
4371
|
* Copyright 2018 Google LLC
|
|
@@ -4402,7 +4402,7 @@ function cp(e){I(e>0&&Number.isInteger(e),(()=>`batchSize is required to be a po
|
|
|
4402
4402
|
* license that can be found in the LICENSE file or at
|
|
4403
4403
|
* https://opensource.org/licenses/MIT.
|
|
4404
4404
|
* =============================================================================
|
|
4405
|
-
*/function fp(e){return Array.isArray(e)}function gp(e){return!function(e){return e instanceof Ut}(e)&&!fp(e)}function vp(e,t,n,i=!0,a=""){if(null==t||0===t.length){if(null!=e){let t=!1;if(fp(e)&&e.length>0)t=!0;else if(gp(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new Bo(`Error when checking model ${a} expected no data, but got ${e}`)}return[]}if(null==e)return t.map((e=>null));let s;if(gp(e)){s=[];for(const n of t){if(null==e[n])throw new Bo(`No data provided for "${n}". Need data for each key in: ${t}`);s.push(e[n])}}else if(fp(e)){if(e.length!==t.length)throw new Bo(`Error when checking model ${a}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);s=e}else{if(t.length>1)throw new Bo(`The model ${a} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=dp(s),null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const r=s[e];if(r.shape.length!==n[e].length)throw new Bo(`Error when checking ${a}: expected ${t[e]} to have ${n[e].length} dimension(s). but got array with shape ${r.shape}`);for(let t=0;t<n[e].length;++t){if(0===t&&!i)continue;const s=r.shape[t],o=n[e][t];if(null!=o&&o>=0&&s!==o)throw new Bo(`${a} expected a batch of elements where each example has shape [${n[e].slice(1,n[e].length)}] (i.e.,tensor shape [*,${n[e].slice(1,n[e].length)}]) but the ${a} received an input with ${r.shape[0]} examples, each with shape [${r.shape.slice(1,r.shape.length)}] (tensor shape [${r.shape}])`)}}return s}function yp(e,t,n,i=!0,a=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new Bo(`Error when checking model ${a}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);s=e}else{if(t.length>1)throw new Bo(`The model expects ${t.length} ${a} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);s=[e]}if(null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const r=s[e];if(r.shape.length!==n[e].length)throw new Bo(`Error when checking ${a}: expected ${t[e]} to have ${n[e].length} dimension(s), but got array with shape ${JSON.stringify(r.shape)}`);for(let s=0;s<n[e].length;++s){if(0===s&&!i)continue;const o=r.shape[s],l=n[e][s];if(null!=l&&l!==o)throw new Bo(`Error when checking ${a}: expected ${t[e]} to have shape ${JSON.stringify(n[e])} but got array with shape ${JSON.stringify(r.shape)}.`)}}}class bp extends tp{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new Bo("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");qh(this,e,t,n)}compile(e){if(null==e.loss&&(e.loss=[]),this.loss=e.loss,"string"==typeof e.optimizer)this.optimizer_=function(e){const t={Adagrad:()=>Ur.adagrad(.01),Adadelta:()=>Ur.adadelta(1,.95,Fl()),Adam:()=>Ur.adam(.001,.9,.999,Fl()),Adamax:()=>Ur.adamax(.002,.9,.999,Fl(),0),RMSProp:()=>Ur.rmsprop(.001,.9,0,Fl()),SGD:()=>Ur.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new Bo(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Fr))throw new Bo("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(Array.isArray(e.loss)||"string"==typeof e.loss||"function"==typeof e.loss)if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new Bo(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);const n=e.loss;t=n.map((e=>Fh(e)))}else{const n=Fh(e.loss);this.outputs.forEach((e=>{t.push(n)}))}else{e.loss=e.loss;for(const t in e.loss)if(-1===this.outputNames.indexOf(t))throw new Bo(`Unknown entry in loss dictionary: "${t}". Only expected the following keys: ${this.outputNames}`);for(const n of this.outputNames)null==e.loss[n]&&console.warn(`Output "${n}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${n} during training`),t.push(Fh(e.loss[n]))}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let e=0;e<this.outputs.length;++e){const t=this.internalOutputShapes[e],n=this.outputNames[e];this.feedOutputNames.push(n),this.feedOutputShapes.push(t),this.feedLossFns.push(this.lossFunctions[e])}const n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Nl("loss",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;const t=this.lossFunctions[e];this.outputs.length>1&&(this.metricsTensors.push([t,e]),this.metricsNames.push(this.outputNames[e]+"_loss"))}}));const i=function(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>[]));let n;if("string"==typeof e||"function"==typeof e)n=[e];else{if(!Array.isArray(e)&&"object"!=typeof e)throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);n=e}if(Array.isArray(n))return t.map((e=>n));{const e=[];for(const i of t){let t=n.hasOwnProperty(i)?n[i]:[];Array.isArray(t)||(t=[t]),e.push(t)}return e}}(e.metrics,this.outputNames),a=(e,t,n)=>{this.outputNames.length>1&&(t=this.outputNames[e]+"_"+t),this.metricsNames.push(t),this.metricsTensors.push([n,e])};Nl("metric",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;(t=>{let n,i,s;for(const r of t){if("string"==typeof r&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(r)){const t=this.internalOutputShapes[e];let a;1===t[t.length-1]||this.lossFunctions[e]===jh?-1!==["accuracy","acc"].indexOf(r)?i=_h:-1!==["crossentropy","ce"].indexOf(r)&&(i=Lh):this.lossFunctions[e]===$h?-1!==["accuracy","acc"].indexOf(r)?i=Mh:-1!==["crossentropy","ce"].indexOf(r)&&(i=Ph):-1!==["accuracy","acc"].indexOf(r)?i=Rh:-1!==["crossentropy","ce"].indexOf(r)&&(i=Oh),-1!==["accuracy","acc"].indexOf(r)?a="acc":-1!==["crossentropy","ce"].indexOf(r)&&(a="ce"),s=i,n=""+a}else{const e=Uh(r);s=e,n=""+Wh(r)}let t;Nl(n,(()=>{t=s})),a(e,n,t)}})(i[e])}})),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){const i=null==n.batchSize?32:n.batchSize;cp(i);const a=this.standardizeUserDataXY(e,t,!0,i);try{const s=a[0].concat(a[1]);this.makeTestFunction();const r=this.testFunction;return Ho(this.testLoop(r,s,i,n.verbose,n.steps))}finally{mp(a[0],e),mp(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),async function(e,t,n){const i=null!=(n=n||{}).batches,a=e.testFunction;let s=[];if(n.verbose>0)throw new Uo("Verbose mode is not implemented yet.");I(!i||n.batches>0&&Number.isInteger(n.batches),(()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`));const r="function"==typeof t.next?t:await t.iterator();let o=0,l=0;for(;!i||l<n.batches;){const t=await r.next();if(s=si((()=>{if(t.value){const{xs:n,ys:i}=sp(e,t.value),r=n.concat(i),c=si((()=>a(r)));if(ri(r),0===l)for(let e=0;e<c.length;++e)s.push(Ea(0));const u=r[0].shape[0];for(let e=0;e<c.length;++e){const t=c[e],n=s[e];s[e]=si((()=>bi(s[e],xi(u,t)))),l>0&&ri(n)}ri(c),o+=u,++l}return s})),t.done){i&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let e=0;e<s.length;++e){const t=s[e];s[e]=ki(s[e],o),ri(t)}return Ho(s)}(this,e,t)}checkNumSamples(e,t,n,i="steps"){let a;if(null!=n){if(a=null,null!=t)throw new Bo(`If ${i} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else{if(null==e)throw new Bo(`Either the input data should have a defined shape, or ${i} shoud be specified.`);a=Array.isArray(e)?e[0].shape[0]:e.shape[0]}return a}execute(e,t){if(Array.isArray(t)&&0===t.length)throw new Bo("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),i=n?t:[t],a=this.retrieveSymbolicTensors(i),s=new Rc;if(e instanceof Ut&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new Bo(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let t=0;t<this.inputs.length;++t)s.add(this.inputs[t],e[t])}else for(const t of this.inputs){const n=e[t.name];if(null==n)throw new Bo(`No value is provided for the model's input ${t.name}`);s.add(t,n)}const r=Oc(a,s);return n?r:r[0]}retrieveSymbolicTensors(e){const t=Vo(null,e.length);let n=e.length;for(const i of this.layers){const a=Array.isArray(i.output)?i.output:[i.output],s=a.map((e=>e.name));for(let i=0;i<e.length;++i){const r=s.indexOf(e[i]);if(-1!==r&&(t[i]=a[r],n--),0===n)break}if(0===n)break}if(n>0){const n=[];throw t.forEach(((t,i)=>{null==t&&n.push(e[i])})),new Bo(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return si((()=>{const i=this.checkNumSamples(e);if(n)throw new Uo("Verbose predictLoop() is not implemented yet.");const a=pp(i,t),s=this.outputs.map((e=>[]));for(let t=0;t<a.length;++t){si((()=>{const n=a[t][0],i=a[t][1],s=up(e,n,i),r=[];if(Array.isArray(s))for(let e=0;e<s.length;++e)r.push({key:this.inputs[e],value:s[e]});else r.push({key:this.inputs[0],value:s});const o=new Rc(r);return Oc(this.outputs,o)})).forEach(((e,t)=>s[t].push(e)))}return Ho(s.map((e=>Oi(e,0))))}))}predict(e,t={}){const n=dp(e);yp(n,this.inputNames,this.feedInputShapes,!1);try{const i=null==t.batchSize?32:t.batchSize;return cp(i),this.predictLoop(n,i)}finally{mp(n,e)}}predictOnBatch(e){yp(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,i){if(null==this.optimizer_)throw new Po("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const a=[];for(let e=0;e<this.feedOutputShapes.length;++e){const t=this.feedOutputShapes[e];this.feedLossFns[e]===$h?a.push(t.slice(0,t.length-1).concat([1])):a.push(t)}if(function(e,t,n){const i=il(e.map((e=>e.shape[0])));i.sort();const a=il(t.map((e=>e.shape[0])));if(a.sort(),i.length>1)throw new Bo(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map((e=>e.shape)))}`);if(a.length>1)throw new Bo(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map((e=>e.shape)))}`);if(i.length>0&&a.length>0&&!C(i,a))throw new Bo(`Input Tensors should have the same number of samples as target Tensors. Found ${i[0]} input sample(s) and ${a[0]} target sample(s).`)}(e=vp(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=vp(t,this.feedOutputNames,a,!1,"target")),function(e,t,n){const i=[Th,jh,Ch];for(let a=0;a<e.length;++a){const s=e[a],r=t[a],o=n[a];if(null!=r){if(r===Ch&&1===s.shape[s.shape.length-1])throw new Bo(`You are passing a target array of shape ${s.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(-1!==i.indexOf(r)){const e=s.shape.slice(1),t=o.slice(1);for(let n=0;n<e.length;++n){const i=e[n],a=t[n];if(null!=a&&i!==a)throw new Bo(`A target Tensor with shape ${s.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=i&&i>0&&e[0].shape[0]%i!=0)throw new Bo(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${i}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,i,a=!0,s){const[r,o]=this.standardizeUserDataXY(e,t,a,s);if(null!=n)throw new Error("sample weight is not supported yet.");let l=null;if(null!=i){const e=np(i,this.outputNames);l=[];for(let t=0;t<e.length;++t)l.push(await ip(o[t],null,e[t]))}return[r,o,l]}testLoop(e,t,n,i=0,a){return si((()=>{const s=this.checkNumSamples(t,n,a,"steps"),r=[];if(i>0)throw new Uo("Verbose mode is not implemented yet.");if(null!=a)throw new Uo("steps mode in testLoop() is not implemented yet");{const i=pp(s,n),a=Vs(zl(0,s));for(let n=0;n<i.length;++n){const s=i[n][0],o=i[n][1],l=Ll(a,s,o-s),c=hp(t,l),u=e(c);if(0===n)for(let e=0;e<u.length;++e)r.push(Ea(0));for(let e=0;e<u.length;++e){const t=u[e];r[e]=bi(r[e],xi(o-s,t))}}for(let e=0;e<r.length;++e)r[e]=ki(r[e],s)}return r}))}getDedupedMetricsNames(){const e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){const i=e[n];let a=i;if(qo(e,i)>1){a+=`_${qo(e.slice(0,n),i)}`}t.push(a)}return t}makeTrainFunction(){return e=>{const t=[],n=e.slice(0,this.inputs.length),i=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+2*this.outputs.length),s=[],r=this.collectedTrainableWeights.map((e=>e.read()));return[this.optimizer_.minimize((()=>{const e=[];for(let t=0;t<this.inputs.length;++t)e.push({key:this.inputs[t],value:n[t]});const r=new Rc(e),o=Oc(this.outputs,r,{training:!0});let l;for(let e=0;e<this.lossFunctions.length;++e){let n=(0,this.lossFunctions[e])(i[e],o[e]);null!=a[e]&&(n=ap(n,a[e]));const s=ns(n);t.push(s),l=0===e?n:bi(l,n)}for(let e=0;e<this.metricsTensors.length;++e){let n;if(this.outputs.length>1&&e<this.outputs.length)n=t[e];else{const t=this.metricsTensors[e][0],a=this.metricsTensors[e][1];n=ns(t(i[a],o[a]))}oi(n),s.push(n)}return l=ns(l),this.calculateLosses().forEach((e=>{l=bi(l,e)})),l}),!0,r)].concat(s)}}makeTestFunction(){this.testFunction=e=>si((()=>{const t=[];let n;const i=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=[];for(let e=0;e<this.inputs.length;++e)s.push({key:this.inputs[e],value:i[e]});const r=new Rc(s),o=Oc(this.outputs,r);for(let e=0;e<this.lossFunctions.length;++e){const i=this.lossFunctions[e],s=ns(i(a[e],o[e]));n=0===e?s:bi(n,s),t.push(n)}for(let e=0;e<this.metricsTensors.length;++e){const n=this.metricsTensors[e][0],i=this.metricsTensors[e][1],s=ns(n(a[i],o[i]));t.push(s)}return t}))}async fit(e,t,n={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");let i,a,s,r,o,l,c,u,h;this.isTraining=!0;try{const p=null==n.batchSize?32:n.batchSize;cp(p);const d=!1,m=await this.standardizeUserData(e,t,n.sampleWeight,n.classWeight,d,p);i=m[0],a=m[1],h=m[2];let f,g=!1;if(null!=n.validationData&&n.validationData.length>0){if(g=!0,2!==n.validationData.length)throw 3===n.validationData.length?new Uo("validationData including sample weights is not supported yet."):new Bo(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);o=n.validationData[0],l=n.validationData[1];const e=!0,t=await this.standardizeUserData(o,l,null,null,e,p);c=t[0],u=t[1],f=c.concat(u)}else if(null!=n.validationSplit&&n.validationSplit>0&&n.validationSplit<1){g=!0;const e=Math.floor(i[0].shape[0]*(1-n.validationSplit)),t=i[0].shape[0];c=up(i,e,t),s=i,i=up(i,0,e),u=up(a,e,t),r=a,a=up(a,0,e),f=c.concat(u)}else null!=n.validationSteps&&(g=!0);const v=i.concat(a).concat(h);this.checkTrainableWeightsConsistency();const y=this.makeTrainFunction(),b=this.getDedupedMetricsNames();let w,k;g?(this.makeTestFunction(),w=this.testFunction,k=b.slice().concat(b.map((e=>"val_"+e)))):(w=null,f=[],k=b.slice());const x=kh(n.callbacks,n.yieldEvery);return await this.fitLoop(y,v,b,p,n.epochs,n.verbose,x,w,f,n.shuffle,k,n.initialEpoch,null,null)}finally{this.isTraining=!1,mp(i,e),mp(a,t),mp(s,e),mp(r,t),mp(c,o),mp(u,l),null!=h&&ri(h)}}async fitLoop(e,t,n,i,a,s,r,o,l,c,u,h,p,d){null==i&&(i=32),null==a&&(a=1),null==c&&(c=!0),null==h&&(h=0);let m=!1;if(null!=o&&null!=l&&(m=!0),null!=d&&(m=!0,null==p))throw new Bo("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const f=this.checkNumSamples(t,i,p,"steps_per_epoch");let g;null!=f&&(g=zl(0,f)),null==s&&(s=1);const{callbackList:v,history:y}=Sh(r,s,a,h,f,p,i,m,u);v.setModel(this),this.history=y,await v.onTrainBegin(),this.stopTraining_=!1;for(let s=h;s<a;++s){await v.onEpochBegin(s);const a={};if(null!=p)throw new Uo("stepsPerEpoch mode is not implemented yet.");{if("batch"===c)throw new Uo("batch shuffling is not implemneted yet");c&&S(g);const s=Vs(g),r=pp(f,i);for(let c=0;c<r.length;++c){const u={};if(await v.onBatchBegin(c,u),si((()=>{const h=r[c][0],p=r[c][1],d=Ll(s,h,p-h);u.batch=c,u.size=p-h;const f=hp(t,d),g=e(f);for(let e=0;e<n.length;++e){const t=n[e],i=g[e];u[t]=i,oi(i)}if(c===r.length-1&&m){const e=this.testLoop(o,l,i);for(let t=0;t<n.length;++t){const i=n[t],s=e[t];oi(s),a["val_"+i]=s}}})),await v.onBatchEnd(c,u),mh(u),this.stopTraining_)break}s.dispose()}if(await v.onEpochEnd(s,a),this.stopTraining_)break}return await v.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(e,t){return op(this,e,t)}async trainOnBatch(e,t){const n=await this.standardizeUserData(e,t),i=n[0],a=n[1],s=this.makeTrainFunction()(i.concat(a)),r=[];for(const e of s){const t=await e.data();r.push(t[0])}return ri(s),mp(n[0],e),mp(n[1],t),Ho(r)}getNamedWeights(e){const t=[],n=null!=e&&e.trainableOnly,i=n?this.trainableWeights:this.weights,a=this.getWeights(n);for(let e=0;e<i.length;++e)n&&!i[e].trainable||t.push({name:i[e].originalName,tensor:a[e]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){const e=super.dispose();if(0===e.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){const t=ai().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-ai().numTensors}return e}getLossIdentifiers(){let e;if("string"==typeof this.loss)e=Zo(this.loss);else if(Array.isArray(this.loss)){for(const e of this.loss)if("string"!=typeof e)throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map((e=>Zo(e)))}else{const t=Object.keys(this.loss);e={};const n=this.loss;for(const i of t){if("string"!=typeof n[i])throw new Error("Serialization of non-string loss is not supported.");e[i]=Zo(n[i])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[Zo(Wh(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((e=>Zo(Wh(e))));{const e={};for(const t in this.metrics)e[t]=Zo(Wh(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(null!=e.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=e.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=e.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");const t=Nh(Qh(e.optimizer_config));let n,i;if("string"==typeof e.loss)n=Yo(e.loss);else if(Array.isArray(e.loss))n=e.loss.map((e=>Yo(e)));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=Yo(e.loss[t])}if(Array.isArray(e.metrics))i=e.metrics.map((e=>Yo(e)));else if(null!=e.metrics){i={};for(const t in e.metrics)i[t]=Yo(e.metrics[t])}this.compile({loss:n,metrics:i,optimizer:t})}async save(e,t){if("string"==typeof e){const t=(n=e,Tn.getSaveHandlers(n));if(0===t.length)throw new Bo(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Bo(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}var n;if(null==e.save)throw new Bo("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const i=await yn(this.getNamedWeights(t)),a={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:`TensorFlow.js tfjs-layers v${ep}`,convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){a.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:n}=await yn(await this.optimizer.getWeights(),e);i.specs.push(...n),i.data=xn([i.data,t])}if(null!=this.userDefinedMetadata){const e=!0;Vh(this.userDefinedMetadata,this.name,e),a.userDefinedMetadata=this.userDefinedMetadata}return a.weightData=i.data,a.weightSpecs=i.specs,e.save(a)}setUserDefinedMetadata(e){Vh(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}bp.className="Model",yi(bp);class wp extends bp{}
|
|
4405
|
+
*/function fp(e){return Array.isArray(e)}function gp(e){return!function(e){return e instanceof Ut}(e)&&!fp(e)}function vp(e,t,n,i=!0,a=""){if(null==t||0===t.length){if(null!=e){let t=!1;if(fp(e)&&e.length>0)t=!0;else if(gp(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new Bo(`Error when checking model ${a} expected no data, but got ${e}`)}return[]}if(null==e)return t.map((e=>null));let s;if(gp(e)){s=[];for(const n of t){if(null==e[n])throw new Bo(`No data provided for "${n}". Need data for each key in: ${t}`);s.push(e[n])}}else if(fp(e)){if(e.length!==t.length)throw new Bo(`Error when checking model ${a}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);s=e}else{if(t.length>1)throw new Bo(`The model ${a} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=dp(s),null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const r=s[e];if(r.shape.length!==n[e].length)throw new Bo(`Error when checking ${a}: expected ${t[e]} to have ${n[e].length} dimension(s). but got array with shape ${r.shape}`);for(let t=0;t<n[e].length;++t){if(0===t&&!i)continue;const s=r.shape[t],o=n[e][t];if(null!=o&&o>=0&&s!==o)throw new Bo(`${a} expected a batch of elements where each example has shape [${n[e].slice(1,n[e].length)}] (i.e.,tensor shape [*,${n[e].slice(1,n[e].length)}]) but the ${a} received an input with ${r.shape[0]} examples, each with shape [${r.shape.slice(1,r.shape.length)}] (tensor shape [${r.shape}])`)}}return s}function yp(e,t,n,i=!0,a=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new Bo(`Error when checking model ${a}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);s=e}else{if(t.length>1)throw new Bo(`The model expects ${t.length} ${a} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);s=[e]}if(null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const r=s[e];if(r.shape.length!==n[e].length)throw new Bo(`Error when checking ${a}: expected ${t[e]} to have ${n[e].length} dimension(s), but got array with shape ${JSON.stringify(r.shape)}`);for(let s=0;s<n[e].length;++s){if(0===s&&!i)continue;const o=r.shape[s],l=n[e][s];if(null!=l&&l!==o)throw new Bo(`Error when checking ${a}: expected ${t[e]} to have shape ${JSON.stringify(n[e])} but got array with shape ${JSON.stringify(r.shape)}.`)}}}class bp extends tp{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new Bo("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");qh(this,e,t,n)}compile(e){if(null==e.loss&&(e.loss=[]),this.loss=e.loss,"string"==typeof e.optimizer)this.optimizer_=function(e){const t={Adagrad:()=>Ur.adagrad(.01),Adadelta:()=>Ur.adadelta(1,.95,Fl()),Adam:()=>Ur.adam(.001,.9,.999,Fl()),Adamax:()=>Ur.adamax(.002,.9,.999,Fl(),0),RMSProp:()=>Ur.rmsprop(.001,.9,0,Fl()),SGD:()=>Ur.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new Bo(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Fr))throw new Bo("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(Array.isArray(e.loss)||"string"==typeof e.loss||"function"==typeof e.loss)if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new Bo(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);const n=e.loss;t=n.map((e=>Fh(e)))}else{const n=Fh(e.loss);this.outputs.forEach((e=>{t.push(n)}))}else{e.loss=e.loss;for(const t in e.loss)if(-1===this.outputNames.indexOf(t))throw new Bo(`Unknown entry in loss dictionary: "${t}". Only expected the following keys: ${this.outputNames}`);for(const n of this.outputNames)null==e.loss[n]&&console.warn(`Output "${n}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${n} during training`),t.push(Fh(e.loss[n]))}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let e=0;e<this.outputs.length;++e){const t=this.internalOutputShapes[e],n=this.outputNames[e];this.feedOutputNames.push(n),this.feedOutputShapes.push(t),this.feedLossFns.push(this.lossFunctions[e])}const n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Nl("loss",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;const t=this.lossFunctions[e];this.outputs.length>1&&(this.metricsTensors.push([t,e]),this.metricsNames.push(this.outputNames[e]+"_loss"))}}));const i=function(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>[]));let n;if("string"==typeof e||"function"==typeof e)n=[e];else{if(!Array.isArray(e)&&"object"!=typeof e)throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);n=e}if(Array.isArray(n))return t.map((e=>n));{const e=[];for(const i of t){let t=n.hasOwnProperty(i)?n[i]:[];Array.isArray(t)||(t=[t]),e.push(t)}return e}}(e.metrics,this.outputNames),a=(e,t,n)=>{this.outputNames.length>1&&(t=this.outputNames[e]+"_"+t),this.metricsNames.push(t),this.metricsTensors.push([n,e])};Nl("metric",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;(t=>{let n,i,s;for(const r of t){if("string"==typeof r&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(r)){const t=this.internalOutputShapes[e];let a;1===t[t.length-1]||this.lossFunctions[e]===jh?-1!==["accuracy","acc"].indexOf(r)?i=_h:-1!==["crossentropy","ce"].indexOf(r)&&(i=Lh):this.lossFunctions[e]===$h?-1!==["accuracy","acc"].indexOf(r)?i=Mh:-1!==["crossentropy","ce"].indexOf(r)&&(i=Ph):-1!==["accuracy","acc"].indexOf(r)?i=Rh:-1!==["crossentropy","ce"].indexOf(r)&&(i=Oh),-1!==["accuracy","acc"].indexOf(r)?a="acc":-1!==["crossentropy","ce"].indexOf(r)&&(a="ce"),s=i,n=""+a}else{const e=Uh(r);s=e,n=""+Wh(r)}let t;Nl(n,(()=>{t=s})),a(e,n,t)}})(i[e])}})),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){const i=null==n.batchSize?32:n.batchSize;cp(i);const a=this.standardizeUserDataXY(e,t,!0,i);try{const s=a[0].concat(a[1]);this.makeTestFunction();const r=this.testFunction;return Ho(this.testLoop(r,s,i,n.verbose,n.steps))}finally{mp(a[0],e),mp(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),async function(e,t,n){const i=null!=(n=n||{}).batches,a=e.testFunction;let s=[];if(n.verbose>0)throw new Uo("Verbose mode is not implemented yet.");I(!i||n.batches>0&&Number.isInteger(n.batches),(()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`));const r="function"==typeof t.next?t:await t.iterator();let o=0,l=0;for(;!i||l<n.batches;){const t=await r.next();if(s=si((()=>{if(t.value){const{xs:n,ys:i}=sp(e,t.value),r=n.concat(i),c=si((()=>a(r)));if(ri(r),0===l)for(let e=0;e<c.length;++e)s.push(Aa(0));const u=r[0].shape[0];for(let e=0;e<c.length;++e){const t=c[e],n=s[e];s[e]=si((()=>bi(s[e],xi(u,t)))),l>0&&ri(n)}ri(c),o+=u,++l}return s})),t.done){i&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let e=0;e<s.length;++e){const t=s[e];s[e]=ki(s[e],o),ri(t)}return Ho(s)}(this,e,t)}checkNumSamples(e,t,n,i="steps"){let a;if(null!=n){if(a=null,null!=t)throw new Bo(`If ${i} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else{if(null==e)throw new Bo(`Either the input data should have a defined shape, or ${i} shoud be specified.`);a=Array.isArray(e)?e[0].shape[0]:e.shape[0]}return a}execute(e,t){if(Array.isArray(t)&&0===t.length)throw new Bo("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),i=n?t:[t],a=this.retrieveSymbolicTensors(i),s=new Rc;if(e instanceof Ut&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new Bo(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let t=0;t<this.inputs.length;++t)s.add(this.inputs[t],e[t])}else for(const t of this.inputs){const n=e[t.name];if(null==n)throw new Bo(`No value is provided for the model's input ${t.name}`);s.add(t,n)}const r=Oc(a,s);return n?r:r[0]}retrieveSymbolicTensors(e){const t=Vo(null,e.length);let n=e.length;for(const i of this.layers){const a=Array.isArray(i.output)?i.output:[i.output],s=a.map((e=>e.name));for(let i=0;i<e.length;++i){const r=s.indexOf(e[i]);if(-1!==r&&(t[i]=a[r],n--),0===n)break}if(0===n)break}if(n>0){const n=[];throw t.forEach(((t,i)=>{null==t&&n.push(e[i])})),new Bo(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return si((()=>{const i=this.checkNumSamples(e);if(n)throw new Uo("Verbose predictLoop() is not implemented yet.");const a=pp(i,t),s=this.outputs.map((e=>[]));for(let t=0;t<a.length;++t){si((()=>{const n=a[t][0],i=a[t][1],s=up(e,n,i),r=[];if(Array.isArray(s))for(let e=0;e<s.length;++e)r.push({key:this.inputs[e],value:s[e]});else r.push({key:this.inputs[0],value:s});const o=new Rc(r);return Oc(this.outputs,o)})).forEach(((e,t)=>s[t].push(e)))}return Ho(s.map((e=>Oi(e,0))))}))}predict(e,t={}){const n=dp(e);yp(n,this.inputNames,this.feedInputShapes,!1);try{const i=null==t.batchSize?32:t.batchSize;return cp(i),this.predictLoop(n,i)}finally{mp(n,e)}}predictOnBatch(e){yp(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,i){if(null==this.optimizer_)throw new Po("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const a=[];for(let e=0;e<this.feedOutputShapes.length;++e){const t=this.feedOutputShapes[e];this.feedLossFns[e]===$h?a.push(t.slice(0,t.length-1).concat([1])):a.push(t)}if(function(e,t,n){const i=il(e.map((e=>e.shape[0])));i.sort();const a=il(t.map((e=>e.shape[0])));if(a.sort(),i.length>1)throw new Bo(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map((e=>e.shape)))}`);if(a.length>1)throw new Bo(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map((e=>e.shape)))}`);if(i.length>0&&a.length>0&&!C(i,a))throw new Bo(`Input Tensors should have the same number of samples as target Tensors. Found ${i[0]} input sample(s) and ${a[0]} target sample(s).`)}(e=vp(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=vp(t,this.feedOutputNames,a,!1,"target")),function(e,t,n){const i=[Th,jh,Ch];for(let a=0;a<e.length;++a){const s=e[a],r=t[a],o=n[a];if(null!=r){if(r===Ch&&1===s.shape[s.shape.length-1])throw new Bo(`You are passing a target array of shape ${s.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(-1!==i.indexOf(r)){const e=s.shape.slice(1),t=o.slice(1);for(let n=0;n<e.length;++n){const i=e[n],a=t[n];if(null!=a&&i!==a)throw new Bo(`A target Tensor with shape ${s.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=i&&i>0&&e[0].shape[0]%i!=0)throw new Bo(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${i}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,i,a=!0,s){const[r,o]=this.standardizeUserDataXY(e,t,a,s);if(null!=n)throw new Error("sample weight is not supported yet.");let l=null;if(null!=i){const e=np(i,this.outputNames);l=[];for(let t=0;t<e.length;++t)l.push(await ip(o[t],null,e[t]))}return[r,o,l]}testLoop(e,t,n,i=0,a){return si((()=>{const s=this.checkNumSamples(t,n,a,"steps"),r=[];if(i>0)throw new Uo("Verbose mode is not implemented yet.");if(null!=a)throw new Uo("steps mode in testLoop() is not implemented yet");{const i=pp(s,n),a=Vs(zl(0,s));for(let n=0;n<i.length;++n){const s=i[n][0],o=i[n][1],l=Ll(a,s,o-s),c=hp(t,l),u=e(c);if(0===n)for(let e=0;e<u.length;++e)r.push(Aa(0));for(let e=0;e<u.length;++e){const t=u[e];r[e]=bi(r[e],xi(o-s,t))}}for(let e=0;e<r.length;++e)r[e]=ki(r[e],s)}return r}))}getDedupedMetricsNames(){const e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){const i=e[n];let a=i;if(qo(e,i)>1){a+=`_${qo(e.slice(0,n),i)}`}t.push(a)}return t}makeTrainFunction(){return e=>{const t=[],n=e.slice(0,this.inputs.length),i=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+2*this.outputs.length),s=[],r=this.collectedTrainableWeights.map((e=>e.read()));return[this.optimizer_.minimize((()=>{const e=[];for(let t=0;t<this.inputs.length;++t)e.push({key:this.inputs[t],value:n[t]});const r=new Rc(e),o=Oc(this.outputs,r,{training:!0});let l;for(let e=0;e<this.lossFunctions.length;++e){let n=(0,this.lossFunctions[e])(i[e],o[e]);null!=a[e]&&(n=ap(n,a[e]));const s=ns(n);t.push(s),l=0===e?n:bi(l,n)}for(let e=0;e<this.metricsTensors.length;++e){let n;if(this.outputs.length>1&&e<this.outputs.length)n=t[e];else{const t=this.metricsTensors[e][0],a=this.metricsTensors[e][1];n=ns(t(i[a],o[a]))}oi(n),s.push(n)}return l=ns(l),this.calculateLosses().forEach((e=>{l=bi(l,e)})),l}),!0,r)].concat(s)}}makeTestFunction(){this.testFunction=e=>si((()=>{const t=[];let n;const i=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=[];for(let e=0;e<this.inputs.length;++e)s.push({key:this.inputs[e],value:i[e]});const r=new Rc(s),o=Oc(this.outputs,r);for(let e=0;e<this.lossFunctions.length;++e){const i=this.lossFunctions[e],s=ns(i(a[e],o[e]));n=0===e?s:bi(n,s),t.push(n)}for(let e=0;e<this.metricsTensors.length;++e){const n=this.metricsTensors[e][0],i=this.metricsTensors[e][1],s=ns(n(a[i],o[i]));t.push(s)}return t}))}async fit(e,t,n={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");let i,a,s,r,o,l,c,u,h;this.isTraining=!0;try{const p=null==n.batchSize?32:n.batchSize;cp(p);const d=!1,m=await this.standardizeUserData(e,t,n.sampleWeight,n.classWeight,d,p);i=m[0],a=m[1],h=m[2];let f,g=!1;if(null!=n.validationData&&n.validationData.length>0){if(g=!0,2!==n.validationData.length)throw 3===n.validationData.length?new Uo("validationData including sample weights is not supported yet."):new Bo(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);o=n.validationData[0],l=n.validationData[1];const e=!0,t=await this.standardizeUserData(o,l,null,null,e,p);c=t[0],u=t[1],f=c.concat(u)}else if(null!=n.validationSplit&&n.validationSplit>0&&n.validationSplit<1){g=!0;const e=Math.floor(i[0].shape[0]*(1-n.validationSplit)),t=i[0].shape[0];c=up(i,e,t),s=i,i=up(i,0,e),u=up(a,e,t),r=a,a=up(a,0,e),f=c.concat(u)}else null!=n.validationSteps&&(g=!0);const v=i.concat(a).concat(h);this.checkTrainableWeightsConsistency();const y=this.makeTrainFunction(),b=this.getDedupedMetricsNames();let w,k;g?(this.makeTestFunction(),w=this.testFunction,k=b.slice().concat(b.map((e=>"val_"+e)))):(w=null,f=[],k=b.slice());const x=kh(n.callbacks,n.yieldEvery);return await this.fitLoop(y,v,b,p,n.epochs,n.verbose,x,w,f,n.shuffle,k,n.initialEpoch,null,null)}finally{this.isTraining=!1,mp(i,e),mp(a,t),mp(s,e),mp(r,t),mp(c,o),mp(u,l),null!=h&&ri(h)}}async fitLoop(e,t,n,i,a,s,r,o,l,c,u,h,p,d){null==i&&(i=32),null==a&&(a=1),null==c&&(c=!0),null==h&&(h=0);let m=!1;if(null!=o&&null!=l&&(m=!0),null!=d&&(m=!0,null==p))throw new Bo("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const f=this.checkNumSamples(t,i,p,"steps_per_epoch");let g;null!=f&&(g=zl(0,f)),null==s&&(s=1);const{callbackList:v,history:y}=Sh(r,s,a,h,f,p,i,m,u);v.setModel(this),this.history=y,await v.onTrainBegin(),this.stopTraining_=!1;for(let s=h;s<a;++s){await v.onEpochBegin(s);const a={};if(null!=p)throw new Uo("stepsPerEpoch mode is not implemented yet.");{if("batch"===c)throw new Uo("batch shuffling is not implemneted yet");c&&S(g);const s=Vs(g),r=pp(f,i);for(let c=0;c<r.length;++c){const u={};if(await v.onBatchBegin(c,u),si((()=>{const h=r[c][0],p=r[c][1],d=Ll(s,h,p-h);u.batch=c,u.size=p-h;const f=hp(t,d),g=e(f);for(let e=0;e<n.length;++e){const t=n[e],i=g[e];u[t]=i,oi(i)}if(c===r.length-1&&m){const e=this.testLoop(o,l,i);for(let t=0;t<n.length;++t){const i=n[t],s=e[t];oi(s),a["val_"+i]=s}}})),await v.onBatchEnd(c,u),mh(u),this.stopTraining_)break}s.dispose()}if(await v.onEpochEnd(s,a),this.stopTraining_)break}return await v.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(e,t){return op(this,e,t)}async trainOnBatch(e,t){const n=await this.standardizeUserData(e,t),i=n[0],a=n[1],s=this.makeTrainFunction()(i.concat(a)),r=[];for(const e of s){const t=await e.data();r.push(t[0])}return ri(s),mp(n[0],e),mp(n[1],t),Ho(r)}getNamedWeights(e){const t=[],n=null!=e&&e.trainableOnly,i=n?this.trainableWeights:this.weights,a=this.getWeights(n);for(let e=0;e<i.length;++e)n&&!i[e].trainable||t.push({name:i[e].originalName,tensor:a[e]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){const e=super.dispose();if(0===e.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){const t=ai().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-ai().numTensors}return e}getLossIdentifiers(){let e;if("string"==typeof this.loss)e=Zo(this.loss);else if(Array.isArray(this.loss)){for(const e of this.loss)if("string"!=typeof e)throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map((e=>Zo(e)))}else{const t=Object.keys(this.loss);e={};const n=this.loss;for(const i of t){if("string"!=typeof n[i])throw new Error("Serialization of non-string loss is not supported.");e[i]=Zo(n[i])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[Zo(Wh(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((e=>Zo(Wh(e))));{const e={};for(const t in this.metrics)e[t]=Zo(Wh(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(null!=e.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=e.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=e.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");const t=Nh(Qh(e.optimizer_config));let n,i;if("string"==typeof e.loss)n=Yo(e.loss);else if(Array.isArray(e.loss))n=e.loss.map((e=>Yo(e)));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=Yo(e.loss[t])}if(Array.isArray(e.metrics))i=e.metrics.map((e=>Yo(e)));else if(null!=e.metrics){i={};for(const t in e.metrics)i[t]=Yo(e.metrics[t])}this.compile({loss:n,metrics:i,optimizer:t})}async save(e,t){if("string"==typeof e){const t=(n=e,Tn.getSaveHandlers(n));if(0===t.length)throw new Bo(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Bo(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}var n;if(null==e.save)throw new Bo("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const i=await yn(this.getNamedWeights(t)),a={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:`TensorFlow.js tfjs-layers v${ep}`,convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){a.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:n}=await yn(await this.optimizer.getWeights(),e);i.specs.push(...n),i.data=xn([i.data,t])}if(null!=this.userDefinedMetadata){const e=!0;Vh(this.userDefinedMetadata,this.name,e),a.userDefinedMetadata=this.userDefinedMetadata}return a.weightData=i.data,a.weightSpecs=i.specs,e.save(a)}setUserDefinedMetadata(e){Vh(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}bp.className="Model",yi(bp);class wp extends bp{}
|
|
4406
4406
|
/**
|
|
4407
4407
|
* @license
|
|
4408
4408
|
* Copyright 2018 Google LLC
|
|
@@ -4444,7 +4444,7 @@ async function kp(e,t){if(null==t&&(t={}),"string"==typeof e){const a=(n=e,i=t,T
|
|
|
4444
4444
|
* See the License for the specific language governing permissions and
|
|
4445
4445
|
* limitations under the License.
|
|
4446
4446
|
* =============================================================================
|
|
4447
|
-
*/return async function(e,t,n){null==n&&(n={});if(null==e.load)throw new Bo("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const i=await e.load();let a=i.modelTopology;null!=a.model_config&&(a=a.model_config);const s=null==n.strict||n.strict,r=null!=i.weightData&&null!=i.weightSpecs&&s,o=Nh(Qh(a),t,r),l=i.trainingConfig;null!=l&&o.loadTrainingConfig(l);null!=i.userDefinedMetadata&&o.setUserDefinedMetadata(i.userDefinedMetadata);if(null!=i.weightData){if(null==i.weightSpecs)throw new Bo("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:e,optimizerWeights:t}=function(e,t){const n=function(e,t){const n={};let i,a=0;for(const s of t){const t=s.name,r=s.dtype,o=s.shape,l=
|
|
4447
|
+
*/return async function(e,t,n){null==n&&(n={});if(null==e.load)throw new Bo("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const i=await e.load();let a=i.modelTopology;null!=a.model_config&&(a=a.model_config);const s=null==n.strict||n.strict,r=null!=i.weightData&&null!=i.weightSpecs&&s,o=Nh(Qh(a),t,r),l=i.trainingConfig;null!=l&&o.loadTrainingConfig(l);null!=i.userDefinedMetadata&&o.setUserDefinedMetadata(i.userDefinedMetadata);if(null!=i.weightData){if(null==i.weightSpecs)throw new Bo("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:e,optimizerWeights:t}=function(e,t){const n=function(e,t){const n={};let i,a=0;for(const s of t){const t=s.name,r=s.dtype,o=s.shape,l=A(o);let c;if("quantization"in s){const n=s.quantization;if("uint8"===n.dtype||"uint16"===n.dtype){if(!("min"in n)||!("scale"in n))throw new Error(`Weight ${s.name} with quantization ${n.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==n.dtype)throw new Error(`Weight ${s.name} has unknown quantization dtype ${n.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==r)throw new Error(`Weight ${s.name} is quantized with ${n.dtype} which only supports weights of type float32 not ${r}.`)}const o=vn[n.dtype],u=e.slice(a,a+l*o),h="uint8"===n.dtype?new Uint8Array(u):new Uint16Array(u);if("float32"===r)if("uint8"===n.dtype||"uint16"===n.dtype){c=new Float32Array(h.length);for(let e=0;e<h.length;e++){const t=h[e];c[e]=t*n.scale+n.min}}else{if("float16"!==n.dtype)throw new Error(`Unsupported quantization type ${n.dtype} for weight type float32.`);void 0===i&&(i=In()),c=i(h)}else{if("int32"!==r)throw new Error(`Unsupported dtype in weight '${t}': ${r}`);if("uint8"!==n.dtype&&"uint16"!==n.dtype)throw new Error(`Unsupported quantization type ${n.dtype} for weight type int32.`);c=new Int32Array(h.length);for(let e=0;e<h.length;e++){const t=h[e];c[e]=Math.round(t*n.scale+n.min)}}a+=l*o}else if("string"===r){const t=A(s.shape);c=[];for(let n=0;n<t;n++){const t=new Uint32Array(e.slice(a,a+4))[0];a+=4;const n=new Uint8Array(e.slice(a,a+t));c.push(n),a+=t}}else{const i=vn[r],s=e.slice(a,a+l*i);if("float32"===r)c=new Float32Array(s);else if("int32"===r)c=new Int32Array(s);else if("bool"===r)c=new Uint8Array(s);else{if("complex64"!==r)throw new Error(`Unsupported dtype in weight '${t}': ${r}`);{c=new Float32Array(s);const e=new Float32Array(c.length/2),i=new Float32Array(c.length/2);for(let t=0;t<e.length;t++)e[t]=c[2*t],i[t]=c[2*t+1];const a=gn(e,o,"float32"),r=gn(i,o,"float32");n[t]=mn(a,r),a.dispose(),r.dispose()}}a+=l*i}"complex64"!==r&&(n[t]=gn(c,o,r))}return n}(e,t),i={},a=[];return t.forEach((e=>{"optimizer"===e.group?a.push({name:e.name,tensor:n[e.name]}):i[e.name]=n[e.name]})),{modelWeights:i,optimizerWeights:a}}(i.weightData,i.weightSpecs);o.loadWeights(e,s),null!=o.optimizer&&t.length>0&&await o.optimizer.setWeights(t),ri(e),ri(t.map((e=>e.tensor)))}return o}(e,void 0,t)}wp.className="Functional",yi(wp);class xp extends bp{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=null!=e.name?e.name:dl("sequential_"),null!=e.layers)for(const t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some((e=>e<0)))throw new Bo(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof xp||e instanceof bp;let n;if(t){if(n=e,1!==n.outputs.length)throw new Bo("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==n.inputs.length)throw new Bo("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===e.inboundNodes.length){if(null==e.batchInputShape)throw new Bo("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const t=function(e){if(null==e.batchShape&&null==e.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=e.batchShape&&null!=e.shape)throw new Bo("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;null!=e.shape&&null==t&&(t=[null].concat(e.shape));let n=e.dtype;return null==n&&(n="float32"),new _c({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(t)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==e.inboundNodes.length)throw new Bo(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(1!==e.inboundNodes[0].outputTensors.length)throw new Bo("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=Fc(this.outputs[0])}this.inboundNodes=[],new jc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Vo(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs[0].shape})}else{const t=e.apply(this.outputs[0]);if(Array.isArray(t))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[t],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return null==this.model&&this.build(),this.model.call(e,t)}build(e){if(xc(e),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new bp({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){null==this.model&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new Po("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new Po("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return null==this.model&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return null==this.model&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return null==this.model?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new Po("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new Po("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},i=!1){let a,s={};if(t instanceof Array){if(null==t[0].className||"Merge"===t[0].className)throw new Bo("Legacy serialization format not supported yet.");a=t}else I(null!=t.layers,(()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field.")),a=t.layers,delete t.layers,s=t;const r=new e(s);if(!(r instanceof xp))throw new Uo(`Sequential.fromConfig called on non-Sequential input: ${r}`);for(const e of a){const t=Nh(e,void 0,i);i&&t.setFastWeightInitDuringBuild(!0),r.add(t)}return r}set stopTraining(e){if(null==this.model)throw new Bo("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(null==this.model)throw new Bo("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}}xp.className="Sequential",yi(xp);
|
|
4448
4448
|
/**
|
|
4449
4449
|
* @license
|
|
4450
4450
|
* Copyright 2018 Google LLC
|
|
@@ -4454,7 +4454,7 @@ async function kp(e,t){if(null==t&&(t={}),"string"==typeof e){const a=(n=e,i=t,T
|
|
|
4454
4454
|
* https://opensource.org/licenses/MIT.
|
|
4455
4455
|
* =============================================================================
|
|
4456
4456
|
*/
|
|
4457
|
-
class Sp extends gi{getConfig(){return{}}}class Np extends Sp{apply(e,t=1){return function(e,t=1){if(1!==t)throw new Uo(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return ba(e)}(e,t)}}Np.className="elu",yi(Np);class Ip extends Sp{apply(e){return zs(e)}}Ip.className="selu",yi(Ip);class Tp extends Sp{apply(e){return
|
|
4457
|
+
class Sp extends gi{getConfig(){return{}}}class Np extends Sp{apply(e,t=1){return function(e,t=1){if(1!==t)throw new Uo(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return ba(e)}(e,t)}}Np.className="elu",yi(Np);class Ip extends Sp{apply(e){return zs(e)}}Ip.className="selu",yi(Ip);class Tp extends Sp{apply(e){return Es(e)}}Tp.className="relu",yi(Tp);class Ep extends Sp{apply(e){return si((()=>ss(6,Es(e))))}}Ep.className="relu6",yi(Ep);class Ap extends Sp{apply(e){return e}}Ap.className="linear",yi(Ap);class Cp extends Sp{apply(e){return Pi(e)}}Cp.className="sigmoid",yi(Cp);class $p extends Sp{apply(e){return function(e){return si((()=>{const t=bi(.5,xi(.2,e));return Qi(t,0,1)}))}(e)}}$p.className="hardSigmoid",yi($p);class jp extends Sp{apply(e){return Ha(e)}}jp.className="softplus",yi(jp);class zp extends Sp{apply(e){return function(e){return si((()=>ki(e,bi(Si(e),1))))}(e)}}zp.className="softsign",yi(zp);class Dp extends Sp{apply(e){return Ui(e)}}Dp.className="tanh",yi(Dp);class Fp extends Sp{apply(e,t=-1){return Ps(e,t)}}Fp.className="softmax",yi(Fp);class _p extends Sp{apply(e,t=-1){return Za(e,t)}}_p.className="logSoftmax",yi(_p);class Rp extends Sp{apply(e,t=1){return si((()=>xi(Pi(xi(e,t)),e)))}}Rp.className="swish",yi(Rp);class Lp extends Sp{apply(e){return si((()=>xi(e,Ui(Ha(e)))))}}function Mp(e){return e.getClassName()}function Op(e,t={}){return tl(e,vi.getMap().classNameMap,t,"activation")}function Pp(e){if(null==e){const e={className:"linear",config:{}};return Op(e)}if("string"==typeof e){const t={};return t.className=e,t.config={},Op(t)}return e instanceof Sp?e:Op(e)}
|
|
4458
4458
|
/**
|
|
4459
4459
|
* @license
|
|
4460
4460
|
* Copyright 2018 Google LLC
|
|
@@ -4472,7 +4472,7 @@ class Sp extends gi{getConfig(){return{}}}class Np extends Sp{apply(e,t=1){retur
|
|
|
4472
4472
|
* license that can be found in the LICENSE file or at
|
|
4473
4473
|
* https://opensource.org/licenses/MIT.
|
|
4474
4474
|
* =============================================================================
|
|
4475
|
-
*/class qp extends Dc{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=kc(e);let n=
|
|
4475
|
+
*/class qp extends Dc{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=kc(e);let n=Es(e);return null!=this.maxValue&&(n=Qi(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}qp.className="ReLU",yi(qp);class Hp extends Dc{constructor(e){super(null==e?{}:e),this.DEFAULT_ALPHA=.3,null==e&&(e={}),this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=kc(e);return Ua(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Hp.className="LeakyReLU",yi(Hp);class Jp extends Dc{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=yc(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Kp(e.alphaRegularizer),this.alphaConstraint=ph(e.alphaConstraint),null==e.sharedAxes)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else{if("number"!=typeof e.sharedAxes)throw new Bo(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=xc(e)).slice(1);if(null!=this.sharedAxes)for(const e of this.sharedAxes)t[e-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const n={};if(null!=this.sharedAxes)for(let t=1;t<e.length;++t)n[t]=e[t];this.inputSpec=[new Ac({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=kc(e),hs(e,this.alpha.read())}getConfig(){const e={alphaInitializer:vc(this.alphaInitializer),alphaRegularizer:Gp(this.alphaRegularizer),alphaConstraint:uh(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}Jp.className="PReLU",yi(Jp);class Zp extends Dc{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==this.DEFAULT_ALPHA)throw new Uo(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=kc(e);return ba(n)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Zp.className="ELU",yi(Zp);class Yp extends Dc{constructor(e){super(null==e?{}:e),this.DEFAULT_THETA=1,null==e&&(e={}),this.theta=null==e.theta?this.DEFAULT_THETA:e.theta}call(e,t){const n=kc(e);return xi(n,ei(Pa(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}Yp.className="ThresholdedReLU",yi(Yp);class Qp extends Dc{constructor(e){super(null==e?{}:e),this.DEFAULT_AXIS=1,null==e&&(e={}),this.softmax=(new Fp).apply,this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis}call(e,t){const n=kc(e);return this.softmax(n,this.axis)}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}
|
|
4476
4476
|
/**
|
|
4477
4477
|
* @license
|
|
4478
4478
|
* Copyright 2018 Google LLC
|
|
@@ -4491,7 +4491,7 @@ function Xp(e,t,n){if("number"==typeof e)return Vo(e,t);if(e.length!==t)throw ne
|
|
|
4491
4491
|
* license that can be found in the LICENSE file or at
|
|
4492
4492
|
* https://opensource.org/licenses/MIT.
|
|
4493
4493
|
* =============================================================================
|
|
4494
|
-
*/function nd(e,t){return si((()=>(wl(t),"channelsFirst"===t?hi(e,[0,2,3,1]):e)))}function id(e,t){return si((()=>(wl(t),"channelsFirst"===t?hi(e,[0,2,3,4,1]):e)))}function ad(e,t,n,i=[1,1],a="valid",s,r,o=null){return si((()=>{if(null==s&&(s="channelsLast"),wl(s),3!==e.rank&&4!==e.rank)throw new Bo(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new Bo(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=nd(e,s);if("causal"===a)throw new Uo("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=nr({x:l,filter:t,strides:i,pad:"same"===a?"same":"valid",dilations:r,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===s&&(l=hi(l,[0,3,1,2])),l}))}Qp.className="Softmax",yi(Qp);class sd extends Dc{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",sd.verifyArgs(t),this.rank=e,ol(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new Uo(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Xp(t.kernelSize,e,"kernelSize"),this.strides=Xp(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,kl(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,wl(this.dataFormat),this.activation=Pp(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=yc(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=ph(t.biasConstraint),this.biasRegularizer=Kp(t.biasRegularizer),this.activityRegularizer=Kp(t.activityRegularizer),this.dilationRate=Xp(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new Bo(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(2===this.rank){if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate];else if(2!==this.dilationRate.length)throw new Bo(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(3===this.rank)if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(3!==this.dilationRate.length)throw new Bo(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(Ko("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!=typeof e.kernelSize&&!rl(e.kernelSize,"number",1,3))throw new Bo(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Mp(this.activation),useBias:this.useBias,biasInitializer:vc(this.biasInitializer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),biasConstraint:uh(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class rd extends sd{constructor(e,t){super(e,t),this.kernel=null,rd.verifyArgs(t),this.filters=t.filters,ol(this.filters,"filters"),this.kernelInitializer=yc(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=ph(t.kernelConstraint),this.kernelRegularizer=Kp(t.kernelRegularizer)}build(e){e=xc(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Bo(`The channel dimension of the input should be defined. Found ${e[t]}`);const n=e[t],i=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",i,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return si((()=>{let t;e=kc(e);const n=null==this.bias?null:this.bias.read(),i=cl(this.activation.getClassName());if(null!=i&&2===this.rank)t=ad(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,i);else{if(1===this.rank)t=function(e,t,n,i=1,a="valid",s,r=1){return si((()=>{if(null==s&&(s="channelsLast"),wl(s),3!==e.shape.length)throw new Bo(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new Bo(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new Bo(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if("channelsFirst"===s&&(e=hi(e,[0,2,1])),"causal"===a)throw new Uo("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=aa(e,t,i,"same"===a?"same":"valid","NWC",r);return null!=n&&(o=Hl(o,n)),o}))}(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=ad(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new Uo("convolutions greater than 3D are not implemented yet.");t=function(e,t,n,i=[1,1,1],a="valid",s,r){return si((()=>{if(null==s&&(s="channelsLast"),wl(s),4!==e.rank&&5!==e.rank)throw new Bo(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new Bo(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=id(e,s);if("causal"===a)throw new Uo("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=oa(o,t,i,"same"===a?"same":"valid","NDHWC",r),null!=n&&(o=Hl(o,n)),"channelsFirst"===s&&(o=hi(o,[0,4,1,2,3])),o}))}(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate)}null!=this.activation&&(t=this.activation.apply(t))}return t}))}computeOutputShape(e){e=xc(e);const t=[],n="channelsLast"===this.dataFormat?e.slice(1,e.length-1):e.slice(2);for(let e=0;e<n.length;++e){const i=ed(n[e],this.kernelSize[e],this.padding,this.strides[e],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[e]);t.push(i)}let i=[e[0]];return"channelsLast"===this.dataFormat?(i=i.concat(t),i.push(this.filters)):(i.push(this.filters),i=i.concat(t)),i}getConfig(){const e={filters:this.filters,kernelInitializer:vc(this.kernelInitializer),kernelRegularizer:Gp(this.kernelRegularizer),kernelConstraint:uh(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||"number"!=typeof e.filters||e.filters<1)throw new Bo(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class od extends rd{constructor(e){super(2,e),od.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!rl(e.kernelSize,"number",1,2))throw new Bo(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}od.className="Conv2D",yi(od);class ld extends rd{constructor(e){super(3,e),ld.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&(!Array.isArray(e.kernelSize)||1!==e.kernelSize.length&&3!==e.kernelSize.length))throw new Bo(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}ld.className="Conv3D",yi(ld);class cd extends od{constructor(e){if(super(e),this.inputSpec=[new Ec({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new Bo(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=xc(e)).length)throw new Bo("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Bo("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],i=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",i,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Ec({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return si((()=>{let t=kc(e);if(4!==t.shape.length)throw new Bo(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,i=n[0];let a,s;"channelsFirst"===this.dataFormat?(a=2,s=3):(a=1,s=2);const r=n[a],o=n[s],l=this.kernelSize[0],c=this.kernelSize[1],u=this.strides[0],h=this.strides[1],p=[i,td(r,u,l,this.padding),td(o,h,c,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=hi(t,[0,2,3,1]));let d=ra(t,this.kernel.read(),p,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(d=hi(d,[0,3,1,2])),null!=this.bias&&(d=Hl(d,this.bias.read(),this.dataFormat)),null!=this.activation&&(d=this.activation.apply(d)),d}))}computeOutputShape(e){const t=(e=xc(e)).slice();let n,i,a;"channelsFirst"===this.dataFormat?(n=1,i=2,a=3):(n=3,i=1,a=2);const s=this.kernelSize[0],r=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[i]=td(t[i],o,s,this.padding),t[a]=td(t[a],l,r,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}cd.className="Conv2DTranspose",yi(cd);class ud extends ld{constructor(e){if(super(e),this.inputSpec=[new Ec({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new Bo(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(5!==(e=xc(e)).length)throw new Bo("Input should have rank 5; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Bo("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],i=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",i,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Ec({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return si((()=>{let t=kc(e);if(5!==t.shape.length)throw new Bo(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,i=n[0];let a,s,r;"channelsFirst"===this.dataFormat?(r=2,a=3,s=4):(r=1,a=2,s=3);const o=n[r],l=n[a],c=n[s],u=this.kernelSize[0],h=this.kernelSize[1],p=this.kernelSize[2],d=this.strides[0],m=this.strides[1],f=this.strides[2],g=[i,td(o,d,u,this.padding),td(l,m,h,this.padding),td(c,f,p,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=hi(t,[0,2,3,4,1]));let v=ca(t,this.kernel.read(),g,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(v=hi(v,[0,4,1,2,3])),null!==this.bias&&(v=Hl(v,this.bias.read(),this.dataFormat)),null!==this.activation&&(v=this.activation.apply(v)),v}))}computeOutputShape(e){const t=(e=xc(e)).slice();let n,i,a,s;"channelsFirst"===this.dataFormat?(n=1,i=2,a=3,s=4):(n=4,i=1,a=2,s=3);const r=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],c=this.strides[0],u=this.strides[1],h=this.strides[2];return t[n]=this.filters,t[i]=td(t[i],c,r,this.padding),t[a]=td(t[a],u,o,this.padding),t[s]=td(t[s],h,l,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}ud.className="Conv3DTranspose",yi(ud);class hd extends rd{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,null==t.filters)throw new Bo("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new Bo("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=t.padding&&"same"!==t.padding&&"valid"!==t.padding)throw new Bo(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,this.depthwiseInitializer=yc(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Kp(t.depthwiseRegularizer),this.depthwiseConstraint=ph(t.depthwiseConstraint),this.pointwiseInitializer=yc(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Kp(t.pointwiseRegularizer),this.pointwiseConstraint=ph(t.pointwiseConstraint)}build(e){if((e=xc(e)).length<this.rank+2)throw new Bo(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t]||e[t]<0)throw new Bo(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);const n=e[t],i=this.kernelSize.concat([n,this.depthMultiplier]),a=[];for(let e=0;e<this.rank;++e)a.push(1);a.push(n*this.depthMultiplier,this.filters);const s=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",i,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,s,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",a,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,s,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,s,this.biasConstraint):this.bias=null,this.inputSpec=[new Ec({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return si((()=>{let t;if(e=kc(e),1===this.rank)throw new Uo("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=hi(e,[0,2,3,1])),t=Ds(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=Hl(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=hi(t,[0,3,1,2])),t}))}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=vc(this.depthwiseInitializer),e.pointwiseInitializer=vc(this.pointwiseInitializer),e.depthwiseRegularizer=Gp(this.depthwiseRegularizer),e.pointwiseRegularizer=Gp(this.pointwiseRegularizer),e.depthwiseConstraint=uh(this.depthwiseConstraint),e.pointwiseConstraint=uh(this.pointwiseConstraint),e}}hd.className="SeparableConv";class pd extends hd{constructor(e){super(2,e)}}pd.className="SeparableConv2D",yi(pd);class dd extends rd{constructor(e){super(1,e),dd.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!rl(e.kernelSize,"number",1,1))throw new Bo(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}dd.className="Conv1D",yi(dd);class md extends Dc{constructor(e){super(e),"number"==typeof e.cropping?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return"channelsFirst"===this.dataFormat?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return si((()=>{if(e=kc(e),"channelsLast"===this.dataFormat){const t=Ol(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Ol(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=Ol(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Ol(t,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}}))}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}md.className="Cropping2D",yi(md);class fd extends Dc{constructor(e){var t;super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=null==e.size?this.DEFAULT_SIZE:e.size,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wl(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,sl(fl,"InterpolationFormat",t)}computeOutputShape(e){if("channelsFirst"===this.dataFormat){const t=null==e[2]?null:this.size[0]*e[2],n=null==e[3]?null:this.size[1]*e[3];return[e[0],e[1],t,n]}{const t=null==e[1]?null:this.size[0]*e[1],n=null==e[2]?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return si((()=>{let t=kc(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=hi(t,[0,2,3,1]);const e=this.size[0]*n[2],i=this.size[1]*n[3],a="nearest"===this.interpolation?zr.resizeNearestNeighbor(t,[e,i]):zr.resizeBilinear(t,[e,i]);return hi(a,[0,3,1,2])}{const e=this.size[0]*n[1],i=this.size[1]*n[2];return"nearest"===this.interpolation?zr.resizeNearestNeighbor(t,[e,i]):zr.resizeBilinear(t,[e,i])}}))}getConfig(){const e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}}fd.className="UpSampling2D",yi(fd);class gd extends sd{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=yc(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=ph(e.depthwiseConstraint),this.depthwiseRegularizer=Kp(e.depthwiseRegularizer)}build(e){if((e=xc(e)).length<4)throw new Bo(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t="channelsFirst"===this.dataFormat?1:3;if(null==e[t]||e[t]<0)throw new Bo(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const n=e[t],i=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",i,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return si((()=>{let t=
|
|
4494
|
+
*/function nd(e,t){return si((()=>(wl(t),"channelsFirst"===t?hi(e,[0,2,3,1]):e)))}function id(e,t){return si((()=>(wl(t),"channelsFirst"===t?hi(e,[0,2,3,4,1]):e)))}function ad(e,t,n,i=[1,1],a="valid",s,r,o=null){return si((()=>{if(null==s&&(s="channelsLast"),wl(s),3!==e.rank&&4!==e.rank)throw new Bo(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new Bo(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=nd(e,s);if("causal"===a)throw new Uo("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=nr({x:l,filter:t,strides:i,pad:"same"===a?"same":"valid",dilations:r,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===s&&(l=hi(l,[0,3,1,2])),l}))}Qp.className="Softmax",yi(Qp);class sd extends Dc{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",sd.verifyArgs(t),this.rank=e,ol(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new Uo(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Xp(t.kernelSize,e,"kernelSize"),this.strides=Xp(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,kl(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,wl(this.dataFormat),this.activation=Pp(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=yc(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=ph(t.biasConstraint),this.biasRegularizer=Kp(t.biasRegularizer),this.activityRegularizer=Kp(t.activityRegularizer),this.dilationRate=Xp(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new Bo(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(2===this.rank){if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate];else if(2!==this.dilationRate.length)throw new Bo(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(3===this.rank)if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(3!==this.dilationRate.length)throw new Bo(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(Ko("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!=typeof e.kernelSize&&!rl(e.kernelSize,"number",1,3))throw new Bo(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Mp(this.activation),useBias:this.useBias,biasInitializer:vc(this.biasInitializer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),biasConstraint:uh(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class rd extends sd{constructor(e,t){super(e,t),this.kernel=null,rd.verifyArgs(t),this.filters=t.filters,ol(this.filters,"filters"),this.kernelInitializer=yc(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=ph(t.kernelConstraint),this.kernelRegularizer=Kp(t.kernelRegularizer)}build(e){e=xc(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Bo(`The channel dimension of the input should be defined. Found ${e[t]}`);const n=e[t],i=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",i,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return si((()=>{let t;e=kc(e);const n=null==this.bias?null:this.bias.read(),i=cl(this.activation.getClassName());if(null!=i&&2===this.rank)t=ad(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,i);else{if(1===this.rank)t=function(e,t,n,i=1,a="valid",s,r=1){return si((()=>{if(null==s&&(s="channelsLast"),wl(s),3!==e.shape.length)throw new Bo(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new Bo(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new Bo(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if("channelsFirst"===s&&(e=hi(e,[0,2,1])),"causal"===a)throw new Uo("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=aa(e,t,i,"same"===a?"same":"valid","NWC",r);return null!=n&&(o=Hl(o,n)),o}))}(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=ad(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new Uo("convolutions greater than 3D are not implemented yet.");t=function(e,t,n,i=[1,1,1],a="valid",s,r){return si((()=>{if(null==s&&(s="channelsLast"),wl(s),4!==e.rank&&5!==e.rank)throw new Bo(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new Bo(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=id(e,s);if("causal"===a)throw new Uo("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=oa(o,t,i,"same"===a?"same":"valid","NDHWC",r),null!=n&&(o=Hl(o,n)),"channelsFirst"===s&&(o=hi(o,[0,4,1,2,3])),o}))}(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate)}null!=this.activation&&(t=this.activation.apply(t))}return t}))}computeOutputShape(e){e=xc(e);const t=[],n="channelsLast"===this.dataFormat?e.slice(1,e.length-1):e.slice(2);for(let e=0;e<n.length;++e){const i=ed(n[e],this.kernelSize[e],this.padding,this.strides[e],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[e]);t.push(i)}let i=[e[0]];return"channelsLast"===this.dataFormat?(i=i.concat(t),i.push(this.filters)):(i.push(this.filters),i=i.concat(t)),i}getConfig(){const e={filters:this.filters,kernelInitializer:vc(this.kernelInitializer),kernelRegularizer:Gp(this.kernelRegularizer),kernelConstraint:uh(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||"number"!=typeof e.filters||e.filters<1)throw new Bo(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class od extends rd{constructor(e){super(2,e),od.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!rl(e.kernelSize,"number",1,2))throw new Bo(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}od.className="Conv2D",yi(od);class ld extends rd{constructor(e){super(3,e),ld.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&(!Array.isArray(e.kernelSize)||1!==e.kernelSize.length&&3!==e.kernelSize.length))throw new Bo(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}ld.className="Conv3D",yi(ld);class cd extends od{constructor(e){if(super(e),this.inputSpec=[new Ac({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new Bo(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=xc(e)).length)throw new Bo("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Bo("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],i=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",i,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Ac({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return si((()=>{let t=kc(e);if(4!==t.shape.length)throw new Bo(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,i=n[0];let a,s;"channelsFirst"===this.dataFormat?(a=2,s=3):(a=1,s=2);const r=n[a],o=n[s],l=this.kernelSize[0],c=this.kernelSize[1],u=this.strides[0],h=this.strides[1],p=[i,td(r,u,l,this.padding),td(o,h,c,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=hi(t,[0,2,3,1]));let d=ra(t,this.kernel.read(),p,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(d=hi(d,[0,3,1,2])),null!=this.bias&&(d=Hl(d,this.bias.read(),this.dataFormat)),null!=this.activation&&(d=this.activation.apply(d)),d}))}computeOutputShape(e){const t=(e=xc(e)).slice();let n,i,a;"channelsFirst"===this.dataFormat?(n=1,i=2,a=3):(n=3,i=1,a=2);const s=this.kernelSize[0],r=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[i]=td(t[i],o,s,this.padding),t[a]=td(t[a],l,r,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}cd.className="Conv2DTranspose",yi(cd);class ud extends ld{constructor(e){if(super(e),this.inputSpec=[new Ac({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new Bo(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(5!==(e=xc(e)).length)throw new Bo("Input should have rank 5; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Bo("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],i=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",i,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Ac({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return si((()=>{let t=kc(e);if(5!==t.shape.length)throw new Bo(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,i=n[0];let a,s,r;"channelsFirst"===this.dataFormat?(r=2,a=3,s=4):(r=1,a=2,s=3);const o=n[r],l=n[a],c=n[s],u=this.kernelSize[0],h=this.kernelSize[1],p=this.kernelSize[2],d=this.strides[0],m=this.strides[1],f=this.strides[2],g=[i,td(o,d,u,this.padding),td(l,m,h,this.padding),td(c,f,p,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=hi(t,[0,2,3,4,1]));let v=ca(t,this.kernel.read(),g,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(v=hi(v,[0,4,1,2,3])),null!==this.bias&&(v=Hl(v,this.bias.read(),this.dataFormat)),null!==this.activation&&(v=this.activation.apply(v)),v}))}computeOutputShape(e){const t=(e=xc(e)).slice();let n,i,a,s;"channelsFirst"===this.dataFormat?(n=1,i=2,a=3,s=4):(n=4,i=1,a=2,s=3);const r=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],c=this.strides[0],u=this.strides[1],h=this.strides[2];return t[n]=this.filters,t[i]=td(t[i],c,r,this.padding),t[a]=td(t[a],u,o,this.padding),t[s]=td(t[s],h,l,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}ud.className="Conv3DTranspose",yi(ud);class hd extends rd{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,null==t.filters)throw new Bo("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new Bo("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=t.padding&&"same"!==t.padding&&"valid"!==t.padding)throw new Bo(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,this.depthwiseInitializer=yc(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Kp(t.depthwiseRegularizer),this.depthwiseConstraint=ph(t.depthwiseConstraint),this.pointwiseInitializer=yc(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Kp(t.pointwiseRegularizer),this.pointwiseConstraint=ph(t.pointwiseConstraint)}build(e){if((e=xc(e)).length<this.rank+2)throw new Bo(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t]||e[t]<0)throw new Bo(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);const n=e[t],i=this.kernelSize.concat([n,this.depthMultiplier]),a=[];for(let e=0;e<this.rank;++e)a.push(1);a.push(n*this.depthMultiplier,this.filters);const s=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",i,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,s,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",a,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,s,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,s,this.biasConstraint):this.bias=null,this.inputSpec=[new Ac({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return si((()=>{let t;if(e=kc(e),1===this.rank)throw new Uo("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=hi(e,[0,2,3,1])),t=Ds(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=Hl(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=hi(t,[0,3,1,2])),t}))}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=vc(this.depthwiseInitializer),e.pointwiseInitializer=vc(this.pointwiseInitializer),e.depthwiseRegularizer=Gp(this.depthwiseRegularizer),e.pointwiseRegularizer=Gp(this.pointwiseRegularizer),e.depthwiseConstraint=uh(this.depthwiseConstraint),e.pointwiseConstraint=uh(this.pointwiseConstraint),e}}hd.className="SeparableConv";class pd extends hd{constructor(e){super(2,e)}}pd.className="SeparableConv2D",yi(pd);class dd extends rd{constructor(e){super(1,e),dd.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!rl(e.kernelSize,"number",1,1))throw new Bo(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}dd.className="Conv1D",yi(dd);class md extends Dc{constructor(e){super(e),"number"==typeof e.cropping?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return"channelsFirst"===this.dataFormat?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return si((()=>{if(e=kc(e),"channelsLast"===this.dataFormat){const t=Ol(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Ol(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=Ol(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Ol(t,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}}))}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}md.className="Cropping2D",yi(md);class fd extends Dc{constructor(e){var t;super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=null==e.size?this.DEFAULT_SIZE:e.size,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wl(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,sl(fl,"InterpolationFormat",t)}computeOutputShape(e){if("channelsFirst"===this.dataFormat){const t=null==e[2]?null:this.size[0]*e[2],n=null==e[3]?null:this.size[1]*e[3];return[e[0],e[1],t,n]}{const t=null==e[1]?null:this.size[0]*e[1],n=null==e[2]?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return si((()=>{let t=kc(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=hi(t,[0,2,3,1]);const e=this.size[0]*n[2],i=this.size[1]*n[3],a="nearest"===this.interpolation?zr.resizeNearestNeighbor(t,[e,i]):zr.resizeBilinear(t,[e,i]);return hi(a,[0,3,1,2])}{const e=this.size[0]*n[1],i=this.size[1]*n[2];return"nearest"===this.interpolation?zr.resizeNearestNeighbor(t,[e,i]):zr.resizeBilinear(t,[e,i])}}))}getConfig(){const e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}}fd.className="UpSampling2D",yi(fd);class gd extends sd{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=yc(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=ph(e.depthwiseConstraint),this.depthwiseRegularizer=Kp(e.depthwiseRegularizer)}build(e){if((e=xc(e)).length<4)throw new Bo(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t="channelsFirst"===this.dataFormat?1:3;if(null==e[t]||e[t]<0)throw new Bo(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const n=e[t],i=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",i,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return si((()=>{let t=
|
|
4495
4495
|
/**
|
|
4496
4496
|
* @license
|
|
4497
4497
|
* Copyright 2018 Google LLC
|
|
@@ -4511,7 +4511,7 @@ function(e,t,n=[1,1],i="valid",a,s){return si((()=>{null==a&&(a="channelsLast"),
|
|
|
4511
4511
|
* https://opensource.org/licenses/MIT.
|
|
4512
4512
|
* =============================================================================
|
|
4513
4513
|
*/
|
|
4514
|
-
function vd(e,t,n,i){if(Array.isArray(e)){if(null!=t||null!=n)throw new Bo("When inputs is an array, neither initialState or constants should be provided");null!=i&&(n=e.slice(e.length-i,e.length),e=e.slice(0,e.length-i)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function a(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=a(t),constants:n=a(n)}}function yd(e,t,n,i=!1,a,s,r=!1,o=!1){return si((()=>{const l=t.shape.length;if(l<3)throw new Bo(`Input should be at least 3D, but is ${l}D.`);const c=[1,0].concat(zl(2,l));if(t=hi(t,c),null!=s)throw new Uo("The rnn() functoin of the deeplearn.js backend does not support constants yet.");r&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=a&&((a=ei(ei(a,"bool"),"float32")).rank===l-1&&(a=_a(a,-1)),a=hi(a,c)),i&&(t=Cs(t,0),null!=a&&(a=Cs(a,0)));const u=[];let h,p=n;const d=t.shape[0],m=Js(t);let f,g;null!=a&&(f=Js(a));for(let t=0;t<d;++t){const n=m[t],i=si((()=>e(n,p)));if(null==a)h=i[0],p=i[1];else{const e=si((()=>{const e=f[t],n=Ja(ls(e),e);return{output:bi(xi(i[0],e),xi(p[0],n)),newStates:p.map(((t,a)=>bi(xi(i[1][a],e),xi(t,n))))}}));h=e.output,p=e.newStates}o&&u.push(h)}if(o){g=Ws(u,1)}return[h,g,p]}))}gd.className="DepthwiseConv2D",yi(gd);class bd extends Dc{constructor(e){let t;if(super(e),null==e.cell)throw new Bo("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new Ad({cells:e.cell}):e.cell,null==t.stateSize)throw new Bo("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=null!=e.returnSequences&&e.returnSequences,this.returnState=null!=e.returnState&&e.returnState,this.goBackwards=null!=e.goBackwards&&e.goBackwards,this._stateful=null!=e.stateful&&e.stateful,this.unroll=null!=e.unroll&&e.unroll,this.supportsMasking=!0,this.inputSpec=[new Ec({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(null==this.states_){return zl(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((e=>null))}return this.states_}setStates(e){this.states_=e}computeOutputShape(e){bc(e)&&(e=e[0]);let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const n=t[0];let i;if(i=this.returnSequences?[e[0],e[1],n]:[e[0],n],this.returnState){const n=[];for(const i of t)n.push([e[0],i]);return[i].concat(n)}return i}computeMask(e,t){return si((()=>{Array.isArray(t)&&(t=t[0]);const e=this.returnSequences?t:null;if(this.returnState){const t=this.states.map((e=>null));return[e].concat(t)}return e}))}get states(){if(null==this.states_){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}return this.states_}set states(e){this.states_=e}build(e){if(null!=this.numConstants)throw new Uo("Constants support is not implemented in RNN yet.");bc(e)&&(e=e[0]);const t=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new Ec({shape:[t,null,...n]});const i=[e[0]].concat(e.slice(2));let a;if(this.cell.build(i),a=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!C(this.stateSpec.map((e=>e.shape[e.shape.length-1])),a))throw new Bo(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map((e=>new Ec({shape:[null,e]})));this.stateful&&this.resetStates()}resetStates(e,t=!1){si((()=>{if(!this.stateful)throw new Oo("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new Bo("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.states_)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>is([n,e]))):this.states_=[is([n,this.cell.stateSize])];else if(null==e)ri(this.states_),null!=this.keptStates&&(ri(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>is([n,e]))):this.states_[0]=is([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Bo(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);!0===t?this.keptStates.push(this.states_.slice()):ri(this.states_);for(let t=0;t<this.states_.length;++t){const i=e[t],a=Array.isArray(this.cell.stateSize)?this.cell.stateSize[t]:this.cell.stateSize,s=[n,a];if(!C(i.shape,s))throw new Bo(`State ${t} is incompatible with layer ${this.name}: expected shape=${s}, received shape=${i.shape}`);this.states_[t]=i}}this.states_=this.states_.map((e=>oi(e.clone())))}))}apply(e,t){let n=null==t?null:t.initialState,i=null==t?null:t.constants;null==t&&(t={});const a=vd(e,n,i,this.numConstants);e=a.inputs,n=a.initialState,i=a.constants;let s=[],r=[];if(null!=n){t.initialState=n,s=s.concat(n),this.stateSpec=[];for(const e of n)this.stateSpec.push(new Ec({shape:e.shape}));r=r.concat(this.stateSpec)}null!=i&&(t.constants=i,s=s.concat(i),this.numConstants=i.length);if(s[0]instanceof Cc){const n=[e].concat(s),i=this.inputSpec.concat(r),a=this.inputSpec;this.inputSpec=i;const o=super.apply(n,t);return this.inputSpec=a,o}return super.apply(e,t)}call(e,t){return si((()=>{const n=null==t?null:t.mask,i=null==t?null:t.training;let a=null==t?null:t.initialState;e=kc(e),null==a&&(a=this.stateful?this.states_:this.getInitialState(e));const s=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(a.length!==s)throw new Bo(`RNN Layer has ${s} state(s) but was passed ${a.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const r={training:i},o=yd(((e,t)=>{const n=this.cell.call([e].concat(t),r);return[n[0],n.slice(1)]}),e,a,this.goBackwards,n,null,this.unroll,this.returnSequences),l=o[0],c=o[1],u=o[2];this.stateful&&this.resetStates(u,i);const h=this.returnSequences?c:l;return this.returnState?[h].concat(u):h}))}getInitialState(e){return si((()=>{let t=is(e.shape);return t=ja(t,[1,2]),t=Rl(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((e=>e>1?Ul(t,[1,e]):t)):this.cell.stateSize>1?[Ul(t,[1,this.cell.stateSize])]:[t]}))}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);const n=this.cell.getConfig();return this.getClassName()===bd.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign(Object.assign(Object.assign({},n),e),t)}static fromConfig(e,t,n={}){const i=Nh(t.cell,n);return new e(Object.assign(t,{cell:i}))}}bd.className="RNN",yi(bd);class wd extends Dc{}class kd extends wd{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,ol(this.units,"units"),this.activation=Pp(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=yc(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Kp(e.kernelRegularizer),this.recurrentRegularizer=Kp(e.recurrentRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.kernelConstraint=ph(e.kernelConstraint),this.recurrentConstraint=ph(e.recurrentConstraint),this.biasConstraint=ph(e.biasConstraint),this.dropout=$l([1,jl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=$l([1,jl([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=xc(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return si((()=>{if(2!==e.length)throw new Bo(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];const i=null!=t.training&&t.training;let a;0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ed({ones:()=>ls(e),rate:this.dropout,training:i,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ed({ones:()=>ls(n),rate:this.recurrentDropout,training:i,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,r=this.recurrentDropoutMask;a=Gl(null!=s?xi(e,s):e,this.kernel.read()),null!=this.bias&&(a=Hl(a,this.bias.read())),null!=r&&(n=xi(n,r));let o=bi(a,Gl(n,this.recurrentKernel.read()));return null!=this.activation&&(o=this.activation.apply(o)),[o,o]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Mp(this.activation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),recurrentInitializer:vc(this.recurrentInitializer),biasInitializer:vc(this.biasInitializer),kernelRegularizer:Gp(this.kernelRegularizer),recurrentRegularizer:Gp(this.recurrentRegularizer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),recurrentConstraint:uh(this.recurrentConstraint),biasConstraint:uh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}kd.className="SimpleRNNCell",yi(kd);class xd extends bd{constructor(e){e.cell=new kd(e),super(e)}call(e,t){return si((()=>{null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}static fromConfig(e,t){return new e(t)}}xd.className="SimpleRNN",yi(xd);class Sd extends wd{constructor(e){if(super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new Bo("GRUCell does not support reset_after parameter set to true.");this.units=e.units,ol(this.units,"units"),this.activation=Pp(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Pp(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=yc(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Kp(e.kernelRegularizer),this.recurrentRegularizer=Kp(e.recurrentRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.kernelConstraint=ph(e.kernelConstraint),this.recurrentConstraint=ph(e.recurrentConstraint),this.biasConstraint=ph(e.biasConstraint),this.dropout=$l([1,jl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=$l([1,jl([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){const t=(e=xc(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return si((()=>{if(2!==e.length)throw new Bo(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const n=null!=t.training&&t.training;let i=e[1];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ed({ones:()=>ls(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ed({ones:()=>ls(i),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,s=this.recurrentDropoutMask;let r,o,l;0<this.dropout&&this.dropout<1&&(e=xi(e,a[0]));let c=Gl(e,this.kernel.read());this.useBias&&(c=Hl(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(i=xi(i,s[0]));const u=this.recurrentKernel.read(),[h,p]=Bs(u,[2*this.units,this.units],u.rank-1),d=Gl(i,h),[m,f,g]=Bs(c,3,c.rank-1),[v,y]=Bs(d,2,d.rank-1);r=this.recurrentActivation.apply(bi(m,v)),o=this.recurrentActivation.apply(bi(f,y));const b=Gl(xi(o,i),p);l=this.activation.apply(bi(g,b));const w=bi(xi(r,i),xi(bi(1,ci(r)),l));return[w,w]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Mp(this.activation),recurrentActivation:Mp(this.recurrentActivation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),recurrentInitializer:vc(this.recurrentInitializer),biasInitializer:vc(this.biasInitializer),kernelRegularizer:Gp(this.kernelRegularizer),recurrentRegularizer:Gp(this.recurrentRegularizer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),recurrentConstraint:uh(this.recurrentConstraint),biasConstraint:uh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}}Sd.className="GRUCell",yi(Sd);class Nd extends bd{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Sd(e),super(e)}call(e,t){return si((()=>{null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Nd.className="GRU",yi(Nd);class Id extends wd{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,ol(this.units,"units"),this.activation=Pp(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Pp(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=yc(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Kp(e.kernelRegularizer),this.recurrentRegularizer=Kp(e.recurrentRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.kernelConstraint=ph(e.kernelConstraint),this.recurrentConstraint=ph(e.recurrentConstraint),this.biasConstraint=ph(e.biasConstraint),this.dropout=$l([1,jl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=$l([1,jl([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;const n=(e=xc(e))[e.length-1];let i;if(this.kernel=this.addWeight("kernel",[n,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){const e=this.biasInitializer,n=this.units;i=new((t=class extends Xl{apply(t,i){const a=e.apply([n]),s=(new tc).apply([n]),r=e.apply([2*n]);return Bl(Bl(a,s),r)}}).className="CustomInit",t)}else i=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,i,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return si((()=>{const n=null!=t.training&&t.training;if(3!==e.length)throw new Bo(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let i=e[1];const a=e[2];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ed({ones:()=>ls(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ed({ones:()=>ls(i),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,r=this.recurrentDropoutMask;let o,l,c,u;0<this.dropout&&this.dropout<1&&(e=xi(e,s[0]));let h=Gl(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(i=xi(i,r[0])),h=bi(h,Gl(i,this.recurrentKernel.read())),this.useBias&&(h=Hl(h,this.bias.read()));const[p,d,m,f]=Bs(h,4,h.rank-1);o=this.recurrentActivation.apply(p),l=this.recurrentActivation.apply(d),c=bi(xi(l,a),xi(o,this.activation.apply(m))),u=this.recurrentActivation.apply(f);const g=xi(u,this.activation.apply(c));return[g,g,c]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Mp(this.activation),recurrentActivation:Mp(this.recurrentActivation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),recurrentInitializer:vc(this.recurrentInitializer),biasInitializer:vc(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Gp(this.kernelRegularizer),recurrentRegularizer:Gp(this.recurrentRegularizer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),recurrentConstraint:uh(this.recurrentConstraint),biasConstraint:uh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}}Id.className="LSTMCell",yi(Id);class Td extends bd{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Id(e),super(e)}call(e,t){return si((()=>{null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Td.className="LSTM",yi(Td);class Ad extends wd{constructor(e){super(e),this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return si((()=>{let n=e.slice(1);const i=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?i.push(n.splice(0,e.stateSize.length)):i.push(n.splice(0,1));i.reverse();const a=[];let s;for(let r=0;r<this.cells.length;++r){const o=this.cells[r];n=i[r],s=0===r?[e[0]].concat(n):[s[0]].concat(n),s=o.call(s,t),a.push(s.slice(1))}n=[];for(const e of a.slice().reverse())n.push(...e);return[s[0]].concat(n)}))}build(e){let t;bc(e)&&(e=e[0]),this.cells.forEach(((n,i)=>{Nl(`RNNCell_${i}`,(()=>{n.build(e),t=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,e=[e[0],t]}))})),this.built=!0}getConfig(){const e=super.getConfig(),t={cells:this.cells.map((e=>({className:e.getClassName(),config:e.getConfig()})))};return Object.assign(Object.assign({},e),t)}static fromConfig(e,t,n={}){const i=[];for(const e of t.cells)i.push(Nh(e,n));return new e({cells:i})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.cells)t.push(...e.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return Tc(e)}setWeights(e){const t=[];for(const n of this.cells){const i=n.weights.length,a=e.splice(i);for(let e=0;e<n.weights.length;++e)t.push([n.weights[e],a[e]])}Ac(t)}}function Ed(e){const{ones:t,rate:n,training:i=!1,count:a=1,dropoutFunc:s}=e,r=()=>null!=s?s(t(),n):Jl(t(),n),o=()=>Zl(r,t,i);if(!a||a<=1)return oi(o().clone());return Array(a).fill(void 0).map(o).map((e=>oi(e.clone())))}
|
|
4514
|
+
function vd(e,t,n,i){if(Array.isArray(e)){if(null!=t||null!=n)throw new Bo("When inputs is an array, neither initialState or constants should be provided");null!=i&&(n=e.slice(e.length-i,e.length),e=e.slice(0,e.length-i)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function a(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=a(t),constants:n=a(n)}}function yd(e,t,n,i=!1,a,s,r=!1,o=!1){return si((()=>{const l=t.shape.length;if(l<3)throw new Bo(`Input should be at least 3D, but is ${l}D.`);const c=[1,0].concat(zl(2,l));if(t=hi(t,c),null!=s)throw new Uo("The rnn() functoin of the deeplearn.js backend does not support constants yet.");r&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=a&&((a=ei(ei(a,"bool"),"float32")).rank===l-1&&(a=_a(a,-1)),a=hi(a,c)),i&&(t=Cs(t,0),null!=a&&(a=Cs(a,0)));const u=[];let h,p=n;const d=t.shape[0],m=Js(t);let f,g;null!=a&&(f=Js(a));for(let t=0;t<d;++t){const n=m[t],i=si((()=>e(n,p)));if(null==a)h=i[0],p=i[1];else{const e=si((()=>{const e=f[t],n=Ja(ls(e),e);return{output:bi(xi(i[0],e),xi(p[0],n)),newStates:p.map(((t,a)=>bi(xi(i[1][a],e),xi(t,n))))}}));h=e.output,p=e.newStates}o&&u.push(h)}if(o){g=Ws(u,1)}return[h,g,p]}))}gd.className="DepthwiseConv2D",yi(gd);class bd extends Dc{constructor(e){let t;if(super(e),null==e.cell)throw new Bo("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new Ed({cells:e.cell}):e.cell,null==t.stateSize)throw new Bo("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=null!=e.returnSequences&&e.returnSequences,this.returnState=null!=e.returnState&&e.returnState,this.goBackwards=null!=e.goBackwards&&e.goBackwards,this._stateful=null!=e.stateful&&e.stateful,this.unroll=null!=e.unroll&&e.unroll,this.supportsMasking=!0,this.inputSpec=[new Ac({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(null==this.states_){return zl(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((e=>null))}return this.states_}setStates(e){this.states_=e}computeOutputShape(e){bc(e)&&(e=e[0]);let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const n=t[0];let i;if(i=this.returnSequences?[e[0],e[1],n]:[e[0],n],this.returnState){const n=[];for(const i of t)n.push([e[0],i]);return[i].concat(n)}return i}computeMask(e,t){return si((()=>{Array.isArray(t)&&(t=t[0]);const e=this.returnSequences?t:null;if(this.returnState){const t=this.states.map((e=>null));return[e].concat(t)}return e}))}get states(){if(null==this.states_){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}return this.states_}set states(e){this.states_=e}build(e){if(null!=this.numConstants)throw new Uo("Constants support is not implemented in RNN yet.");bc(e)&&(e=e[0]);const t=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new Ac({shape:[t,null,...n]});const i=[e[0]].concat(e.slice(2));let a;if(this.cell.build(i),a=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!C(this.stateSpec.map((e=>e.shape[e.shape.length-1])),a))throw new Bo(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map((e=>new Ac({shape:[null,e]})));this.stateful&&this.resetStates()}resetStates(e,t=!1){si((()=>{if(!this.stateful)throw new Oo("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new Bo("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.states_)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>is([n,e]))):this.states_=[is([n,this.cell.stateSize])];else if(null==e)ri(this.states_),null!=this.keptStates&&(ri(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>is([n,e]))):this.states_[0]=is([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Bo(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);!0===t?this.keptStates.push(this.states_.slice()):ri(this.states_);for(let t=0;t<this.states_.length;++t){const i=e[t],a=Array.isArray(this.cell.stateSize)?this.cell.stateSize[t]:this.cell.stateSize,s=[n,a];if(!C(i.shape,s))throw new Bo(`State ${t} is incompatible with layer ${this.name}: expected shape=${s}, received shape=${i.shape}`);this.states_[t]=i}}this.states_=this.states_.map((e=>oi(e.clone())))}))}apply(e,t){let n=null==t?null:t.initialState,i=null==t?null:t.constants;null==t&&(t={});const a=vd(e,n,i,this.numConstants);e=a.inputs,n=a.initialState,i=a.constants;let s=[],r=[];if(null!=n){t.initialState=n,s=s.concat(n),this.stateSpec=[];for(const e of n)this.stateSpec.push(new Ac({shape:e.shape}));r=r.concat(this.stateSpec)}null!=i&&(t.constants=i,s=s.concat(i),this.numConstants=i.length);if(s[0]instanceof Cc){const n=[e].concat(s),i=this.inputSpec.concat(r),a=this.inputSpec;this.inputSpec=i;const o=super.apply(n,t);return this.inputSpec=a,o}return super.apply(e,t)}call(e,t){return si((()=>{const n=null==t?null:t.mask,i=null==t?null:t.training;let a=null==t?null:t.initialState;e=kc(e),null==a&&(a=this.stateful?this.states_:this.getInitialState(e));const s=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(a.length!==s)throw new Bo(`RNN Layer has ${s} state(s) but was passed ${a.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const r={training:i},o=yd(((e,t)=>{const n=this.cell.call([e].concat(t),r);return[n[0],n.slice(1)]}),e,a,this.goBackwards,n,null,this.unroll,this.returnSequences),l=o[0],c=o[1],u=o[2];this.stateful&&this.resetStates(u,i);const h=this.returnSequences?c:l;return this.returnState?[h].concat(u):h}))}getInitialState(e){return si((()=>{let t=is(e.shape);return t=ja(t,[1,2]),t=Rl(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((e=>e>1?Ul(t,[1,e]):t)):this.cell.stateSize>1?[Ul(t,[1,this.cell.stateSize])]:[t]}))}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);const n=this.cell.getConfig();return this.getClassName()===bd.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign(Object.assign(Object.assign({},n),e),t)}static fromConfig(e,t,n={}){const i=Nh(t.cell,n);return new e(Object.assign(t,{cell:i}))}}bd.className="RNN",yi(bd);class wd extends Dc{}class kd extends wd{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,ol(this.units,"units"),this.activation=Pp(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=yc(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Kp(e.kernelRegularizer),this.recurrentRegularizer=Kp(e.recurrentRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.kernelConstraint=ph(e.kernelConstraint),this.recurrentConstraint=ph(e.recurrentConstraint),this.biasConstraint=ph(e.biasConstraint),this.dropout=$l([1,jl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=$l([1,jl([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=xc(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return si((()=>{if(2!==e.length)throw new Bo(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];const i=null!=t.training&&t.training;let a;0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ad({ones:()=>ls(e),rate:this.dropout,training:i,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ad({ones:()=>ls(n),rate:this.recurrentDropout,training:i,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,r=this.recurrentDropoutMask;a=Gl(null!=s?xi(e,s):e,this.kernel.read()),null!=this.bias&&(a=Hl(a,this.bias.read())),null!=r&&(n=xi(n,r));let o=bi(a,Gl(n,this.recurrentKernel.read()));return null!=this.activation&&(o=this.activation.apply(o)),[o,o]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Mp(this.activation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),recurrentInitializer:vc(this.recurrentInitializer),biasInitializer:vc(this.biasInitializer),kernelRegularizer:Gp(this.kernelRegularizer),recurrentRegularizer:Gp(this.recurrentRegularizer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),recurrentConstraint:uh(this.recurrentConstraint),biasConstraint:uh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}kd.className="SimpleRNNCell",yi(kd);class xd extends bd{constructor(e){e.cell=new kd(e),super(e)}call(e,t){return si((()=>{null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}static fromConfig(e,t){return new e(t)}}xd.className="SimpleRNN",yi(xd);class Sd extends wd{constructor(e){if(super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new Bo("GRUCell does not support reset_after parameter set to true.");this.units=e.units,ol(this.units,"units"),this.activation=Pp(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Pp(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=yc(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Kp(e.kernelRegularizer),this.recurrentRegularizer=Kp(e.recurrentRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.kernelConstraint=ph(e.kernelConstraint),this.recurrentConstraint=ph(e.recurrentConstraint),this.biasConstraint=ph(e.biasConstraint),this.dropout=$l([1,jl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=$l([1,jl([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){const t=(e=xc(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return si((()=>{if(2!==e.length)throw new Bo(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const n=null!=t.training&&t.training;let i=e[1];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ad({ones:()=>ls(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ad({ones:()=>ls(i),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,s=this.recurrentDropoutMask;let r,o,l;0<this.dropout&&this.dropout<1&&(e=xi(e,a[0]));let c=Gl(e,this.kernel.read());this.useBias&&(c=Hl(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(i=xi(i,s[0]));const u=this.recurrentKernel.read(),[h,p]=Bs(u,[2*this.units,this.units],u.rank-1),d=Gl(i,h),[m,f,g]=Bs(c,3,c.rank-1),[v,y]=Bs(d,2,d.rank-1);r=this.recurrentActivation.apply(bi(m,v)),o=this.recurrentActivation.apply(bi(f,y));const b=Gl(xi(o,i),p);l=this.activation.apply(bi(g,b));const w=bi(xi(r,i),xi(bi(1,ci(r)),l));return[w,w]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Mp(this.activation),recurrentActivation:Mp(this.recurrentActivation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),recurrentInitializer:vc(this.recurrentInitializer),biasInitializer:vc(this.biasInitializer),kernelRegularizer:Gp(this.kernelRegularizer),recurrentRegularizer:Gp(this.recurrentRegularizer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),recurrentConstraint:uh(this.recurrentConstraint),biasConstraint:uh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}}Sd.className="GRUCell",yi(Sd);class Nd extends bd{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Sd(e),super(e)}call(e,t){return si((()=>{null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Nd.className="GRU",yi(Nd);class Id extends wd{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,ol(this.units,"units"),this.activation=Pp(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Pp(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=yc(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Kp(e.kernelRegularizer),this.recurrentRegularizer=Kp(e.recurrentRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.kernelConstraint=ph(e.kernelConstraint),this.recurrentConstraint=ph(e.recurrentConstraint),this.biasConstraint=ph(e.biasConstraint),this.dropout=$l([1,jl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=$l([1,jl([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;const n=(e=xc(e))[e.length-1];let i;if(this.kernel=this.addWeight("kernel",[n,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){const e=this.biasInitializer,n=this.units;i=new((t=class extends Xl{apply(t,i){const a=e.apply([n]),s=(new tc).apply([n]),r=e.apply([2*n]);return Bl(Bl(a,s),r)}}).className="CustomInit",t)}else i=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,i,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return si((()=>{const n=null!=t.training&&t.training;if(3!==e.length)throw new Bo(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let i=e[1];const a=e[2];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ad({ones:()=>ls(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ad({ones:()=>ls(i),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,r=this.recurrentDropoutMask;let o,l,c,u;0<this.dropout&&this.dropout<1&&(e=xi(e,s[0]));let h=Gl(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(i=xi(i,r[0])),h=bi(h,Gl(i,this.recurrentKernel.read())),this.useBias&&(h=Hl(h,this.bias.read()));const[p,d,m,f]=Bs(h,4,h.rank-1);o=this.recurrentActivation.apply(p),l=this.recurrentActivation.apply(d),c=bi(xi(l,a),xi(o,this.activation.apply(m))),u=this.recurrentActivation.apply(f);const g=xi(u,this.activation.apply(c));return[g,g,c]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Mp(this.activation),recurrentActivation:Mp(this.recurrentActivation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),recurrentInitializer:vc(this.recurrentInitializer),biasInitializer:vc(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Gp(this.kernelRegularizer),recurrentRegularizer:Gp(this.recurrentRegularizer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),recurrentConstraint:uh(this.recurrentConstraint),biasConstraint:uh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}}Id.className="LSTMCell",yi(Id);class Td extends bd{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Id(e),super(e)}call(e,t){return si((()=>{null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Td.className="LSTM",yi(Td);class Ed extends wd{constructor(e){super(e),this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return si((()=>{let n=e.slice(1);const i=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?i.push(n.splice(0,e.stateSize.length)):i.push(n.splice(0,1));i.reverse();const a=[];let s;for(let r=0;r<this.cells.length;++r){const o=this.cells[r];n=i[r],s=0===r?[e[0]].concat(n):[s[0]].concat(n),s=o.call(s,t),a.push(s.slice(1))}n=[];for(const e of a.slice().reverse())n.push(...e);return[s[0]].concat(n)}))}build(e){let t;bc(e)&&(e=e[0]),this.cells.forEach(((n,i)=>{Nl(`RNNCell_${i}`,(()=>{n.build(e),t=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,e=[e[0],t]}))})),this.built=!0}getConfig(){const e=super.getConfig(),t={cells:this.cells.map((e=>({className:e.getClassName(),config:e.getConfig()})))};return Object.assign(Object.assign({},e),t)}static fromConfig(e,t,n={}){const i=[];for(const e of t.cells)i.push(Nh(e,n));return new e({cells:i})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.cells)t.push(...e.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return Tc(e)}setWeights(e){const t=[];for(const n of this.cells){const i=n.weights.length,a=e.splice(i);for(let e=0;e<n.weights.length;++e)t.push([n.weights[e],a[e]])}Ec(t)}}function Ad(e){const{ones:t,rate:n,training:i=!1,count:a=1,dropoutFunc:s}=e,r=()=>null!=s?s(t(),n):Jl(t(),n),o=()=>Zl(r,t,i);if(!a||a<=1)return oi(o().clone());return Array(a).fill(void 0).map(o).map((e=>oi(e.clone())))}
|
|
4515
4515
|
/**
|
|
4516
4516
|
* @license
|
|
4517
4517
|
* Copyright 2020 Google LLC
|
|
@@ -4520,7 +4520,7 @@ function vd(e,t,n,i){if(Array.isArray(e)){if(null!=t||null!=n)throw new Bo("When
|
|
|
4520
4520
|
* license that can be found in the LICENSE file or at
|
|
4521
4521
|
* https://opensource.org/licenses/MIT.
|
|
4522
4522
|
* =============================================================================
|
|
4523
|
-
*/
|
|
4523
|
+
*/Ed.className="StackedRNNCells",yi(Ed);var Cd=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(i=Object.getOwnPropertySymbols(e);a<i.length;a++)t.indexOf(i[a])<0&&Object.prototype.propertyIsEnumerable.call(e,i[a])&&(n[i[a]]=e[i[a]])}return n};class $d extends bd{constructor(e){if(e.unroll)throw new Uo("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Uo("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new Ac({ndim:5})]}call(e,t){return si((()=>{if(null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new Bo("ConvRNN2D cell does not support constants");const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return si((()=>{const{stateSize:t}=this.cell,n=e.shape,i=this.computeSingleOutputShape(n),a=is([i[0],...i.slice(2)]);return Array.isArray(t)?Array(t.length).fill(a):[a]}))}resetStates(e,t=!1){si((()=>{if(!this.stateful)throw new Oo("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape,i=this.computeSingleOutputShape(n),a=[i[0],...i.slice(2)];if(null==n[0])throw new Bo("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.getStates())Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>is(a))):this.states_=[is(a)];else if(null==e)ri(this.states_),null!=this.keptStates&&(ri(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>is(a))):this.states_[0]=is(a);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Bo(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):ri(this.states_);for(let t=0;t<this.states_.length;++t){const n=e[t],i=a;if(!C(n.shape,i))throw new Bo(`State ${t} is incompatible with layer ${this.name}: expected shape=${i}, received shape=${n.shape}`);this.states_[t]=n}}this.states_=this.states_.map((e=>oi(e.clone())))}))}computeSingleOutputShape(e){const{dataFormat:t,filters:n,kernelSize:i,padding:a,strides:s,dilationRate:r}=this.cell,o="channelsFirst"===t,l=e[o?3:2],c=e[o?4:3],u=ed(l,i[0],a,s[0],r[0]),h=ed(c,i[1],a,s[1],r[1]);return[...e.slice(0,2),...o?[n,u,h]:[u,h,n]]}}$d.className="ConvRNN2D";class jd extends Id{constructor(e){const{filters:t,kernelSize:n,strides:i,padding:a,dataFormat:s,dilationRate:r}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,ol(this.filters,"filters"),this.kernelSize=Xp(n,2,"kernelSize"),this.kernelSize.forEach((e=>ol(e,"kernelSize"))),this.strides=Xp(i||1,2,"strides"),this.strides.forEach((e=>ol(e,"strides"))),this.padding=a||"valid",kl(this.padding),this.dataFormat=s||"channelsLast",wl(this.dataFormat),this.dilationRate=Xp(r||1,2,"dilationRate"),this.dilationRate.forEach((e=>ol(e,"dilationRate")))}build(e){var t;e=xc(e);const n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new Bo(`The channel dimension of the input should be defined. Found ${e[n]}`);const i=e[n],a=this.kernelSize.concat([i,4*this.filters]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const s=this.kernelSize.concat([this.filters,4*this.filters]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",s,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let e;if(this.unitForgetBias){const n=this.biasInitializer,i=this.filters;e=new((t=class extends Xl{apply(e,t){return Pl([n.apply([i]),as([i]),n.apply([2*i])])}}).className="CustomInit",t)}else e=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.filters],null,e,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return si((()=>{if(3!==e.length)throw new Bo(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training||!1,i=e[0],a=e[1],s=e[2];0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ad({ones:()=>ls(i),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const r=this.dropoutMask,o=(e,t,n)=>t&&t[n]?xi(t[n],e):e;let l=o(i,r,0),c=o(i,r,1),u=o(i,r,2),h=o(i,r,3);0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ad({ones:()=>ls(a),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const p=this.recurrentDropoutMask;let d=o(a,p,0),m=o(a,p,1),f=o(a,p,2),g=o(a,p,3);const[v,y,b,w]=Bs(this.kernel.read(),4,3),[k,x,S,N]=this.useBias?Bs(this.bias.read(),4):[null,null,null,null];l=this.inputConv(l,v,k,this.padding),c=this.inputConv(c,y,x,this.padding),u=this.inputConv(u,b,S,this.padding),h=this.inputConv(h,w,N,this.padding);const[I,T,E,A]=Bs(this.recurrentKernel.read(),4,3);d=this.recurrentConv(d,I),m=this.recurrentConv(m,T),f=this.recurrentConv(f,E),g=this.recurrentConv(g,A);const C=this.recurrentActivation.apply(bi(l,d)),$=this.recurrentActivation.apply(bi(c,m)),j=bi(xi($,s),xi(C,this.activation.apply(bi(u,f)))),z=xi(this.recurrentActivation.apply(bi(h,g)),this.activation.apply(j));return[z,z,j]}))}getConfig(){const e=super.getConfig(),t=Cd(e,["units"]),n={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},t),n)}inputConv(e,t,n,i){const a=ia(e,t,this.strides,i||"valid","channelsFirst"===this.dataFormat?"NCHW":"NHWC",this.dilationRate);return n?Hl(a,n,this.dataFormat):a}recurrentConv(e,t){return ia(e,t,1,"same","channelsFirst"===this.dataFormat?"NCHW":"NHWC")}}jd.className="ConvLSTM2DCell",yi(jd);class zd extends $d{constructor(e){const t=new jd(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}}zd.className="ConvLSTM2D",yi(zd);
|
|
4524
4524
|
/**
|
|
4525
4525
|
* @license
|
|
4526
4526
|
* Copyright 2018 Google LLC
|
|
@@ -4530,7 +4530,7 @@ function vd(e,t,n,i){if(Array.isArray(e)){if(null!=t||null!=n)throw new Bo("When
|
|
|
4530
4530
|
* https://opensource.org/licenses/MIT.
|
|
4531
4531
|
* =============================================================================
|
|
4532
4532
|
*/
|
|
4533
|
-
class Dd extends Dc{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(null==this.noiseShape)return this.noiseShape;const t=e.shape,n=[];for(let e=0;e<this.noiseShape.length;++e)n.push(null==this.noiseShape[e]?t[e]:this.noiseShape[e]);return n}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e);if(0<this.rate&&this.rate<1){const e=null!=t.training&&t.training,i=this.getNoiseShape(n);return Zl((()=>Jl(n,this.rate,i,this.seed)),(()=>n),e)}return e}))}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}Dd.className="Dropout",yi(Dd);class Fd extends Dd{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}Fd.className="SpatialDropout1D",yi(Fd);class _d extends Dc{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){let t=null;null!=e.batchSize&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,ol(this.units,"units"),this.activation=Pp(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=ph(e.kernelConstraint),this.biasConstraint=ph(e.biasConstraint),this.kernelRegularizer=Kp(e.kernelRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.activityRegularizer=Kp(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=xc(e))[e.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){const t=(e=xc(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e),i=cl(this.activation.getClassName());let a;return null!=i?a=Gl(n,this.kernel.read(),i,this.bias?this.bias.read():null):(a=Gl(n,this.kernel.read()),null!=this.bias&&(a=Hl(a,this.bias.read())),null!=this.activation&&(a=this.activation.apply(a))),a}))}getConfig(){const e={units:this.units,activation:Mp(this.activation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),biasInitializer:vc(this.biasInitializer),kernelRegularizer:Gp(this.kernelRegularizer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),biasConstraint:uh(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}_d.className="Dense",yi(_d);class Rd extends Dc{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=xc(e);for(const t of e.slice(1))if(null==t)throw new Bo(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],Cl(e,1)]}call(e,t){return si((()=>{this.invokeCallHook(e,t);let n=kc(e);if("channelsFirst"===this.dataFormat&&n.rank>1){const e=[0];for(let t=2;t<n.rank;++t)e.push(t);e.push(1),n=hi(n,e)}return function(e){if(e.rank<=1)throw new Bo(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],Cl(e.shape,1)];return _i(e,t)}(n)}))}getConfig(){const e={};null!=this.dataFormat&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}Rd.className="Flatten",yi(Rd);class Ld extends Dc{constructor(e){super(e),this.supportsMasking=!0,this.activation=Pp(e.activation)}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e);return this.activation.apply(n)}))}getConfig(){const e={activation:Mp(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}Ld.className="Activation",yi(Ld);class Md extends Dc{constructor(e){super(e),this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return si((()=>{return e=kc(e),t=e,n=this.n,si((()=>{if(2!==t.shape.length)throw new Bo(`repeat() expects a rank-2 tensor, but received a rank-${t.shape.length} tensor.`);return Ul(Rl(t,1),[1,n,1])}));var t,n}))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}Md.className="RepeatVector",yi(Md);class Od extends Dc{constructor(e){super(e),this.targetShape=e.targetShape;for(let e=0;e<this.targetShape.length;++e)this.isUnknown(this.targetShape[e])&&(this.targetShape[e]=null)}isUnknown(e){return e<0||null==e}fixUnknownDimension(e,t){const n="Total size of new array must be unchanged.",i=t.slice();let a=1,s=null;for(let e=0;e<i.length;++e){const t=i[e];if(this.isUnknown(t)){if(null!==s)throw new Bo("Can only specifiy one unknown dimension.");s=e}else a*=t}const r=Cl(e);if(null!==s){if(0===a||r%a!=0)throw new Bo(n);i[s]=r/a}else if(r!==a)throw new Bo(n);return i}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e),i=n.shape,a=i.slice(0,1).concat(this.fixUnknownDimension(i.slice(1),this.targetShape));return _i(n,a)}))}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}Od.className="Reshape",yi(Od);class Pd extends Dc{constructor(e){if(super(e),null==e.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);const t=zl(1,e.dims.length+1);if(!C(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new
|
|
4533
|
+
class Dd extends Dc{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(null==this.noiseShape)return this.noiseShape;const t=e.shape,n=[];for(let e=0;e<this.noiseShape.length;++e)n.push(null==this.noiseShape[e]?t[e]:this.noiseShape[e]);return n}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e);if(0<this.rate&&this.rate<1){const e=null!=t.training&&t.training,i=this.getNoiseShape(n);return Zl((()=>Jl(n,this.rate,i,this.seed)),(()=>n),e)}return e}))}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}Dd.className="Dropout",yi(Dd);class Fd extends Dd{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}Fd.className="SpatialDropout1D",yi(Fd);class _d extends Dc{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){let t=null;null!=e.batchSize&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,ol(this.units,"units"),this.activation=Pp(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=ph(e.kernelConstraint),this.biasConstraint=ph(e.biasConstraint),this.kernelRegularizer=Kp(e.kernelRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.activityRegularizer=Kp(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=xc(e))[e.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){const t=(e=xc(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e),i=cl(this.activation.getClassName());let a;return null!=i?a=Gl(n,this.kernel.read(),i,this.bias?this.bias.read():null):(a=Gl(n,this.kernel.read()),null!=this.bias&&(a=Hl(a,this.bias.read())),null!=this.activation&&(a=this.activation.apply(a))),a}))}getConfig(){const e={units:this.units,activation:Mp(this.activation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),biasInitializer:vc(this.biasInitializer),kernelRegularizer:Gp(this.kernelRegularizer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),biasConstraint:uh(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}_d.className="Dense",yi(_d);class Rd extends Dc{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=xc(e);for(const t of e.slice(1))if(null==t)throw new Bo(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],Cl(e,1)]}call(e,t){return si((()=>{this.invokeCallHook(e,t);let n=kc(e);if("channelsFirst"===this.dataFormat&&n.rank>1){const e=[0];for(let t=2;t<n.rank;++t)e.push(t);e.push(1),n=hi(n,e)}return function(e){if(e.rank<=1)throw new Bo(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],Cl(e.shape,1)];return _i(e,t)}(n)}))}getConfig(){const e={};null!=this.dataFormat&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}Rd.className="Flatten",yi(Rd);class Ld extends Dc{constructor(e){super(e),this.supportsMasking=!0,this.activation=Pp(e.activation)}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e);return this.activation.apply(n)}))}getConfig(){const e={activation:Mp(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}Ld.className="Activation",yi(Ld);class Md extends Dc{constructor(e){super(e),this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return si((()=>{return e=kc(e),t=e,n=this.n,si((()=>{if(2!==t.shape.length)throw new Bo(`repeat() expects a rank-2 tensor, but received a rank-${t.shape.length} tensor.`);return Ul(Rl(t,1),[1,n,1])}));var t,n}))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}Md.className="RepeatVector",yi(Md);class Od extends Dc{constructor(e){super(e),this.targetShape=e.targetShape;for(let e=0;e<this.targetShape.length;++e)this.isUnknown(this.targetShape[e])&&(this.targetShape[e]=null)}isUnknown(e){return e<0||null==e}fixUnknownDimension(e,t){const n="Total size of new array must be unchanged.",i=t.slice();let a=1,s=null;for(let e=0;e<i.length;++e){const t=i[e];if(this.isUnknown(t)){if(null!==s)throw new Bo("Can only specifiy one unknown dimension.");s=e}else a*=t}const r=Cl(e);if(null!==s){if(0===a||r%a!=0)throw new Bo(n);i[s]=r/a}else if(r!==a)throw new Bo(n);return i}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e),i=n.shape,a=i.slice(0,1).concat(this.fixUnknownDimension(i.slice(1),this.targetShape));return _i(n,a)}))}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}Od.className="Reshape",yi(Od);class Pd extends Dc{constructor(e){if(super(e),null==e.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);const t=zl(1,e.dims.length+1);if(!C(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new Ac({ndim:this.dims.length+1})]}computeOutputShape(e){const t=(e=xc(e)).slice();return this.dims.forEach(((n,i)=>{t[i+1]=e[n]})),t}call(e,t){return hi(kc(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}Pd.className="Permute",yi(Pd);class Bd extends Dc{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,this.maskValue=null!=e?null==e.maskValue?0:e.maskValue:0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const n=kc(e);return Ii(os(n,this.maskValue),-1)}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e),i=Ii(os(n,this.maskValue),-1,!0);return xi(n,ei(i,n.dtype))}))}}Bd.className="Masking",yi(Bd);
|
|
4534
4534
|
/**
|
|
4535
4535
|
* @license
|
|
4536
4536
|
* Copyright 2018 Google LLC
|
|
@@ -4570,7 +4570,7 @@ class Qd extends Dc{constructor(e){super(e),this.supportsMasking=!0,this.stddev=
|
|
|
4570
4570
|
* https://opensource.org/licenses/MIT.
|
|
4571
4571
|
* =============================================================================
|
|
4572
4572
|
*/
|
|
4573
|
-
function tm(e,t,n,i,a,s=.001){let r;if(2===e.rank)r=Vi(e,t,n,i,a,s);else if(3===e.rank)r=Ki(e,t,n,i,a,s);else{if(4!==e.rank)throw new Uo(`batchNormalization is not implemented for array of rank ${e.rank} yet`);r=qi(e,t,n,i,a,s)}return r}function nm(e,t,n,i,a=.001){return C(i.slice().sort(),zl(0,e.rank-1))?function(e,t,n,i,a=.001){return si((()=>{const s=rs(e,i),r=s.mean,o=s.variance;return[tm(e,r,o,n,t,a),r,o]}))}(e,t,n,i,a):function(e,t,n,i,a=.001){return si((()=>{const s=rs(e,i),r=s.mean,o=s.variance,l=[];for(const t of zl(0,e.rank))-1!==i.indexOf(t)?l.push(1):l.push(e.shape[t]);const c=_i(r,l),u=_i(o,l),h=null==t?null:_i(t,l),p=null==n?null:_i(n,l);return[tm(e,c,u,p,h,a),r,o]}))}(e,t,n,i,a)}em.className="AlphaDropout",yi(em);class im extends Dc{constructor(e){null==e&&(e={}),super(e),this.supportsMasking=!0,this.axis=null==e.axis?-1:e.axis,this.momentum=null==e.momentum?.99:e.momentum,this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=yc(e.betaInitializer||"zeros"),this.gammaInitializer=yc(e.gammaInitializer||"ones"),this.movingMeanInitializer=yc(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=yc(e.movingVarianceInitializer||"ones"),this.betaConstraint=ph(e.betaConstraint),this.gammaConstraint=ph(e.gammaConstraint),this.betaRegularizer=Kp(e.betaRegularizer),this.gammaRegularizer=Kp(e.gammaRegularizer)}build(e){e=xc(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new Bo(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new
|
|
4573
|
+
function tm(e,t,n,i,a,s=.001){let r;if(2===e.rank)r=Vi(e,t,n,i,a,s);else if(3===e.rank)r=Ki(e,t,n,i,a,s);else{if(4!==e.rank)throw new Uo(`batchNormalization is not implemented for array of rank ${e.rank} yet`);r=qi(e,t,n,i,a,s)}return r}function nm(e,t,n,i,a=.001){return C(i.slice().sort(),zl(0,e.rank-1))?function(e,t,n,i,a=.001){return si((()=>{const s=rs(e,i),r=s.mean,o=s.variance;return[tm(e,r,o,n,t,a),r,o]}))}(e,t,n,i,a):function(e,t,n,i,a=.001){return si((()=>{const s=rs(e,i),r=s.mean,o=s.variance,l=[];for(const t of zl(0,e.rank))-1!==i.indexOf(t)?l.push(1):l.push(e.shape[t]);const c=_i(r,l),u=_i(o,l),h=null==t?null:_i(t,l),p=null==n?null:_i(n,l);return[tm(e,c,u,p,h,a),r,o]}))}(e,t,n,i,a)}em.className="AlphaDropout",yi(em);class im extends Dc{constructor(e){null==e&&(e={}),super(e),this.supportsMasking=!0,this.axis=null==e.axis?-1:e.axis,this.momentum=null==e.momentum?.99:e.momentum,this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=yc(e.betaInitializer||"zeros"),this.gammaInitializer=yc(e.gammaInitializer||"ones"),this.movingMeanInitializer=yc(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=yc(e.movingVarianceInitializer||"ones"),this.betaConstraint=ph(e.betaConstraint),this.gammaConstraint=ph(e.gammaConstraint),this.betaRegularizer=Kp(e.betaRegularizer),this.gammaRegularizer=Kp(e.gammaRegularizer)}build(e){e=xc(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new Bo(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Ac({ndim:e.length,axes:{[t]:n}})];const i=[n];this.scale&&(this.gamma=this.addWeight("gamma",i,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",i,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",i,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",i,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return si((()=>{const n=null!=t.training&&t.training,i=kc(e),a=i.shape,s=a.length,r=zl(0,s),o=this.axis>=0?this.axis:this.axis+s;r.splice(o,1);const l=Vo(1,s);l[o]=a[o];const c=r.slice();c.sort();const u=!C(c,zl(0,s).slice(0,s-1));if(!n)return(()=>{if(u){const e=_i(this.movingMean.read(),l),t=_i(this.movingVariance.read(),l),n=this.center?_i(this.beta.read(),l):null,a=this.scale?_i(this.gamma.read(),l):null;return tm(i,e,t,n,a,this.epsilon)}return tm(i,this.movingMean.read(),this.movingVariance.read(),null==this.beta?null:this.beta.read(),null==this.gamma?null:this.gamma.read(),this.epsilon)})();const[h,p,d]=nm(i,this.gamma.read(),this.beta.read(),r,this.epsilon),m=(e,t,n)=>{si((()=>{const i=1-n,a=e.read(),s=xi(Ja(a,t),i);e.write(Ja(a,s))}))};return(()=>{m(this.movingMean,p,this.momentum),m(this.movingVariance,d,this.momentum)})(),h}))}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:vc(this.betaInitializer),gammaInitializer:vc(this.gammaInitializer),movingMeanInitializer:vc(this.movingMeanInitializer),movingVarianceInitializer:vc(this.movingVarianceInitializer),betaRegularizer:Gp(this.betaRegularizer),gammaRegularizer:Gp(this.gammaRegularizer),betaConstraint:uh(this.betaConstraint),gammaConstraint:uh(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}im.className="BatchNormalization",yi(im);class am extends Dc{constructor(e){if(null==e&&(e={}),super(e),this.axis=null==e.axis?-1:e.axis,"number"==typeof this.axis){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else{if(!Array.isArray(this.axis))throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);for(const e of this.axis)if(!Number.isInteger(e))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=yc(e.betaInitializer||"zeros"),this.gammaInitializer=yc(e.gammaInitializer||"ones"),this.betaRegularizer=Kp(e.betaRegularizer),this.gammaRegularizer=Kp(e.gammaRegularizer),this.supportsMasking=!0}build(e){const t=(e=xc(e)).length;"number"==typeof this.axis&&(this.axis=[this.axis]);for(let e=0;e<this.axis.length;++e)this.axis[e]<0&&(this.axis[e]+=t);for(const e of this.axis)if(e<0||e>=t)throw new Error(`Invalid axis: ${e}`);if(this.axis.length!==il(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const n=this.axis.map((t=>e[t]));this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,true):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,true):this.beta=null,this.built=!0}call(e,t){const n=kc(e),i=n.shape,a=i.length;return si((()=>{let{mean:e,variance:t}=rs(n,this.axis,!0);const s=Vo(1,a);for(const e of this.axis)s[e]=i[e];const r=e=>null!=e&&e.shape.length!==a?_i(e,s):e;let o=this.scale?r(this.gamma.read()):null,l=this.center?r(this.beta.read()):null;const c=[],u=[];for(let e=0;e<a;++e)-1!==this.axis.indexOf(e)?(c.push(i[e]),u.push(1)):(c.push(1),u.push(i[e]));return e=Ra(e,c),t=Ra(t,c),null!=o&&(o=Ra(o,u)),null!=l&&(l=Ra(l,u)),tm(n,e,t,l,o,this.epsilon)}))}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:vc(this.betaInitializer),gammaInitializer:vc(this.gammaInitializer),betaRegularizer:Gp(this.betaRegularizer),gammaRegularizer:Gp(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}am.className="LayerNormalization",yi(am);class sm extends Dc{constructor(e){if(null==e&&(e={}),super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,null==e.padding)this.padding=[[1,1],[1,1]];else if("number"==typeof e.padding)this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,2!==e.padding.length)throw new Bo(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if("number"==typeof e.padding[0])t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,2!==e.padding[0].length)throw new Bo(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],2!==e.padding[1].length)throw new Bo(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new Ac({ndim:4})]}computeOutputShape(e){let t,n;return e=xc(e),"channelsFirst"===this.dataFormat?(t=null!=e[2]&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]])}call(e,t){return si((()=>{return t=kc(e),n=this.padding,i=this.dataFormat,si((()=>{if(4!==t.rank)throw new Bo(`temporalPadding expects input tensor to be 4-D, but received a ${t.rank}-D tensor.`);if(null==n&&(n=[[1,1],[1,1]]),2!==n.length||2!==n[0].length||2!==n[1].length)throw new Bo("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==i&&(i="channelsLast"),"channelsLast"!==i&&"channelsFirst"!==i)throw new Bo(`Unknown data format: ${i}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let e;return e="channelsFirst"===i?[[0,0],[0,0],n[0],n[1]]:[[0,0],n[0],n[1],[0,0]],cs(t,e)}));
|
|
4574
4574
|
/**
|
|
4575
4575
|
* @license
|
|
4576
4576
|
* Copyright 2018 Google LLC
|
|
@@ -4590,7 +4590,7 @@ var t,n,i}))}getConfig(){const e={padding:this.padding,dataFormat:this.dataForma
|
|
|
4590
4590
|
* https://opensource.org/licenses/MIT.
|
|
4591
4591
|
* =============================================================================
|
|
4592
4592
|
*/
|
|
4593
|
-
function rm(e,t,n,i,a,s){return si((()=>{let r;wl(a),xl(s),kl(i),null==n&&(n=[1,1]),null==i&&(i="valid"),null==a&&(a="channelsLast"),null==s&&(s="max"),e=nd(e,a);const o="same"===i?"same":"valid";return r="max"===s?Xa(e,t,n,o):Ri(e,t,n,o),"channelsFirst"===a&&(r=hi(r,[0,3,1,2])),r}))}function om(e,t,n,i,a,s){return si((()=>{let r;wl(a),xl(s),kl(i),null==n&&(n=[1,1,1]),null==i&&(i="valid"),null==a&&(a="channelsLast"),null==s&&(s="max"),e=id(e,a);const o="same"===i?"same":"valid";return r="max"===s?es(e,t,n,o):Li(e,t,n,o),"channelsFirst"===a&&(r=hi(r,[0,4,1,2,3])),r}))}sm.className="ZeroPadding2D",yi(sm);class lm extends Dc{constructor(e){if(null==e.poolSize&&(e.poolSize=2),super(e),"number"==typeof e.poolSize)this.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new Bo(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);this.poolSize=e.poolSize}if(ol(this.poolSize,"poolSize"),null==e.strides)this.strides=this.poolSize;else if("number"==typeof e.strides)this.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new Bo(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);this.strides=e.strides}ol(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,kl(this.padding),this.inputSpec=[new
|
|
4593
|
+
function rm(e,t,n,i,a,s){return si((()=>{let r;wl(a),xl(s),kl(i),null==n&&(n=[1,1]),null==i&&(i="valid"),null==a&&(a="channelsLast"),null==s&&(s="max"),e=nd(e,a);const o="same"===i?"same":"valid";return r="max"===s?Xa(e,t,n,o):Ri(e,t,n,o),"channelsFirst"===a&&(r=hi(r,[0,3,1,2])),r}))}function om(e,t,n,i,a,s){return si((()=>{let r;wl(a),xl(s),kl(i),null==n&&(n=[1,1,1]),null==i&&(i="valid"),null==a&&(a="channelsLast"),null==s&&(s="max"),e=id(e,a);const o="same"===i?"same":"valid";return r="max"===s?es(e,t,n,o):Li(e,t,n,o),"channelsFirst"===a&&(r=hi(r,[0,4,1,2,3])),r}))}sm.className="ZeroPadding2D",yi(sm);class lm extends Dc{constructor(e){if(null==e.poolSize&&(e.poolSize=2),super(e),"number"==typeof e.poolSize)this.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new Bo(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);this.poolSize=e.poolSize}if(ol(this.poolSize,"poolSize"),null==e.strides)this.strides=this.poolSize;else if("number"==typeof e.strides)this.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new Bo(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);this.strides=e.strides}ol(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,kl(this.padding),this.inputSpec=[new Ac({ndim:3})]}computeOutputShape(e){const t=ed((e=xc(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return si((()=>{this.invokeCallHook(e,t),e=Rl(kc(e),2);const n=this.poolingFunction(kc(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Us(n,[2])}))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class cm extends lm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),rm(e,t,n,i,a,"max")}}cm.className="MaxPooling1D",yi(cm);class um extends lm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),rm(e,t,n,i,a,"avg")}}um.className="AveragePooling1D",yi(um);class hm extends Dc{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new Bo(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];ol(this.poolSize,"poolSize"),ol(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wl(this.dataFormat),kl(this.padding),this.inputSpec=[new Ac({ndim:4})]}computeOutputShape(e){e=xc(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=ed(t,this.poolSize[0],this.padding,this.strides[0]),n=ed(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return si((()=>(this.invokeCallHook(e,t),this.poolingFunction(kc(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class pm extends hm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),rm(e,t,n,i,a,"max")}}pm.className="MaxPooling2D",yi(pm);class dm extends hm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),rm(e,t,n,i,a,"avg")}}dm.className="AveragePooling2D",yi(dm);class mm extends Dc{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(3!==e.strides.length)throw new Bo(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];ol(this.poolSize,"poolSize"),ol(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wl(this.dataFormat),kl(this.padding),this.inputSpec=[new Ac({ndim:5})]}computeOutputShape(e){e=xc(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],i="channelsFirst"===this.dataFormat?e[4]:e[3];return t=ed(t,this.poolSize[0],this.padding,this.strides[0]),n=ed(n,this.poolSize[1],this.padding,this.strides[1]),i=ed(i,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n,i]:[e[0],t,n,i,e[4]]}call(e,t){return si((()=>(this.invokeCallHook(e,t),this.poolingFunction(kc(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class fm extends mm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),om(e,t,n,i,a,"max")}}fm.className="MaxPooling3D",yi(fm);class gm extends mm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),om(e,t,n,i,a,"avg")}}gm.className="AveragePooling3D",yi(gm);class vm extends Dc{constructor(e){super(e),this.inputSpec=[new Ac({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Uo}}class ym extends vm{constructor(e){super(e||{})}call(e,t){return si((()=>{const t=kc(e);return ns(t,1)}))}}ym.className="GlobalAveragePooling1D",yi(ym);class bm extends vm{constructor(e){super(e||{})}call(e,t){return si((()=>{const t=kc(e);return Ia(t,1)}))}}bm.className="GlobalMaxPooling1D",yi(bm);class wm extends Dc{constructor(e){super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wl(this.dataFormat),this.inputSpec=[new Ac({ndim:4})]}computeOutputShape(e){return"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Uo}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class km extends wm{call(e,t){return si((()=>{const t=kc(e);return"channelsLast"===this.dataFormat?ns(t,[1,2]):ns(t,[2,3])}))}}km.className="GlobalAveragePooling2D",yi(km);class xm extends wm{call(e,t){return si((()=>{const t=kc(e);return"channelsLast"===this.dataFormat?Ia(t,[1,2]):Ia(t,[2,3])}))}}xm.className="GlobalMaxPooling2D",yi(xm);
|
|
4594
4594
|
/**
|
|
4595
4595
|
* @license
|
|
4596
4596
|
* Copyright 2018 Google LLC
|
|
@@ -4600,7 +4600,7 @@ function rm(e,t,n,i,a,s){return si((()=>{let r;wl(a),xl(s),kl(i),null==n&&(n=[1,
|
|
|
4600
4600
|
* https://opensource.org/licenses/MIT.
|
|
4601
4601
|
* =============================================================================
|
|
4602
4602
|
*/
|
|
4603
|
-
class Sm extends Dc{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return null!=this.layer&&this.layer.trainable}set trainable(e){null!=this.layer&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){const i=Nh(t.layer,n);delete t.layer;const a={layer:i};return Object.assign(a,t),new e(a)}}class Nm extends Sm{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=xc(e)).length<3)throw new Bo(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){const t=[(e=xc(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),i=e[1];return[n[0],i].concat(n.slice(1))}call(e,t){return si((()=>yd(((e,n)=>[kc(this.layer.call(e,t)),[]]),e=kc(e),[],!1,null,null,!1,!0)[1]))}}Nm.className="TimeDistributed",yi(Nm);class Im extends Sm{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Nh(n),t.goBackwards=!0!==t.goBackwards;const i={};var a;if(i.className=e.layer.getClassName(),i.config=t,this.backwardLayer=Nh(i),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,a=this.mergeMode,sl(yl,"BidirectionalMergeMode",a),e.weights)throw new Uo("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t,n,i,a=this.forwardLayer.computeOutputShape(e);return Array.isArray(a)&&Array.isArray(a[0])||(a=[a]),this.returnState?(i=a.slice(1),t=a[0]):t=a[0],"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(i).concat(i.slice()):[t].concat(i).concat(i.slice()):Ho(n)}apply(e,t){let n=null==t?null:t.initialState,i=null==t?null:t.constants;null==t&&(t={});const a=vd(e,n,i,this.numConstants);if(e=a.inputs,n=a.initialState,i=a.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(null==n||0===n.length)&&null==i)return super.apply(e,t);const s=[],r=[];if(null!=n){const e=n.length;if(e%2>0)throw new Bo("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,s.push(...n);const i=n.map((e=>new
|
|
4603
|
+
class Sm extends Dc{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return null!=this.layer&&this.layer.trainable}set trainable(e){null!=this.layer&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){const i=Nh(t.layer,n);delete t.layer;const a={layer:i};return Object.assign(a,t),new e(a)}}class Nm extends Sm{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=xc(e)).length<3)throw new Bo(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){const t=[(e=xc(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),i=e[1];return[n[0],i].concat(n.slice(1))}call(e,t){return si((()=>yd(((e,n)=>[kc(this.layer.call(e,t)),[]]),e=kc(e),[],!1,null,null,!1,!0)[1]))}}Nm.className="TimeDistributed",yi(Nm);class Im extends Sm{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Nh(n),t.goBackwards=!0!==t.goBackwards;const i={};var a;if(i.className=e.layer.getClassName(),i.config=t,this.backwardLayer=Nh(i),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,a=this.mergeMode,sl(yl,"BidirectionalMergeMode",a),e.weights)throw new Uo("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t,n,i,a=this.forwardLayer.computeOutputShape(e);return Array.isArray(a)&&Array.isArray(a[0])||(a=[a]),this.returnState?(i=a.slice(1),t=a[0]):t=a[0],"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(i).concat(i.slice()):[t].concat(i).concat(i.slice()):Ho(n)}apply(e,t){let n=null==t?null:t.initialState,i=null==t?null:t.constants;null==t&&(t={});const a=vd(e,n,i,this.numConstants);if(e=a.inputs,n=a.initialState,i=a.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(null==n||0===n.length)&&null==i)return super.apply(e,t);const s=[],r=[];if(null!=n){const e=n.length;if(e%2>0)throw new Bo("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,s.push(...n);const i=n.map((e=>new Ac({shape:e.shape})));this.forwardLayer.stateSpec=i.slice(0,e/2),this.backwardLayer.stateSpec=i.slice(e/2),r.push(...i)}if(null!=i)throw new Uo("Support for constants in Bidirectional layers is not implemented yet.");const o=s[0]instanceof Cc;for(const e of s)if(e instanceof Cc!==o)throw new Bo("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){const n=[e].concat(s),i=this.inputSpec.concat(r),a=this.inputSpec;this.inputSpec=i;const o=super.apply(n,t);return this.inputSpec=a,o}return super.apply(e,t)}call(e,t){return si((()=>{const n=t.initialState;let i,a,s,r;if(null==n)i=this.forwardLayer.call(e,t),a=this.backwardLayer.call(e,t);else{const s=n.slice(0,n.length/2),r=n.slice(n.length/2);i=this.forwardLayer.call(e,Object.assign(t,{initialState:s})),a=this.backwardLayer.call(e,Object.assign(t,{initialState:r}))}return this.returnState&&(Array.isArray(i)&&(s=i.slice(1).concat(a.slice(1))),i=i[0],a=a[0]),this.returnSequences&&(a=Cs(a,1)),"concat"===this.mergeMode?r=Pl([i,a]):"sum"===this.mergeMode?r=bi(i,a):"ave"===this.mergeMode?r=xi(.5,bi(i,a)):"mul"===this.mergeMode?r=xi(i,a):null==this.mergeMode&&(r=[i,a]),this.returnState?null==this.mergeMode?r.concat(s):[r].concat(s):r}))}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){Nl(this.forwardLayer.name,(()=>{this.forwardLayer.build(e)})),Nl(this.backwardLayer.name,(()=>{this.backwardLayer.build(e)})),this.built=!0}computeMask(e,t){let n;if(Array.isArray(t)&&(t=t[0]),n=this.returnSequences?null==this.mergeMode?[t,t]:t:null==this.mergeMode?[null,null]:null,this.returnState){const e=this.forwardLayer.states.map((e=>null));return Array.isArray(n)?n.concat(e).concat(e):[n].concat(e).concat(e)}return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(e),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const n=Nh(t.layer);if(delete t.layer,null!=t.numConstants)throw new Uo("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const i=t;return i.layer=n,new e(i)}}Im.className="Bidirectional",yi(Im);
|
|
4604
4604
|
/**
|
|
4605
4605
|
* @license
|
|
4606
4606
|
* Copyright 2022 CodeSmith LLC
|
|
@@ -4620,7 +4620,7 @@ class Tm extends Dc{constructor(e){super(e),this.scale=e.scale,e.offset?this.off
|
|
|
4620
4620
|
* https://opensource.org/licenses/MIT.
|
|
4621
4621
|
* =============================================================================
|
|
4622
4622
|
*/
|
|
4623
|
-
const{resizeBilinear:
|
|
4623
|
+
const{resizeBilinear:Em,cropAndResize:Am}=zr;class Cm extends Dc{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,n,i,a,s,r,o){return si((()=>{let l,c=!1;const u=[t/s,n/r,(i+t)/s,(a+n)/r],h=[];3===e.rank?(c=!0,l=Ws([e])):l=e;for(let e=0;e<l.shape[0];e++)h.push(u);const p=gn(h,[h.length,4]),d=Ts(0,h.length,1,"int32"),m=Am(l,p,d,[i,a],"nearest");return _l(c?kc(Js(m)):m,o)}))}upsize(e,t,n,i){return si((()=>_l(Em(e,[t,n]),i)))}call(e,t){return si((()=>{const t=kc(e),n=t.dtype,i=t.shape,a=i[i.length-3],s=i[i.length-2];let r=0;a!==this.height&&(r=Math.floor((a-this.height)/2));let o=0;return s!==this.width&&(o=Math.floor((s-this.width)/2),0===o&&(o=1)),r>=0&&o>=0?this.centerCrop(t,r,o,this.height,this.width,a,s,n):this.upsize(e,this.height,this.width,n)}))}getConfig(){const e={height:this.height,width:this.width},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=xc(e)).length-3,n=e.length-2;return e[t]=this.height,e[n]=this.width,e}}Cm.className="CenterCrop",yi(Cm);
|
|
4624
4624
|
/**
|
|
4625
4625
|
* @license
|
|
4626
4626
|
* Copyright 2022 CodeSmith LLC
|
|
@@ -4667,7 +4667,7 @@ const jm=new Set(["bilinear","nearest"]);class zm extends Dc{constructor(e){if(s
|
|
|
4667
4667
|
* limitations under the License.
|
|
4668
4668
|
* =============================================================================
|
|
4669
4669
|
*/
|
|
4670
|
-
xt(Io),xt(lo),xt(Ao),xt(Eo),xt(Co),xt($o),xt(wo),xt(jo),xt(Mo),xt(vo),xt(_o),xt(xo),xt(ro);var Dm={"штих":"noun","пяних":"noun","белих":"adjective","борзих":"adjective","малих":"adjective","старих":"adjective","дарнопих":"noun","сухих":"adjective","черемних":"noun","сирих":"adjective","плохих":"adjective","целих":"adjective","жих":"noun","войцих":"noun","скорих":"adjective","бурих":"adjective","чалих":"adjective","серих":"adjective","удалих":"adjective","карих":"adjective","гених":"noun","литвих":"noun","марцих":"noun","сізих":"adjective","яних":"noun","мжачих":"adjective","сірих":"adjective","янбих":"noun","бодрих":"adjective","войтих":"adjective","стрий":"noun","чорторий":"noun","юрий":"adjective","цибрий":"noun","цібрий":"noun","карий":"adjective","куприй":"noun","кирий":"noun","негрий":"noun","губрий":"noun","шкабрий":"noun","замрий":"noun","передрий":"noun","одерий":"noun","жегрий":"noun","порий":"adjective","жарий":"adjective","зюбрий":"noun","семерий":"noun","лий":"noun","бий":"noun","рий":"noun","вий":"noun","ший":"noun","валий":"noun","крайній":"adjective","осінній":"adjective","кутній":"adjective","середній":"adjective","горішній":"adjective","безродній":"adjective","осадчій":"adjective","кий":"noun","новохатній":"adjective","очеретній":"adjective","рбий":"noun","закутній":"adjective","недавній":"adjective","порожній":"adjective","бокий":"noun","вчерашній":"adjective","огородній":"adjective","трощий":"noun","крічфалушій":"adjective","карагеоргій":"adjective","вчорашній":"adjective","житній":"adjective","нижній":"adjective","синій":"adjective","хорий":"noun","краснобокій":"adjective","хижній":"adjective","калюжній":"adjective","виноградній":"adjective","коломий":"noun","летучій":"adjective","поздній":"adjective","польчій":"adjective","серий":"noun","нагорній":"adjective","фартушній":"adjective","холошвій":"noun","батий":"noun","волошиній":"adjective","жирий":"noun","заможній":"adjective","короткій":"adjective","останній":"adjective","передній":"adjective","піддубній":"adjective","пізній":"adjective","погородній":"adjective","бояжній":"adjective","сивній":"adjective","смий":"noun","задвірній":"adjective","остатній":"adjective","підсадній":"adjective","достатній":"adjective","жамардій":"adjective","зимній":"adjective","рябой":"adjective","рудой":"adjective","козодой":"noun","яровой":"adjective","кривой":"adjective","садовой":"adjective","полевой":"adjective","сисой":"noun","плохой":"adjective","сухой":"adjective","гаєвой":"adjective","глухой":"adjective","горевой":"adjective","іоніцой":"noun","кутовой":"adjective","копаной":"adjective","злой":"adjective","сєдой":"adjective","благой":"adjective","водостой":"noun","косой":"adjective","ліждвой":"noun","большой":"adjective","кальной":"noun","половой":"adjective","чорной":"adjective","косогой":"adjective","золотой":"adjective","лановой":"adjective","яловой":"adjective","дорогой":"adjective","німой":"adjective","первой":"adjective","русой":"adjective","худой":"adjective","цаподой":"noun","авасілой":"noun","валовой":"adjective","гнідой":"adjective","молокопой":"noun","золотобой":"noun","ярковой":"noun","аміхалакіой":"noun","седой":"adjective","крутой":"adjective","кучной":"adjective","слепой":"adjective","дурной":"adjective","молодой":"adjective","бухой":"adjective","самотній":"adjective","біла":"adjective","бура":"adjective","велика":"adjective","домовина":"noun","рослина":"noun","врецьона":"noun","глибока":"adjective","висока":"adjective","гладка":"adjective","грицина":"noun","гужва":"noun","ковінька":"noun","дика":"adjective","діброва":"noun","кицька":"noun","ківа":"noun","лепка":"adjective","островерха":"adjective","петрина":"noun","прудка":"adjective","семенина":"noun","турчина":"noun","чуприна":"noun","швидка":"adjective","щербина":"noun","яковина":"noun","синьоока":"adjective","крива":"adjective","сліпа":"adjective","глуха":"adjective","жовта":"adjective","добра":"adjective","хоробра":"adjective","сухоребра":"adjective","гарна":"adjective","мала":"adjective","весна":"noun","зла":"adjective","жива":"adjective","ніяка":"adjective","ціла":"adjective","молода":"adjective","далека":"adjective","золота":"adjective","жвава":"adjective","дорога":"adjective","коса":"adjective","литва":"noun","чужа":"adjective","тепла":"adjective","груба":"adjective","слава":"noun","брова":"noun","стара":"adjective","катерина":"noun","василина":"noun","нижня":"adjective","худа":"adjective","проста":"adjective","дівоча":"adjective","крута":"adjective","метка":"adjective","чорна":"adjective","сторона":"noun","невкрита":"adjective","руда":"adjective","темна":"adjective","проява":"noun","тиха":"adjective","божа":"adjective","весела":"adjective","бабина":"adjective","суха":"adjective","люта":"adjective","стіна":"noun","вража":"adjective","хороша":"adjective","легка":"adjective","козача":"adjective","польща":"noun","недужа":"adjective","розлога":"adjective","гаряча":"adjective","середня":"adjective","торішня":"adjective","сита":"adjective","гостра":"adjective","осіння":"adjective","невесела":"adjective","москва":"noun","широка":"adjective","половина":"noun","синя":"adjective","сира":"adjective","довга":"adjective","коротка":"adjective","лукава":"adjective","абияка":"adjective","королева":"noun","чайна":"adjective","сіра":"adjective","сутула":"adjective","сава":"noun","дебела":"adjective","мокра":"adjective","убога":"adjective","безрука":"adjective","димна":"adjective","мила":"adjective","боса":"adjective","гола":"adjective","красноока":"adjective","остання":"adjective","десна":"noun","житня":"adjective","тризна":"noun","цупка":"adjective","порожня":"adjective","ліва":"adjective","сьома":"adjective","вовна":"noun","сова":"noun","бела":"adjective","ряба":"adjective","гніда":"adjective","гожа":"adjective","кисла":"adjective","кутня":"adjective","огниста":"adjective","мудра":"adjective","дужа":"adjective","підстава":"noun","бодра":"adjective","бадьора":"adjective","кривохижа":"adjective","прихожа":"adjective","побожа":"adjective","пригожа":"adjective","петрунька":"noun","ковинька":"noun","кишинька":"noun","кропивянька":"noun","зеленька":"noun","лабунька":"noun","м'якенька":"adjective","бухонька":"noun","сиза":"adjective","маза":"adjective","блаза":"adjective","улина":"adjective","ейвена":"adjective","еремина":"adjective","ена":"adjective","клята":"adjective","периста":"adjective","працевита":"adjective","свіжа":"adjective","рижа":"adjective","копистира":"noun","скорина":"noun","більченя":"noun","кривошеня":"noun","нестереня":"noun","захарченя":"noun","войценя":"noun","протасеня":"noun","олещеня":"noun","денисеня":"noun","стрельченя":"noun","молодоженя":"noun","заграва":"noun","неменша":"adjective","неменьша":"adjective","меньша":"adjective","паший":"noun","пєша":"adjective","дзвінка":"adjective","пухка":"adjective","безпала":"adjective","вобла":"adjective","горжа":"adjective","горіла":"adjective","китаста":"adjective","лиса":"adjective","осадча":"adjective","пелехата":"adjective","підпала":"adjective","ставнича":"adjective","чала":"adjective","чубата":"adjective","целомудра":"adjective","кара":"adjective","коцупатра":"adjective","немудра":"adjective","шара":"adjective","шингира":"adjective","передера":"adjective","далекора":"adjective","жара":"adjective","яра":"adjective","золотопера":"adjective","остра":"adjective","хитра":"adjective","прозора":"adjective","карчинска":"adjective","гнила":"adjective","хижа":"adjective","крижа":"adjective","погоріла":"adjective","куца":"adjective","солодка":"adjective","безверха":"adjective","усата":"adjective","довгопола":"adjective","щербата":"adjective","пишна":"adjective","хоружа":"adjective","мирна":"adjective","долга":"adjective","бєла":"adjective","надточа":"adjective","гаркава":"adjective","мягка":"adjective","топча":"adjective","товста":"adjective","блага":"adjective","захожа":"adjective","боліла":"adjective","басиста":"adjective","басіста":"adjective","люба":"adjective","горбата":"adjective","драна":"adjective","куряча":"adjective","куса":"adjective","зайва":"adjective","кругла":"adjective","брижата":"adjective","скора":"adjective","плоха":"adjective","горяча":"adjective","тверда":"adjective","невідома":"adjective","картава":"adjective","горна":"adjective","черна":"adjective","гуржа":"adjective","гикава":"adjective","шита":"adjective","сєра":"adjective","сіда":"adjective","гнуча":"adjective","слизька":"adjective","бистра":"adjective","полева":"adjective","парубоча":"adjective","вібла":"adjective","мазна":"adjective","волохата":"adjective","шалена":"adjective","щира":"adjective","слаба":"adjective","суковата":"adjective","нища":"adjective","одинока":"adjective","сядриста":"adjective","яшна":"adjective","ракоча":"adjective","губата":"adjective","летуча":"adjective","патлата":"adjective","вяла":"adjective","гірна":"adjective","кіптіла":"adjective","кривовяза":"adjective","лиха":"adjective","подуфала":"adjective","буйна":"adjective","зайшла":"adjective","купрата":"adjective","мерзла":"adjective","варгата":"adjective","горда":"adjective","драпата":"adjective","загризла":"adjective","кичата":"adjective","оковита":"adjective","тлуста":"adjective","тонка":"adjective","коптіла":"adjective","погожа":"adjective","товстокора":"adjective","гладенька":"adjective","глубока":"adjective","періста":"adjective","виконавча":"adjective","кохана":"adjective","кризька":"adjective","німа":"adjective","росла":"adjective","некипіла":"adjective","плакуща":"adjective","похила":"adjective","строга":"adjective","богата":"adjective","заливча":"adjective","крамна":"adjective","поставнича":"adjective","безуса":"adjective","плоска":"adjective","сергата":"adjective","сухотепла":"adjective","толста":"adjective","шарпата":"adjective","безребра":"adjective","душна":"adjective","змерзла":"adjective","золотоверха":"adjective","наточа":"adjective","положа":"adjective","рокоча":"adjective","горлата":"adjective","скупа":"adjective","бібла":"adjective","ільніцка":"adjective","рогоча":"adjective","сміла":"adjective","щедра":"adjective","безклуба":"adjective","білоока":"adjective","шерстка":"adjective","безкишка":"adjective","летюча":"adjective","ловча":"adjective","піша":"adjective","раба":"adjective","суховерха":"adjective","тягла":"adjective","шаблиста":"adjective","шубала":"adjective","бедрата":"adjective","верлата":"adjective","галича":"adjective","запухла":"adjective","зубата":"adjective","кунта":"adjective","некрита":"adjective","пахуча":"adjective","теляча":"adjective","шпарка":"adjective","глива":"adjective","косата":"adjective","любима":"adjective","низька":"adjective","окрепка":"adjective","робоча":"adjective","слизькоуха":"adjective","хропата":"adjective","цівата":"adjective","шията":"adjective","безборода":"adjective","голоборода":"adjective","голомоза":"adjective","горєла":"adjective","єжела":"adjective","калиста":"adjective","корчиста":"adjective","курна":"adjective","надута":"adjective","пікуща":"adjective","погорела":"adjective","савіцка":"adjective","тупа":"adjective","дзяна":"adjective","жовкла":"adjective","колюча":"adjective","мазана":"adjective","сапата":"adjective","світа":"adjective","сухолитка":"adjective","цаберяба":"adjective","цвіла":"adjective","чупла":"adjective","асадча":"adjective","гарагата":"adjective","дзюбата":"adjective","долгопола":"adjective","жилава":"adjective","козина":"adjective","крепка":"adjective","ласа":"adjective","личката":"adjective","лобата":"adjective","льогка":"adjective","мишаста":"adjective","невмита":"adjective","перката":"adjective","рідка":"adjective","саплива":"adjective","тонкошкура":"adjective","цепла":"adjective","беззуба":"adjective","бушна":"adjective","бяла":"adjective","кріпка":"adjective","лакома":"adjective","майна":"adjective","нагла":"adjective","огніста":"adjective","осядла":"adjective","рабоча":"adjective","рапава":"adjective","розмаїта":"adjective","тупча":"adjective","ушата":"adjective","чорноока":"adjective","галянта":"adjective","голомовза":"adjective","одажа":"adjective","орлата":"adjective","пашиста":"adjective","пробита":"adjective","сепіта":"adjective","слабка":"adjective","цікава":"adjective","шамка":"adjective","шибиста":"adjective","баліцка":"adjective","бита":"adjective","боляча":"adjective","глабчаста":"adjective","гусліста":"adjective","деньдобра":"adjective","замліла":"adjective","лабата":"adjective","мяка":"adjective","несміла":"adjective","нєма":"adjective","обща":"adjective","одайна":"adjective","оката":"adjective","остиста":"adjective","пахуща":"adjective","пстра":"adjective","сладка":"adjective","храпата":"adjective","чесніша":"adjective","чула":"adjective","бідноша":"adjective","довгорука":"adjective","довгоша":"adjective","іваніцка":"adjective","корната":"adjective","кулява":"adjective","літуча":"adjective","марна":"adjective","медзата":"adjective","обмокла":"adjective","піджара":"adjective","побоча":"adjective","сагата":"adjective","удала":"adjective","усяка":"adjective","байдужа":"adjective","бескорса":"adjective","гірка":"adjective","главата":"adjective","горча":"adjective","горька":"adjective","добровольска":"adjective","довгопта":"adjective","досужа":"adjective","драпята":"adjective","камяна":"adjective","каправа":"adjective","киричата":"adjective","колота":"adjective","комарніцка":"adjective","люзна":"adjective","молодша":"adjective","неумита":"adjective","пересідла":"adjective","підла":"adjective","пухла":"adjective","семяниста":"adjective","сіроока":"adjective","стряпча":"adjective","твереза":"adjective","цибульска":"adjective","чарна":"adjective","ярка":"adjective","безгуба":"adjective","білоборода":"adjective","болєла":"adjective","бровата":"adjective","гікава":"adjective","голобока":"adjective","драбата":"adjective","жарка":"adjective","каплата":"adjective","кісла":"adjective","ковалевска":"adjective","ковальска":"adjective","козловска":"adjective","крилата":"adjective","куцка":"adjective","малоока":"adjective","мгка":"adjective","немята":"adjective","непроста":"adjective","нехороша":"adjective","пелихата":"adjective","підласа":"adjective","подпала":"adjective","руцка":"adjective","семениста":"adjective","услиста":"adjective","шорстка":"adjective","хила":"adjective","буката":"adjective","васалата":"adjective","вибла":"adjective","видойна":"adjective","виловата":"adjective","гарча":"adjective","горела":"adjective","дута":"adjective","зибла":"adjective","індича":"adjective","кальноока":"adjective","карнауха":"adjective","кривобедра":"adjective","кричфалуша":"adjective","кубата":"adjective","кужда":"adjective","ломана":"adjective","мацевита":"adjective","івашина":"noun","солоха":"adjective","перерва":"noun","проскура":"adjective","бова":"noun","сметана":"noun","дуброва":"noun","проскурня":"noun","родіна":"noun","єна":"noun","солонина":"noun","ліщина":"noun","лугина":"adjective","сосна":"noun","гавва":"noun","ужва":"noun","кулина":"adjective","халява":"noun","холява":"noun","підкова":"noun","крайня":"adjective","хохотва":"noun","цибулька":"noun","нікульча":"noun","кравчина":"noun","лупина":"adjective","лихошва":"noun","думбрава":"noun","плахотня":"adjective","покутня":"adjective","пона":"noun","семена":"noun","грона":"noun","єва":"noun","парасківа":"noun","шова":"noun","бурдужа":"adjective","козюберда":"adjective","говтва":"noun","приколота":"adjective","варнава":"noun","гурина":"adjective","рябокобила":"noun","кучина":"adjective","савва":"noun","кремена":"noun","малая":"adjective","горішня":"adjective","бурдюжа":"adjective","слаква":"noun","городня":"adjective","лиштва":"noun","цяцька":"noun","походня":"noun","недавня":"adjective","долішня":"adjective","марюхна":"noun","борона":"noun","колошва":"noun","семенча":"noun","затона":"noun","заплава":"noun","краснопера":"adjective","рибитва":"noun","сидора":"adjective","краплина":"noun","крутиголова":"noun","бакалина":"adjective","немна":"noun","очеретня":"adjective","пробийголова":"noun","мальона":"noun","сажина":"adjective","вчерашня":"adjective","бузина":"noun","забийворота":"noun","магльона":"noun","нейчева":"noun","потороча":"noun","ревіна":"noun","матьора":"adjective","святина":"noun","хіна":"noun","кожина":"adjective","наріжня":"noun","леона":"noun","передня":"adjective","савина":"adjective","сікачина":"noun","кльова":"noun","недолуга":"adjective","шкоропата":"noun","карасава":"noun","морева":"adjective","мустафіна":"noun","цьова":"noun","бубна":"noun","катона":"noun","міна":"noun","похвала":"noun","слоква":"noun","статіва":"noun","строна":"noun","вова":"noun","карева":"adjective","місюна":"noun","швая":"noun","бальва":"noun","вершина":"noun","врона":"noun","білокобила":"noun","гордина":"noun","кольва":"noun","льова":"noun","перекліта":"noun","основа":"noun","харена":"noun","борозна":"noun","будаква":"noun","каранікола":"noun","палесіка":"noun","рожина":"noun","штана":"noun","вицина":"noun","дубна":"noun","жовна":"noun","зіва":"noun","катарина":"noun","похмура":"adjective","фесина":"noun","шемена":"noun","галутва":"noun","зарева":"noun","ковальва":"noun","мирона":"noun","новосела":"noun","пачина":"adjective","совва":"noun","гіна":"noun","корона":"noun","новоженя":"noun","підберезня":"adjective","ряднина":"noun","сакська":"noun","канна":"noun","лукачина":"noun","плачінта":"noun","редьква":"noun","софина":"adjective","шатня":"adjective","блозва":"noun","вчорашня":"adjective","гриценя":"noun","куропатва":"noun","людва":"noun","стехна":"noun","парахоня":"noun","плєва":"noun","яворина":"noun","бендина":"noun","жовтонога":"adjective","конева":"adjective","мандалина":"noun","мацина":"noun","перезва":"noun","похвата":"noun","токмина":"noun","тюрина":"adjective","гицина":"noun","дзіна":"noun","куява":"noun","малонога":"adjective","стоколоса":"adjective","тимина":"adjective","біднина":"noun","вдовина":"adjective","лисохмара":"noun","микитина":"adjective","полівара":"noun","рибонька":"noun","ружина":"noun","тишина":"noun","цюрмаста":"noun","чалая":"adjective","васина":"noun","воїна":"noun","гулая":"noun","кова":"noun","она":"noun","палісіка":"noun","підошва":"noun","свидина":"noun","тирсина":"noun","хаврона":"noun","зона":"noun","кнзєва":"noun","розна":"adjective","ронжина":"noun","рудомина":"noun","сальва":"noun","скільсара":"noun","служала":"noun","фомина":"adjective","чупина":"adjective","шалупня":"noun","джупина":"noun","зоська":"noun","кузява":"noun","неледва":"noun","равва":"noun","разьва":"noun","шкорина":"noun","білозора":"adjective","бранціра":"noun","випна":"noun","галина":"adjective","мандаліна":"noun","мицька":"noun","мячина":"adjective","недосєка":"noun","пристая":"noun","м'яка":"adjective","вовчина":"noun","гринява":"noun","дівонька":"noun","ігіна":"noun","обійдихата":"noun","хижня":"adjective","челядина":"noun","янева":"adjective","голева":"adjective","дзюнька":"noun","дубрава":"noun","лигомина":"noun","мална":"noun","мархева":"noun","несправа":"noun","озява":"noun","панна":"noun","пупена":"noun","силява":"noun","сухокобила":"noun","цюрмоста":"noun","чевельча":"noun","чівільча":"noun","башева":"noun","бражна":"noun","варавва":"noun","волна":"noun","гольча":"noun","густа":"adjective","достатня":"adjective","зуграва":"noun","карапулька":"noun","кірна":"adjective","крапіва":"noun","луковина":"noun","магдалина":"adjective","мамона":"noun","мелещеня":"noun","мряна":"noun","параскева":"noun","похідня":"noun","пріхна":"noun","свтина":"noun","сьоська":"noun","терепіща":"noun","ціцяла":"noun","бодаква":"noun","гальвіта":"noun","деревенча":"noun","дона":"noun","дубена":"noun","задависвічка":"noun","йовва":"noun","капаціла":"noun","котельва":"noun","лісота":"noun","малюська":"noun","підсадня":"adjective","рєва":"noun","сувора":"adjective","хаджава":"noun","хомина":"adjective","шалева":"adjective","пір'їна":"noun","псина":"noun","бобина":"noun","болотня":"adjective","бруква":"noun","кіона":"noun","ковбінька":"noun","кривонога":"adjective","лєва":"noun","мухина":"adjective","нефортуна":"noun","органіста":"noun","пасулька":"noun","планіда":"adjective","пристава":"noun","салайда":"adjective","бачина":"noun","безкорса":"adjective","бєлокобила":"noun","борзина":"noun","бружина":"noun","воротня":"adjective","гальона":"noun","голтва":"noun","горемульта":"noun","дацина":"noun","забанджала":"noun","злая":"adjective","кікена":"noun","козачухна":"noun","коропатва":"noun","кузина":"adjective","лапунька":"noun","літава":"noun","мінчуна":"noun","на":"noun","ничая":"noun","новіцка":"adjective","пенькна":"noun","пухна":"noun","пуцята":"noun","рісна":"noun","розмаіта":"noun","румина":"adjective","свтна":"noun","сердита":"adjective","січінава":"noun","сментина":"noun","трізна":"noun","хоботня":"adjective","шкуропата":"noun","безхутра":"adjective","білява":"noun","гальва":"noun","гевела":"adjective","гирява":"noun","гнєда":"adjective","гребенча":"noun","гусонька":"noun","калабанька":"noun","козупляка":"noun","лапина":"adjective","мурина":"adjective","некульча":"noun","орона":"noun","парна":"adjective","пліва":"noun","приходька":"noun","сенина":"noun","солотва":"noun","тетева":"adjective","хавана":"noun","хилобока":"adjective","царева":"adjective","ахалая":"noun","варенька":"noun","варшава":"noun","вересоча":"noun","галунька":"noun","гліва":"noun","голина":"adjective","грузька":"adjective","гудина":"noun","євона":"noun","кірева":"adjective","кожем'яка":"noun","колоберда":"adjective","курінька":"noun","маржина":"noun","мигалина":"noun","мікава":"adjective","падва":"noun","паланичка":"adjective","палена":"adjective","подкова":"noun","ратушня":"adjective","селегейна":"noun","сминтина":"noun","сумина":"adjective","теміркая":"noun","ухата":"adjective","хавроня":"noun","холоста":"adjective","ціва":"noun","чернята":"noun","чикольва":"noun","шалина":"adjective","юдина":"adjective","адвена":"noun","балева":"adjective","брона":"noun","вербовата":"adjective","веремєва":"noun","волчаста":"adjective","гафина":"adjective","голутва":"noun","дацева":"noun","дерена":"adjective","закрева":"noun","каджая":"noun","кальченя":"noun","капаниста":"adjective","кикина":"adjective","костерева":"noun","кривокобила":"noun","кулєва":"noun","лавна":"noun","маліцка":"adjective","молдова":"noun","моркова":"noun","пажина":"adjective","перевернихата":"noun","пилева":"adjective","піддубня":"adjective","постіва":"noun","пуста":"adjective","суботня":"adjective","фадеева":"adjective","ходаніцка":"adjective","хохітва":"noun","цибата":"adjective","черноока":"adjective","чкадуа":"noun","чокена":"noun","шепетина":"noun","шербина":"noun","яка":"adjective","ятва":"noun","безена":"noun","безшкура":"adjective","безязика":"adjective","белая":"adjective","берулава":"noun","бузна":"noun","бурсала":"noun","бучаста":"adjective","вчина":"noun","гапона":"noun","гернажа":"noun","гордуна":"noun","горсва":"noun","горясва":"noun","грицька":"noun","двіжона":"noun","задурня":"adjective","заслона":"noun","зачешигрива":"noun","йона":"noun","качна":"adjective","козовіта":"noun","криворота":"adjective","кур'ята":"noun","лозна":"adjective","люлява":"noun","лютая":"adjective","матухна":"noun","накутня":"adjective","плохая":"adjective","бухая":"adjective","самотня":"adjective"};class Fm{encode(e){const t=new Uint8Array(1);switch(e.wordClass){case r.NOUN:t[0]=1;break;case r.ADJECTIVE:t[0]=0;break;default:throw new TypeError(`Invalid word class: "${e.wordClass}".`)}return t}decode(e){if(e.length<1||e.length>1)throw new RangeError("Invalid vector length.");const t=e[0];if(t<0||t>1)throw new RangeError("Invalid vector value.");return{wordClass:t>=.5?r.NOUN:r.ADJECTIVE}}}class _m{constructor(e,t=0){this.vectorSize=e,this.unknownCharcode=t}encode(e){var t;const n=new Uint8Array(this.vectorSize),i=e.slice(-this.vectorSize).toLowerCase().padStart(this.vectorSize,"-");for(let e=0;e<i.length;e+=1){const a=i[e];n[e]=null!==(t=s[a])&&void 0!==t?t:this.unknownCharcode}return n}}Q().set("IS_NODE",!1);var Rm={class_name:"Sequential",config:{name:"sequential_1",layers:[{class_name:"Embedding",config:{input_dim:34,output_dim:16,embeddings_initializer:{class_name:"RandomUniform",config:{minval:-.05,maxval:.05,seed:null}},embeddings_regularizer:null,activity_regularizer:null,embeddings_constraint:null,mask_zero:null,input_length:null,name:"embedding_Embedding1",trainable:!0,batch_input_shape:[null,null]}},{class_name:"SimpleRNN",config:{name:"simple_rnn_SimpleRNN1",trainable:!0,units:16,activation:"relu",use_bias:!0,kernel_initializer:{class_name:"VarianceScaling",config:{scale:1,mode:"fan_avg",distribution:"normal",seed:null}},recurrent_initializer:{class_name:"Orthogonal",config:{gain:1,seed:null}},bias_initializer:{class_name:"Zeros",config:{}},kernel_regularizer:null,recurrent_regularizer:null,bias_regularizer:null,activity_regularizer:null,kernel_constraint:null,recurrent_constraint:null,bias_constraint:null,dropout:0,recurrent_dropout:0,return_sequences:!1,return_state:!1,go_backwards:!1,stateful:!1,unroll:!1}},{class_name:"Dense",config:{units:1,activation:"sigmoid",use_bias:!0,kernel_initializer:{class_name:"VarianceScaling",config:{scale:1,mode:"fan_avg",distribution:"normal",seed:null}},bias_initializer:{class_name:"Zeros",config:{}},kernel_regularizer:null,bias_regularizer:null,activity_regularizer:null,kernel_constraint:null,bias_constraint:null,name:"dense_Dense1",trainable:!0}}]},keras_version:"tfjs-layers 4.2.0",backend:"tensor_flow.js"},Lm=[{name:"embedding_Embedding1/embeddings",shape:[34,16],dtype:"float32"},{name:"simple_rnn_SimpleRNN1/kernel",shape:[16,16],dtype:"float32"},{name:"simple_rnn_SimpleRNN1/recurrent_kernel",shape:[16,16],dtype:"float32"},{name:"simple_rnn_SimpleRNN1/bias",shape:[16],dtype:"float32"},{name:"dense_Dense1/kernel",shape:[16,1],dtype:"float32"},{name:"dense_Dense1/bias",shape:[1],dtype:"float32"}],Mm="D3HrvZUs7rxT6Vu+tVsfvPLyB70zbt695ECPvKyKWj7TnUO+JZ9pvs8MkL3/1DQ+kftzvPGZZL4aDpe8KiOnvSvRHz52vQK9mGiSPm50B72RCfM+7hW6PSOuTz7b9zG+M5MOPv/mYL7Q9Rk+aPgRvrfQuT6mQ2Q+eOawPp/PpLyM9yY+zB4APT27n75OVUk+V8y6vetFyD0zPlW+sqPfPER8Ub6J1pI+5QwEvcZktT12HLW+FSFGPU6s2ryQapW9/MNNvoK1t71R5sK8N6Y/vjqBzTtusl2+0Ks8PpZOQ74ua5U9TOIfvkpgHDxho/294hcTPkJaiL1iXTo9o28bPhnMBr69EoG8CAeCvtgxXT5kMKq+KnLfPbScM73jYjw+LTa8vSeQWj49+cU7/FH2PKtOwr5y8K29GMMdvrkIgb0wK4C8Zeq2vXlG+L15O4c+CaFGvpmCjD5guBg+0AAQPv0EjT3CdZ0+vLOBulXEAb7VVpi+WldAPpIP8T0ETFm+NcLIPZix17rKGEW+n8jxPfT8hr43TLC8esPRvX6k4D1lZ0C+WERdPo4Qab4SdWw+uWSevp7+zTjX5Xi8nw+ZvldSb7xUfke7HX01PVOV2zzFqV2+SqcNvvPUTz0nzZi9Zl+ePWj6Wr3PLjY+vbjrvSRr6b1es/w8oaLjPUC0G72spye9rsomPtW/t72QYEy9AtR6PuX44z1dLrk9k6HAPE1+Eb7w1mY+N8MSvuMLsj1qmsO6JrRAvsJowr7iA1E+udZGPDLR57xRSj8+GFSnvYNUujxIvpM8FHmHvkr8QD38Po29LslnvShYOD45FAE7vfaWPbnegruqB2W9MdUkPpskUb3YGTU+L3gwvQhAYD4ed66+qJQUvjydBr7bSam8fYz/PCTisD7GYoQ+HDxJvSaIR77s3u+8sVTkvaDBaL13FBs+Z8T4vT4aKj2d4DC7ft+GPvVXFLxGXGI9RJ9avl7RCD6ujIy+M+/zPQbAtr3B2+c9BpZcPYIBTj7QNsM95bqEPc221T3u7TO+M2PIPU/BQb78/nk+f4TmvV5Elj0VOAK+0Y+DPq0GkL364pI98CGUvjK4IL1CLoK+kohXvTS3I76BpcM9WE0Rva5vkz301Ui+CLe7vWkLnT1sjpM8EYyWPWblIryk+gI+gnQSvu9XKL7jtni9Rc/IvaonHj2sKBc+VzRovpdOpT64szY+OavnvfzjeLuBH62+OqC2OoeMBr0eJVi7ST7CPLK/3jxTOoC9BRUSPjNBaD6OIlm+7ApUPlbsWj5KIKi+J9F1Pfi88L1+JdA9a6F+PsiRub06rh2+HlXnPb5Wj774l+i6nifjvWMCtL2WnqW9pUNdvjQM4L0ZJDy9lZ+LPbJWhj2hUZO+iWF0vhq17zqKwOI9Qq6sPWo8gD3c0co9/5WaPLN6PL6HOLO8fXvUvEF2IL4QJ7S98UzCPZJTlb6VUCM+y7dqvkJXyTyxD+I9N6PXvUxuqr0jiuM9p1OgO/wUFL07zEy+n5rPvSLifbt4N5e+kbdRviF6Db0ZSjo+B+dXvqB+iT7nFI68Z9bUPU9FGT21fz4+fee2vaIHqLzRTtG8aGggPqQlpD1GORk9/FpnPjatAL60OPg8x+qAPdU74zxSk6+9lYwdPikogr6pxao99PmXvH+yEz4zu5U9IeURPXqY9LpuvYk8OGmYvFX7+TtuUaO9qg0GPph0Xr5vdYM+0deHvozgtryfgDC8DaCGPTVxHb6q0fI97pWqPOXMAj7Y9ae+fljRuoumt71vblO+UaetPcadt7yiUYi9R9x8PqXbmb4V9gK+v2jjvVsTU72VAJ29JC1vPcpy1D2uNZM9N5mlvru77rxAZSo9jZWkvv+0HD6CY6k9RvnyvLM8Wr4/Yjo+aEr4vcUQkj3Ef7+7DusLvhf0oLxUt1u+LdOWPndY+Ty5+Dq+QfqQvqgCbj7V0L68swkNviGjaz0SkyQ+h9uuvckW97rM35m+O7ERPQvQ4L2XN3a9XwqPPifY7TynN0i9enwJPWh2Tj27c02+k0bpPWtEGz4p+qs9DzsKPhlEoD7U1qM9v7SAvNgeIr7tPJM9om6CvhmNcz7pBIa9HEvlPRmEGj7SzgE9tdoAO8dkeT2N2Xm9ChofvhVPSj19rZG+A2PfPVrax72zacc9YWsTvjSKAj4inbu9GbJGvSEnt76qFeq8JsAnvZ0cO75Lk7e5G8+WPrc5Cb3RGVg+xwxfvgTMNr18pdU9U49jPaRh5rg8G2Q+iUtrObd+jT0FTYG+XgVgvKwXJr6TWuG9BWosPlr9pT6IF2G+boCIvU0FOb39ivu9aMA5viC1S714C3q+CES6Pt11j76mNqk+/btevCcEVL7z5cK+ALgyPJeTPb0+7O+7lftrPslPZz1EqIY9DWKYvdtgWL5/DwI9Q2NFvJhKcb0MMQo+NtltPWZcmT2FlVA9V5Nnvc9IJr0TXCA+nAIuPoF7xbon0SQ+Kwi8ve0ePb6O3++9k2/GvZoLlrxRDM48DwOkvEiWIz7jsgC+NYZzvTu7Jb7Jcgm8qAoyPg8zkT3o8UI+7Mt/vZsaYj7UZDm+Z4BTPBgkQr7CSTs+PKpvPbkSED3tAaW9LJ9APo74Fz62CFe8xMDCPi83F76ttk++K6FGvQkDDr42fbG+N9cbPvP1Br2CU1c+qukfvu3DJz6Vjfy8jlM9PZNaKL4Ceu29dDVCvoG7fD5qTLu75+YoPXt8GD7ey2U+KpynvemmCL1L1VC9LsfhvcoBND44he273UFiPrLzK72XXPS9ZjZGPtBwh7gwW2i+ccbxvXtoMj4Q/u49AzHBvoTjHD40AuW+OiwYP4x9JD6PGAY/KN7+Pc0xhb6OqxY9AptQvbc7Or39a9e6DJ/zPvd+iz6XX7g6kqsEP5LI1L7ICBk+1k5SP0lR0T43qYI+kbFLvcUh5L7+v90+5mnZveLTxj03yAS+phJLvW7x3b4m3J68GeeBvlrhgj05ac++0Yyfvcrz7L1/Y/i+ZjMKPhEy6j3ImRu+fRRuPkunGL5dMVG+Yd5Fv6ys1z6PXYI+JhzOvaGxDT4p38I+QcDHPtkxbb0XnjM/ogGYviZrLj291se+iNNqvpZuUb7nas8+lj4tvvyQ3D7w+FO9r4ybPs7MJD+WsIG9pGxHPqmQo75RdUG/gFs2vRXbrj7n87w9aGosPm8vDr/oUeO+2pWxPsk1RT7lvPS+YBmZvkDPU745ORi/BxbNPg83pD2KOSq9Nh0tPw6bSj+WVTk97hLcPnMDpT7GgXW8dL46vltPvb11QOu9CeYDPYDxwbx5UQ8+MnesPb+Ajj7Uv7m+qE+TvM+Qt77g88s+7940P8/1zj5p9+g+FugoPgNebT69zXg+IbhFvnHq6LsVozg+iIaBPau6Kr6tTOG+U1bhPS6zFD64rqY/FZebvhOPeL5DGXo+dwgLPjKu6z5+X78+iAsNPrs/Pb+RQoe+6MyqvWutu75ml7G+3Casvq63/b4exKi9+5lMv7V/yb4twI49cbIcv/+5/r5lWxE/78Q+PhjngT4SENI9xZKXPmmQEb9UJGK+eYE3vtOLiDxf4zo+9KX5Pl0APj9PhqA+i/wMv1iRsjzngaK+/ocBv8RUnr0hPdM+YAshv896DL1aukY+kiIJvsKhvD66FTi++84Fv5vWjL4lr6W+OLvyvba/krzwXgm9X8rUvv+XNb7jhSo/zfCAPLRlqD4Fn5S+DeQfP0847T7NIZ4+/gMAPxyfcT6VQOM+UOmWvWDtrD4TLFW9NGQSveJN9T7AuFm+MvUSv/TnFz8uw68+k05IPj26MTwDLsW+hsLFvifDqD7Z6d28z+AOv1DeZL8TnA++mrwBvT0BGL5ireW+PLbOOQjsJjzUmya/CcavOz8kwr70lmK+PHcmPsmi9r5VeAI+yly7PSGkIT6xV1Q/uHsKP4WFir4DBcc+SIJuPlP0Lb5Nufu+dKc3vk/X4L2Qvyo/jJSCPr3+Vr7NNA4/5AqcPoYisjuvO6g9JGKRPgxvQj/bUnG8yqAbP8wDO75rdkO+keIuPvrKxT4VCoQ9fx3XPih9K77kIOg99g2gPcrn4rxDzyy+TDdxPpzmHz//YWM+PIXFvTGs4z5SaaE9NAwkv4Qcub6gS3g+6Wa0vf3qJD8NDC2/q4z6PFVEob5p8yG+uSjhvjAMgD4GQ2Q/+EfRPlrsL79K2PO+FyOrPav1lT6vSzQ+nQOovRiVMD4Yfg4+weDxPv9V8b3ix407T0mFvEXdYT4DaKq+rE4YviLa2r4q/vI7hVWOvWgaV77A7QU/OU2iPp8QQT58RIA+Lbf+vo65Fz1RDRw+mv6WvdOImj4/IyY9a+vPO/pDuj6WiFe94SnbvW0cAb5HUcQ8croTvdeGIT6Q5p89/2EpPyPapj33gSS+q161vhFrSj00b5A9P6g4vssdob5sS5G+r72gvUDqCj+C5+a9lJHFPjtFxz10OYs+qXakvlUu5Trwp749nrcQPbAzwr5pCs8+UhoIvsHVdT7iw+i+UYxzPgTn5T50arg+R/4IP7kH2T2cguW+pQX+vFqQdr3z5yY+SdURProPID4CXhA9crIcP/7a4D6r/549Ly6lvXeFUb9n9xs/CC3oPrOgAj8iPwo/8nPXviKqAr8q6TQ+vrumPrdtHz8prJq+V1/oPUZWGr4Y4cU9nRopvtRCkz2jeTy+pJW0PgwDyz6XfIo+QmZevqCRSj1/pIa+KoufPllZvT5o244+nRIYP3TbM70N+8y+a7d2vcsSWj4Cdrw+AT8hPVoDwL0BxL2+G1pmPo/CZL66zSS+g2rFPvewar7nfGe+YEuevRgFIr7dyRS+KES0Pnu1p754F6s+/inJPXa3tL4Qd5A+OmbLPWvlnb75WsU9rRHMvsgqxD5MQ90+Y38LPnBkZj7fKIs9uJCHvdiuXr6D/Rw9hpVyPu9Vqr4Qzom85dP6vYymmr1yG5w+2gSMPlV5tT1D1ks+EKTZPm4gOb6ZC+w+k8EOPA8oXb6r9z2+h6Tgvm7Dvj7OzJQ+7tkIPvbDjz4TN6u9GneSPTIooD7GdRA/wYQ4vVr7b71F/QI+cRORPrRPWzxVX22+Yu2vPsHriL720za+oBlVPogMe72YNKM8r9aEO5uq1z7RegW+4aX1PqfYRD/wpfI9sVqvPCI99jpAtWC9eXJ2PBb++j6w+809iODsPfwV0b2kL7S9D+FLPQZECD4oYRA+V1Z+vjarEj5ZF/q8KJSAPkjENr7zNd28pKODPj8FPL8mgFY8kJVMvgBfQ75uooK++9TaPg/5Cr5Pzo6+1Yy3viONQL/Fvng+Bmn6vTpQkb0N7Oi94ZVHPYE2Hr7J/Rk+zQzKvL3Chj5d85o+Q/YRPrsjnj7YzJY+01w3PyVgGD6INkM+XtnevbmxiL7Z1NI+jpdgvggkdz0QnJq+35a8PZX0SL4+y78+grnOPYHzlD2VKRA/xRW4PqyCPL4Cowa/Ku+pvZabKz99894+sY/Vva/ezL1zsUw+er4IP8DL/D1qa2a+m6B3PK8Cq76mu2++gsjvvP0kBz8pWqe+SyotvKUdmz4pFXA7bkXCvbwSbj44g7c8mID4viXITL56E/G9zBVuPPD+u7wCmJc9v1nDuyyEX77G7Nq8GUwXvQJRVT3nTYY9/wK9Pct9sT1dCqU9aRsHvlmTFD2/B5M9PclmvNt2Jb8eqR2+bZhIvlmRVT4k0zU/OFSyvnCsHb/BfrK+ZZJGv10pNT8uXQk/AaVXvgbtG76M5kC+b6zpPfBICD8I1Lm8",Om={format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v4.2.0",convertedBy:null};const Pm="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);class Bm{inflect(e,t,n){return a(this,void 0,void 0,(function*(){const i=[],a=e.split("-");for(let e=0;e<a.length;e+=1){const s=yield this.inflectNamePart(a[e],t,n,e===a.length-1);i.push(s)}return i.join("-")}))}}const Um=/[ая]$/i,Wm=/(ой|ий|ій|их)$/i;const Gm=new class extends Bm{constructor(e){super(),this.wordInflector=e}inflectNamePart(e,t,n){return this.wordInflector.inflect(e,{grammaticalCase:n,gender:t,application:"givenName"})}}(b),Vm=new class extends Bm{constructor(e){super(),this.wordInflector=e}inflectNamePart(e,t,n){return this.wordInflector.inflect(e,{grammaticalCase:n,gender:t,application:"patronymicName",customRuleFilter:e=>e.application.includes("patronymicName")})}}(b),Km=new class{constructor(e){this.modelLoader=e,this.modelPromise=null,this.wordTransformer=new _m(20),this.familyNameClassTransformer=new Fm}classify(e){return a(this,void 0,void 0,(function*(){let t=this.getCached(e);if(null!=t)return t;const n=yield this.loadModel(),i=this.wordTransformer.encode(e),a=yield n.predict(Ks([i])).data();return t=this.familyNameClassTransformer.decode(a),t}))}getCached(e){let t=null;const n=Dm[e.toLowerCase()];return n&&(t={wordClass:n}),t}loadModel(){return a(this,void 0,void 0,(function*(){return null==this.modelPromise&&(this.modelPromise=kp(this.modelLoader)),this.modelPromise}))}}(new class{load(){return a(this,void 0,void 0,(function*(){const e={};if(e.modelTopology=Rm,e.weightSpecs=Lm,e.weightData=function(e){if(Pm){const t=Buffer.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n.set([t.charCodeAt(e)],e);return n.buffer}(Mm),null!=Om){const t=Om;e.format=t.format,e.generatedBy=t.generatedBy,e.convertedBy=t.convertedBy,null!=t.signature&&(e.signature=t.signature),null!=t.userDefinedMetadata&&(e.userDefinedMetadata=t.userDefinedMetadata),null!=t.modelInitializer&&(e.modelInitializer=t.modelInitializer),null!=t.initializerSignature&&(e.initializerSignature=t.initializerSignature),null!=t.trainingConfig&&(e.trainingConfig=t.trainingConfig)}return e}))}}),qm=new class extends Bm{constructor(e,t){super(),this.wordInflector=e,this.familyNameClassifier=t}inflectNamePart(e,t,n,i){return a(this,void 0,void 0,(function*(){if(!i&&l(e))return e;let a=null;return this.isUncertainFamilyNameClass(e,t)&&(a=yield this.familyNameClassifier.classify(e)),this.wordInflector.inflect(e,{grammaticalCase:n,gender:t,wordClass:null==a?void 0:a.wordClass,application:"familyName"})}))}isUncertainFamilyNameClass(t,n){return n===e.GrammaticalGender.FEMININE&&Um.test(t)||n===e.GrammaticalGender.MASCULINE&&Wm.test(t)}}(b,Km),Hm=new class{constructor(e,t,n){this.givenNameInflector=e,this.patronymicNameInflector=t,this.familyNameInflector=n}inflect(e,t,n){return a(this,void 0,void 0,(function*(){const i={};return null!=e.givenName&&(i.givenName=yield this.givenNameInflector.inflect(e.givenName,t,n)),null!=e.patronymicName&&(i.patronymicName=yield this.patronymicNameInflector.inflect(e.patronymicName,t,n)),null!=e.familyName&&(i.familyName=yield this.familyNameInflector.inflect(e.familyName,t,n)),i}))}}
|
|
4670
|
+
xt(Io),xt(lo),xt(Eo),xt(Ao),xt(Co),xt($o),xt(wo),xt(jo),xt(Mo),xt(vo),xt(_o),xt(xo),xt(ro);var Dm={"штих":"noun","пяних":"noun","белих":"adjective","борзих":"adjective","малих":"adjective","старих":"adjective","дарнопих":"noun","сухих":"adjective","черемних":"noun","сирих":"adjective","плохих":"adjective","целих":"adjective","жих":"noun","войцих":"noun","скорих":"adjective","бурих":"adjective","чалих":"adjective","серих":"adjective","удалих":"adjective","карих":"adjective","гених":"noun","литвих":"noun","марцих":"noun","сізих":"adjective","яних":"noun","мжачих":"adjective","сірих":"adjective","янбих":"noun","бодрих":"adjective","войтих":"adjective","стрий":"noun","чорторий":"noun","юрий":"adjective","цибрий":"noun","цібрий":"noun","карий":"adjective","куприй":"noun","кирий":"noun","негрий":"noun","губрий":"noun","шкабрий":"noun","замрий":"noun","передрий":"noun","одерий":"noun","жегрий":"noun","порий":"adjective","жарий":"adjective","зюбрий":"noun","семерий":"noun","лий":"noun","бий":"noun","рий":"noun","вий":"noun","ший":"noun","валий":"noun","крайній":"adjective","осінній":"adjective","кутній":"adjective","середній":"adjective","горішній":"adjective","безродній":"adjective","осадчій":"adjective","кий":"noun","новохатній":"adjective","очеретній":"adjective","рбий":"noun","закутній":"adjective","недавній":"adjective","порожній":"adjective","бокий":"noun","вчерашній":"adjective","огородній":"adjective","трощий":"noun","крічфалушій":"adjective","карагеоргій":"adjective","вчорашній":"adjective","житній":"adjective","нижній":"adjective","синій":"adjective","хорий":"noun","краснобокій":"adjective","хижній":"adjective","калюжній":"adjective","виноградній":"adjective","коломий":"noun","летучій":"adjective","поздній":"adjective","польчій":"adjective","серий":"noun","нагорній":"adjective","фартушній":"adjective","холошвій":"noun","батий":"noun","волошиній":"adjective","жирий":"noun","заможній":"adjective","короткій":"adjective","останній":"adjective","передній":"adjective","піддубній":"adjective","пізній":"adjective","погородній":"adjective","бояжній":"adjective","сивній":"adjective","смий":"noun","задвірній":"adjective","остатній":"adjective","підсадній":"adjective","достатній":"adjective","жамардій":"adjective","зимній":"adjective","рябой":"adjective","рудой":"adjective","козодой":"noun","яровой":"adjective","кривой":"adjective","садовой":"adjective","полевой":"adjective","сисой":"noun","плохой":"adjective","сухой":"adjective","гаєвой":"adjective","глухой":"adjective","горевой":"adjective","іоніцой":"noun","кутовой":"adjective","копаной":"adjective","злой":"adjective","сєдой":"adjective","благой":"adjective","водостой":"noun","косой":"adjective","ліждвой":"noun","большой":"adjective","кальной":"noun","половой":"adjective","чорной":"adjective","косогой":"adjective","золотой":"adjective","лановой":"adjective","яловой":"adjective","дорогой":"adjective","німой":"adjective","первой":"adjective","русой":"adjective","худой":"adjective","цаподой":"noun","авасілой":"noun","валовой":"adjective","гнідой":"adjective","молокопой":"noun","золотобой":"noun","ярковой":"noun","аміхалакіой":"noun","седой":"adjective","крутой":"adjective","кучной":"adjective","слепой":"adjective","дурной":"adjective","молодой":"adjective","бухой":"adjective","самотній":"adjective","біла":"adjective","бура":"adjective","велика":"adjective","домовина":"noun","рослина":"noun","врецьона":"noun","глибока":"adjective","висока":"adjective","гладка":"adjective","грицина":"noun","гужва":"noun","ковінька":"noun","дика":"adjective","діброва":"noun","кицька":"noun","ківа":"noun","лепка":"adjective","островерха":"adjective","петрина":"noun","прудка":"adjective","семенина":"noun","турчина":"noun","чуприна":"noun","швидка":"adjective","щербина":"noun","яковина":"noun","синьоока":"adjective","крива":"adjective","сліпа":"adjective","глуха":"adjective","жовта":"adjective","добра":"adjective","хоробра":"adjective","сухоребра":"adjective","гарна":"adjective","мала":"adjective","весна":"noun","зла":"adjective","жива":"adjective","ніяка":"adjective","ціла":"adjective","молода":"adjective","далека":"adjective","золота":"adjective","жвава":"adjective","дорога":"adjective","коса":"adjective","литва":"noun","чужа":"adjective","тепла":"adjective","груба":"adjective","слава":"noun","брова":"noun","стара":"adjective","катерина":"noun","василина":"noun","нижня":"adjective","худа":"adjective","проста":"adjective","дівоча":"adjective","крута":"adjective","метка":"adjective","чорна":"adjective","сторона":"noun","невкрита":"adjective","руда":"adjective","темна":"adjective","проява":"noun","тиха":"adjective","божа":"adjective","весела":"adjective","бабина":"adjective","суха":"adjective","люта":"adjective","стіна":"noun","вража":"adjective","хороша":"adjective","легка":"adjective","козача":"adjective","польща":"noun","недужа":"adjective","розлога":"adjective","гаряча":"adjective","середня":"adjective","торішня":"adjective","сита":"adjective","гостра":"adjective","осіння":"adjective","невесела":"adjective","москва":"noun","широка":"adjective","половина":"noun","синя":"adjective","сира":"adjective","довга":"adjective","коротка":"adjective","лукава":"adjective","абияка":"adjective","королева":"noun","чайна":"adjective","сіра":"adjective","сутула":"adjective","сава":"noun","дебела":"adjective","мокра":"adjective","убога":"adjective","безрука":"adjective","димна":"adjective","мила":"adjective","боса":"adjective","гола":"adjective","красноока":"adjective","остання":"adjective","десна":"noun","житня":"adjective","тризна":"noun","цупка":"adjective","порожня":"adjective","ліва":"adjective","сьома":"adjective","вовна":"noun","сова":"noun","бела":"adjective","ряба":"adjective","гніда":"adjective","гожа":"adjective","кисла":"adjective","кутня":"adjective","огниста":"adjective","мудра":"adjective","дужа":"adjective","підстава":"noun","бодра":"adjective","бадьора":"adjective","кривохижа":"adjective","прихожа":"adjective","побожа":"adjective","пригожа":"adjective","петрунька":"noun","ковинька":"noun","кишинька":"noun","кропивянька":"noun","зеленька":"noun","лабунька":"noun","м'якенька":"adjective","бухонька":"noun","сиза":"adjective","маза":"adjective","блаза":"adjective","улина":"adjective","ейвена":"adjective","еремина":"adjective","ена":"adjective","клята":"adjective","периста":"adjective","працевита":"adjective","свіжа":"adjective","рижа":"adjective","копистира":"noun","скорина":"noun","більченя":"noun","кривошеня":"noun","нестереня":"noun","захарченя":"noun","войценя":"noun","протасеня":"noun","олещеня":"noun","денисеня":"noun","стрельченя":"noun","молодоженя":"noun","заграва":"noun","неменша":"adjective","неменьша":"adjective","меньша":"adjective","паший":"noun","пєша":"adjective","дзвінка":"adjective","пухка":"adjective","безпала":"adjective","вобла":"adjective","горжа":"adjective","горіла":"adjective","китаста":"adjective","лиса":"adjective","осадча":"adjective","пелехата":"adjective","підпала":"adjective","ставнича":"adjective","чала":"adjective","чубата":"adjective","целомудра":"adjective","кара":"adjective","коцупатра":"adjective","немудра":"adjective","шара":"adjective","шингира":"adjective","передера":"adjective","далекора":"adjective","жара":"adjective","яра":"adjective","золотопера":"adjective","остра":"adjective","хитра":"adjective","прозора":"adjective","карчинска":"adjective","гнила":"adjective","хижа":"adjective","крижа":"adjective","погоріла":"adjective","куца":"adjective","солодка":"adjective","безверха":"adjective","усата":"adjective","довгопола":"adjective","щербата":"adjective","пишна":"adjective","хоружа":"adjective","мирна":"adjective","долга":"adjective","бєла":"adjective","надточа":"adjective","гаркава":"adjective","мягка":"adjective","топча":"adjective","товста":"adjective","блага":"adjective","захожа":"adjective","боліла":"adjective","басиста":"adjective","басіста":"adjective","люба":"adjective","горбата":"adjective","драна":"adjective","куряча":"adjective","куса":"adjective","зайва":"adjective","кругла":"adjective","брижата":"adjective","скора":"adjective","плоха":"adjective","горяча":"adjective","тверда":"adjective","невідома":"adjective","картава":"adjective","горна":"adjective","черна":"adjective","гуржа":"adjective","гикава":"adjective","шита":"adjective","сєра":"adjective","сіда":"adjective","гнуча":"adjective","слизька":"adjective","бистра":"adjective","полева":"adjective","парубоча":"adjective","вібла":"adjective","мазна":"adjective","волохата":"adjective","шалена":"adjective","щира":"adjective","слаба":"adjective","суковата":"adjective","нища":"adjective","одинока":"adjective","сядриста":"adjective","яшна":"adjective","ракоча":"adjective","губата":"adjective","летуча":"adjective","патлата":"adjective","вяла":"adjective","гірна":"adjective","кіптіла":"adjective","кривовяза":"adjective","лиха":"adjective","подуфала":"adjective","буйна":"adjective","зайшла":"adjective","купрата":"adjective","мерзла":"adjective","варгата":"adjective","горда":"adjective","драпата":"adjective","загризла":"adjective","кичата":"adjective","оковита":"adjective","тлуста":"adjective","тонка":"adjective","коптіла":"adjective","погожа":"adjective","товстокора":"adjective","гладенька":"adjective","глубока":"adjective","періста":"adjective","виконавча":"adjective","кохана":"adjective","кризька":"adjective","німа":"adjective","росла":"adjective","некипіла":"adjective","плакуща":"adjective","похила":"adjective","строга":"adjective","богата":"adjective","заливча":"adjective","крамна":"adjective","поставнича":"adjective","безуса":"adjective","плоска":"adjective","сергата":"adjective","сухотепла":"adjective","толста":"adjective","шарпата":"adjective","безребра":"adjective","душна":"adjective","змерзла":"adjective","золотоверха":"adjective","наточа":"adjective","положа":"adjective","рокоча":"adjective","горлата":"adjective","скупа":"adjective","бібла":"adjective","ільніцка":"adjective","рогоча":"adjective","сміла":"adjective","щедра":"adjective","безклуба":"adjective","білоока":"adjective","шерстка":"adjective","безкишка":"adjective","летюча":"adjective","ловча":"adjective","піша":"adjective","раба":"adjective","суховерха":"adjective","тягла":"adjective","шаблиста":"adjective","шубала":"adjective","бедрата":"adjective","верлата":"adjective","галича":"adjective","запухла":"adjective","зубата":"adjective","кунта":"adjective","некрита":"adjective","пахуча":"adjective","теляча":"adjective","шпарка":"adjective","глива":"adjective","косата":"adjective","любима":"adjective","низька":"adjective","окрепка":"adjective","робоча":"adjective","слизькоуха":"adjective","хропата":"adjective","цівата":"adjective","шията":"adjective","безборода":"adjective","голоборода":"adjective","голомоза":"adjective","горєла":"adjective","єжела":"adjective","калиста":"adjective","корчиста":"adjective","курна":"adjective","надута":"adjective","пікуща":"adjective","погорела":"adjective","савіцка":"adjective","тупа":"adjective","дзяна":"adjective","жовкла":"adjective","колюча":"adjective","мазана":"adjective","сапата":"adjective","світа":"adjective","сухолитка":"adjective","цаберяба":"adjective","цвіла":"adjective","чупла":"adjective","асадча":"adjective","гарагата":"adjective","дзюбата":"adjective","долгопола":"adjective","жилава":"adjective","козина":"adjective","крепка":"adjective","ласа":"adjective","личката":"adjective","лобата":"adjective","льогка":"adjective","мишаста":"adjective","невмита":"adjective","перката":"adjective","рідка":"adjective","саплива":"adjective","тонкошкура":"adjective","цепла":"adjective","беззуба":"adjective","бушна":"adjective","бяла":"adjective","кріпка":"adjective","лакома":"adjective","майна":"adjective","нагла":"adjective","огніста":"adjective","осядла":"adjective","рабоча":"adjective","рапава":"adjective","розмаїта":"adjective","тупча":"adjective","ушата":"adjective","чорноока":"adjective","галянта":"adjective","голомовза":"adjective","одажа":"adjective","орлата":"adjective","пашиста":"adjective","пробита":"adjective","сепіта":"adjective","слабка":"adjective","цікава":"adjective","шамка":"adjective","шибиста":"adjective","баліцка":"adjective","бита":"adjective","боляча":"adjective","глабчаста":"adjective","гусліста":"adjective","деньдобра":"adjective","замліла":"adjective","лабата":"adjective","мяка":"adjective","несміла":"adjective","нєма":"adjective","обща":"adjective","одайна":"adjective","оката":"adjective","остиста":"adjective","пахуща":"adjective","пстра":"adjective","сладка":"adjective","храпата":"adjective","чесніша":"adjective","чула":"adjective","бідноша":"adjective","довгорука":"adjective","довгоша":"adjective","іваніцка":"adjective","корната":"adjective","кулява":"adjective","літуча":"adjective","марна":"adjective","медзата":"adjective","обмокла":"adjective","піджара":"adjective","побоча":"adjective","сагата":"adjective","удала":"adjective","усяка":"adjective","байдужа":"adjective","бескорса":"adjective","гірка":"adjective","главата":"adjective","горча":"adjective","горька":"adjective","добровольска":"adjective","довгопта":"adjective","досужа":"adjective","драпята":"adjective","камяна":"adjective","каправа":"adjective","киричата":"adjective","колота":"adjective","комарніцка":"adjective","люзна":"adjective","молодша":"adjective","неумита":"adjective","пересідла":"adjective","підла":"adjective","пухла":"adjective","семяниста":"adjective","сіроока":"adjective","стряпча":"adjective","твереза":"adjective","цибульска":"adjective","чарна":"adjective","ярка":"adjective","безгуба":"adjective","білоборода":"adjective","болєла":"adjective","бровата":"adjective","гікава":"adjective","голобока":"adjective","драбата":"adjective","жарка":"adjective","каплата":"adjective","кісла":"adjective","ковалевска":"adjective","ковальска":"adjective","козловска":"adjective","крилата":"adjective","куцка":"adjective","малоока":"adjective","мгка":"adjective","немята":"adjective","непроста":"adjective","нехороша":"adjective","пелихата":"adjective","підласа":"adjective","подпала":"adjective","руцка":"adjective","семениста":"adjective","услиста":"adjective","шорстка":"adjective","хила":"adjective","буката":"adjective","васалата":"adjective","вибла":"adjective","видойна":"adjective","виловата":"adjective","гарча":"adjective","горела":"adjective","дута":"adjective","зибла":"adjective","індича":"adjective","кальноока":"adjective","карнауха":"adjective","кривобедра":"adjective","кричфалуша":"adjective","кубата":"adjective","кужда":"adjective","ломана":"adjective","мацевита":"adjective","івашина":"noun","солоха":"adjective","перерва":"noun","проскура":"adjective","бова":"noun","сметана":"noun","дуброва":"noun","проскурня":"noun","родіна":"noun","єна":"noun","солонина":"noun","ліщина":"noun","лугина":"adjective","сосна":"noun","гавва":"noun","ужва":"noun","кулина":"adjective","халява":"noun","холява":"noun","підкова":"noun","крайня":"adjective","хохотва":"noun","цибулька":"noun","нікульча":"noun","кравчина":"noun","лупина":"adjective","лихошва":"noun","думбрава":"noun","плахотня":"adjective","покутня":"adjective","пона":"noun","семена":"noun","грона":"noun","єва":"noun","парасківа":"noun","шова":"noun","бурдужа":"adjective","козюберда":"adjective","говтва":"noun","приколота":"adjective","варнава":"noun","гурина":"adjective","рябокобила":"noun","кучина":"adjective","савва":"noun","кремена":"noun","малая":"adjective","горішня":"adjective","бурдюжа":"adjective","слаква":"noun","городня":"adjective","лиштва":"noun","цяцька":"noun","походня":"noun","недавня":"adjective","долішня":"adjective","марюхна":"noun","борона":"noun","колошва":"noun","семенча":"noun","затона":"noun","заплава":"noun","краснопера":"adjective","рибитва":"noun","сидора":"adjective","краплина":"noun","крутиголова":"noun","бакалина":"adjective","немна":"noun","очеретня":"adjective","пробийголова":"noun","мальона":"noun","сажина":"adjective","вчерашня":"adjective","бузина":"noun","забийворота":"noun","магльона":"noun","нейчева":"noun","потороча":"noun","ревіна":"noun","матьора":"adjective","святина":"noun","хіна":"noun","кожина":"adjective","наріжня":"noun","леона":"noun","передня":"adjective","савина":"adjective","сікачина":"noun","кльова":"noun","недолуга":"adjective","шкоропата":"noun","карасава":"noun","морева":"adjective","мустафіна":"noun","цьова":"noun","бубна":"noun","катона":"noun","міна":"noun","похвала":"noun","слоква":"noun","статіва":"noun","строна":"noun","вова":"noun","карева":"adjective","місюна":"noun","швая":"noun","бальва":"noun","вершина":"noun","врона":"noun","білокобила":"noun","гордина":"noun","кольва":"noun","льова":"noun","перекліта":"noun","основа":"noun","харена":"noun","борозна":"noun","будаква":"noun","каранікола":"noun","палесіка":"noun","рожина":"noun","штана":"noun","вицина":"noun","дубна":"noun","жовна":"noun","зіва":"noun","катарина":"noun","похмура":"adjective","фесина":"noun","шемена":"noun","галутва":"noun","зарева":"noun","ковальва":"noun","мирона":"noun","новосела":"noun","пачина":"adjective","совва":"noun","гіна":"noun","корона":"noun","новоженя":"noun","підберезня":"adjective","ряднина":"noun","сакська":"noun","канна":"noun","лукачина":"noun","плачінта":"noun","редьква":"noun","софина":"adjective","шатня":"adjective","блозва":"noun","вчорашня":"adjective","гриценя":"noun","куропатва":"noun","людва":"noun","стехна":"noun","парахоня":"noun","плєва":"noun","яворина":"noun","бендина":"noun","жовтонога":"adjective","конева":"adjective","мандалина":"noun","мацина":"noun","перезва":"noun","похвата":"noun","токмина":"noun","тюрина":"adjective","гицина":"noun","дзіна":"noun","куява":"noun","малонога":"adjective","стоколоса":"adjective","тимина":"adjective","біднина":"noun","вдовина":"adjective","лисохмара":"noun","микитина":"adjective","полівара":"noun","рибонька":"noun","ружина":"noun","тишина":"noun","цюрмаста":"noun","чалая":"adjective","васина":"noun","воїна":"noun","гулая":"noun","кова":"noun","она":"noun","палісіка":"noun","підошва":"noun","свидина":"noun","тирсина":"noun","хаврона":"noun","зона":"noun","кнзєва":"noun","розна":"adjective","ронжина":"noun","рудомина":"noun","сальва":"noun","скільсара":"noun","служала":"noun","фомина":"adjective","чупина":"adjective","шалупня":"noun","джупина":"noun","зоська":"noun","кузява":"noun","неледва":"noun","равва":"noun","разьва":"noun","шкорина":"noun","білозора":"adjective","бранціра":"noun","випна":"noun","галина":"adjective","мандаліна":"noun","мицька":"noun","мячина":"adjective","недосєка":"noun","пристая":"noun","м'яка":"adjective","вовчина":"noun","гринява":"noun","дівонька":"noun","ігіна":"noun","обійдихата":"noun","хижня":"adjective","челядина":"noun","янева":"adjective","голева":"adjective","дзюнька":"noun","дубрава":"noun","лигомина":"noun","мална":"noun","мархева":"noun","несправа":"noun","озява":"noun","панна":"noun","пупена":"noun","силява":"noun","сухокобила":"noun","цюрмоста":"noun","чевельча":"noun","чівільча":"noun","башева":"noun","бражна":"noun","варавва":"noun","волна":"noun","гольча":"noun","густа":"adjective","достатня":"adjective","зуграва":"noun","карапулька":"noun","кірна":"adjective","крапіва":"noun","луковина":"noun","магдалина":"adjective","мамона":"noun","мелещеня":"noun","мряна":"noun","параскева":"noun","похідня":"noun","пріхна":"noun","свтина":"noun","сьоська":"noun","терепіща":"noun","ціцяла":"noun","бодаква":"noun","гальвіта":"noun","деревенча":"noun","дона":"noun","дубена":"noun","задависвічка":"noun","йовва":"noun","капаціла":"noun","котельва":"noun","лісота":"noun","малюська":"noun","підсадня":"adjective","рєва":"noun","сувора":"adjective","хаджава":"noun","хомина":"adjective","шалева":"adjective","пір'їна":"noun","псина":"noun","бобина":"noun","болотня":"adjective","бруква":"noun","кіона":"noun","ковбінька":"noun","кривонога":"adjective","лєва":"noun","мухина":"adjective","нефортуна":"noun","органіста":"noun","пасулька":"noun","планіда":"adjective","пристава":"noun","салайда":"adjective","бачина":"noun","безкорса":"adjective","бєлокобила":"noun","борзина":"noun","бружина":"noun","воротня":"adjective","гальона":"noun","голтва":"noun","горемульта":"noun","дацина":"noun","забанджала":"noun","злая":"adjective","кікена":"noun","козачухна":"noun","коропатва":"noun","кузина":"adjective","лапунька":"noun","літава":"noun","мінчуна":"noun","на":"noun","ничая":"noun","новіцка":"adjective","пенькна":"noun","пухна":"noun","пуцята":"noun","рісна":"noun","розмаіта":"noun","румина":"adjective","свтна":"noun","сердита":"adjective","січінава":"noun","сментина":"noun","трізна":"noun","хоботня":"adjective","шкуропата":"noun","безхутра":"adjective","білява":"noun","гальва":"noun","гевела":"adjective","гирява":"noun","гнєда":"adjective","гребенча":"noun","гусонька":"noun","калабанька":"noun","козупляка":"noun","лапина":"adjective","мурина":"adjective","некульча":"noun","орона":"noun","парна":"adjective","пліва":"noun","приходька":"noun","сенина":"noun","солотва":"noun","тетева":"adjective","хавана":"noun","хилобока":"adjective","царева":"adjective","ахалая":"noun","варенька":"noun","варшава":"noun","вересоча":"noun","галунька":"noun","гліва":"noun","голина":"adjective","грузька":"adjective","гудина":"noun","євона":"noun","кірева":"adjective","кожем'яка":"noun","колоберда":"adjective","курінька":"noun","маржина":"noun","мигалина":"noun","мікава":"adjective","падва":"noun","паланичка":"adjective","палена":"adjective","подкова":"noun","ратушня":"adjective","селегейна":"noun","сминтина":"noun","сумина":"adjective","теміркая":"noun","ухата":"adjective","хавроня":"noun","холоста":"adjective","ціва":"noun","чернята":"noun","чикольва":"noun","шалина":"adjective","юдина":"adjective","адвена":"noun","балева":"adjective","брона":"noun","вербовата":"adjective","веремєва":"noun","волчаста":"adjective","гафина":"adjective","голутва":"noun","дацева":"noun","дерена":"adjective","закрева":"noun","каджая":"noun","кальченя":"noun","капаниста":"adjective","кикина":"adjective","костерева":"noun","кривокобила":"noun","кулєва":"noun","лавна":"noun","маліцка":"adjective","молдова":"noun","моркова":"noun","пажина":"adjective","перевернихата":"noun","пилева":"adjective","піддубня":"adjective","постіва":"noun","пуста":"adjective","суботня":"adjective","фадеева":"adjective","ходаніцка":"adjective","хохітва":"noun","цибата":"adjective","черноока":"adjective","чкадуа":"noun","чокена":"noun","шепетина":"noun","шербина":"noun","яка":"adjective","ятва":"noun","безена":"noun","безшкура":"adjective","безязика":"adjective","белая":"adjective","берулава":"noun","бузна":"noun","бурсала":"noun","бучаста":"adjective","вчина":"noun","гапона":"noun","гернажа":"noun","гордуна":"noun","горсва":"noun","горясва":"noun","грицька":"noun","двіжона":"noun","задурня":"adjective","заслона":"noun","зачешигрива":"noun","йона":"noun","качна":"adjective","козовіта":"noun","криворота":"adjective","кур'ята":"noun","лозна":"adjective","люлява":"noun","лютая":"adjective","матухна":"noun","накутня":"adjective","плохая":"adjective","бухая":"adjective","самотня":"adjective"};class Fm{encode(e){const t=new Uint8Array(1);switch(e.wordClass){case r.NOUN:t[0]=1;break;case r.ADJECTIVE:t[0]=0;break;default:throw new TypeError(`Invalid word class: "${e.wordClass}".`)}return t}decode(e){if(e.length<1||e.length>1)throw new RangeError("Invalid vector length.");const t=e[0];if(t<0||t>1)throw new RangeError("Invalid vector value.");return{wordClass:t>=.5?r.NOUN:r.ADJECTIVE}}}class _m{constructor(e,t=0){this.vectorSize=e,this.unknownCharcode=t}encode(e){var t;const n=new Uint8Array(this.vectorSize),i=e.slice(-this.vectorSize).toLowerCase().padStart(this.vectorSize,"-");for(let e=0;e<i.length;e+=1){const a=i[e];n[e]=null!==(t=s[a])&&void 0!==t?t:this.unknownCharcode}return n}}Q().set("IS_NODE",!1);var Rm={class_name:"Sequential",config:{name:"sequential_1",layers:[{class_name:"Embedding",config:{input_dim:34,output_dim:16,embeddings_initializer:{class_name:"RandomUniform",config:{minval:-.05,maxval:.05,seed:null}},embeddings_regularizer:null,activity_regularizer:null,embeddings_constraint:null,mask_zero:null,input_length:null,name:"embedding_Embedding1",trainable:!0,batch_input_shape:[null,null]}},{class_name:"SimpleRNN",config:{name:"simple_rnn_SimpleRNN1",trainable:!0,units:16,activation:"relu",use_bias:!0,kernel_initializer:{class_name:"VarianceScaling",config:{scale:1,mode:"fan_avg",distribution:"normal",seed:null}},recurrent_initializer:{class_name:"Orthogonal",config:{gain:1,seed:null}},bias_initializer:{class_name:"Zeros",config:{}},kernel_regularizer:null,recurrent_regularizer:null,bias_regularizer:null,activity_regularizer:null,kernel_constraint:null,recurrent_constraint:null,bias_constraint:null,dropout:0,recurrent_dropout:0,return_sequences:!1,return_state:!1,go_backwards:!1,stateful:!1,unroll:!1}},{class_name:"Dense",config:{units:1,activation:"sigmoid",use_bias:!0,kernel_initializer:{class_name:"VarianceScaling",config:{scale:1,mode:"fan_avg",distribution:"normal",seed:null}},bias_initializer:{class_name:"Zeros",config:{}},kernel_regularizer:null,bias_regularizer:null,activity_regularizer:null,kernel_constraint:null,bias_constraint:null,name:"dense_Dense1",trainable:!0}}]},keras_version:"tfjs-layers 4.2.0",backend:"tensor_flow.js"},Lm=[{name:"embedding_Embedding1/embeddings",shape:[34,16],dtype:"float32"},{name:"simple_rnn_SimpleRNN1/kernel",shape:[16,16],dtype:"float32"},{name:"simple_rnn_SimpleRNN1/recurrent_kernel",shape:[16,16],dtype:"float32"},{name:"simple_rnn_SimpleRNN1/bias",shape:[16],dtype:"float32"},{name:"dense_Dense1/kernel",shape:[16,1],dtype:"float32"},{name:"dense_Dense1/bias",shape:[1],dtype:"float32"}],Mm="D3HrvZUs7rxT6Vu+tVsfvPLyB70zbt695ECPvKyKWj7TnUO+JZ9pvs8MkL3/1DQ+kftzvPGZZL4aDpe8KiOnvSvRHz52vQK9mGiSPm50B72RCfM+7hW6PSOuTz7b9zG+M5MOPv/mYL7Q9Rk+aPgRvrfQuT6mQ2Q+eOawPp/PpLyM9yY+zB4APT27n75OVUk+V8y6vetFyD0zPlW+sqPfPER8Ub6J1pI+5QwEvcZktT12HLW+FSFGPU6s2ryQapW9/MNNvoK1t71R5sK8N6Y/vjqBzTtusl2+0Ks8PpZOQ74ua5U9TOIfvkpgHDxho/294hcTPkJaiL1iXTo9o28bPhnMBr69EoG8CAeCvtgxXT5kMKq+KnLfPbScM73jYjw+LTa8vSeQWj49+cU7/FH2PKtOwr5y8K29GMMdvrkIgb0wK4C8Zeq2vXlG+L15O4c+CaFGvpmCjD5guBg+0AAQPv0EjT3CdZ0+vLOBulXEAb7VVpi+WldAPpIP8T0ETFm+NcLIPZix17rKGEW+n8jxPfT8hr43TLC8esPRvX6k4D1lZ0C+WERdPo4Qab4SdWw+uWSevp7+zTjX5Xi8nw+ZvldSb7xUfke7HX01PVOV2zzFqV2+SqcNvvPUTz0nzZi9Zl+ePWj6Wr3PLjY+vbjrvSRr6b1es/w8oaLjPUC0G72spye9rsomPtW/t72QYEy9AtR6PuX44z1dLrk9k6HAPE1+Eb7w1mY+N8MSvuMLsj1qmsO6JrRAvsJowr7iA1E+udZGPDLR57xRSj8+GFSnvYNUujxIvpM8FHmHvkr8QD38Po29LslnvShYOD45FAE7vfaWPbnegruqB2W9MdUkPpskUb3YGTU+L3gwvQhAYD4ed66+qJQUvjydBr7bSam8fYz/PCTisD7GYoQ+HDxJvSaIR77s3u+8sVTkvaDBaL13FBs+Z8T4vT4aKj2d4DC7ft+GPvVXFLxGXGI9RJ9avl7RCD6ujIy+M+/zPQbAtr3B2+c9BpZcPYIBTj7QNsM95bqEPc221T3u7TO+M2PIPU/BQb78/nk+f4TmvV5Elj0VOAK+0Y+DPq0GkL364pI98CGUvjK4IL1CLoK+kohXvTS3I76BpcM9WE0Rva5vkz301Ui+CLe7vWkLnT1sjpM8EYyWPWblIryk+gI+gnQSvu9XKL7jtni9Rc/IvaonHj2sKBc+VzRovpdOpT64szY+OavnvfzjeLuBH62+OqC2OoeMBr0eJVi7ST7CPLK/3jxTOoC9BRUSPjNBaD6OIlm+7ApUPlbsWj5KIKi+J9F1Pfi88L1+JdA9a6F+PsiRub06rh2+HlXnPb5Wj774l+i6nifjvWMCtL2WnqW9pUNdvjQM4L0ZJDy9lZ+LPbJWhj2hUZO+iWF0vhq17zqKwOI9Qq6sPWo8gD3c0co9/5WaPLN6PL6HOLO8fXvUvEF2IL4QJ7S98UzCPZJTlb6VUCM+y7dqvkJXyTyxD+I9N6PXvUxuqr0jiuM9p1OgO/wUFL07zEy+n5rPvSLifbt4N5e+kbdRviF6Db0ZSjo+B+dXvqB+iT7nFI68Z9bUPU9FGT21fz4+fee2vaIHqLzRTtG8aGggPqQlpD1GORk9/FpnPjatAL60OPg8x+qAPdU74zxSk6+9lYwdPikogr6pxao99PmXvH+yEz4zu5U9IeURPXqY9LpuvYk8OGmYvFX7+TtuUaO9qg0GPph0Xr5vdYM+0deHvozgtryfgDC8DaCGPTVxHb6q0fI97pWqPOXMAj7Y9ae+fljRuoumt71vblO+UaetPcadt7yiUYi9R9x8PqXbmb4V9gK+v2jjvVsTU72VAJ29JC1vPcpy1D2uNZM9N5mlvru77rxAZSo9jZWkvv+0HD6CY6k9RvnyvLM8Wr4/Yjo+aEr4vcUQkj3Ef7+7DusLvhf0oLxUt1u+LdOWPndY+Ty5+Dq+QfqQvqgCbj7V0L68swkNviGjaz0SkyQ+h9uuvckW97rM35m+O7ERPQvQ4L2XN3a9XwqPPifY7TynN0i9enwJPWh2Tj27c02+k0bpPWtEGz4p+qs9DzsKPhlEoD7U1qM9v7SAvNgeIr7tPJM9om6CvhmNcz7pBIa9HEvlPRmEGj7SzgE9tdoAO8dkeT2N2Xm9ChofvhVPSj19rZG+A2PfPVrax72zacc9YWsTvjSKAj4inbu9GbJGvSEnt76qFeq8JsAnvZ0cO75Lk7e5G8+WPrc5Cb3RGVg+xwxfvgTMNr18pdU9U49jPaRh5rg8G2Q+iUtrObd+jT0FTYG+XgVgvKwXJr6TWuG9BWosPlr9pT6IF2G+boCIvU0FOb39ivu9aMA5viC1S714C3q+CES6Pt11j76mNqk+/btevCcEVL7z5cK+ALgyPJeTPb0+7O+7lftrPslPZz1EqIY9DWKYvdtgWL5/DwI9Q2NFvJhKcb0MMQo+NtltPWZcmT2FlVA9V5Nnvc9IJr0TXCA+nAIuPoF7xbon0SQ+Kwi8ve0ePb6O3++9k2/GvZoLlrxRDM48DwOkvEiWIz7jsgC+NYZzvTu7Jb7Jcgm8qAoyPg8zkT3o8UI+7Mt/vZsaYj7UZDm+Z4BTPBgkQr7CSTs+PKpvPbkSED3tAaW9LJ9APo74Fz62CFe8xMDCPi83F76ttk++K6FGvQkDDr42fbG+N9cbPvP1Br2CU1c+qukfvu3DJz6Vjfy8jlM9PZNaKL4Ceu29dDVCvoG7fD5qTLu75+YoPXt8GD7ey2U+KpynvemmCL1L1VC9LsfhvcoBND44he273UFiPrLzK72XXPS9ZjZGPtBwh7gwW2i+ccbxvXtoMj4Q/u49AzHBvoTjHD40AuW+OiwYP4x9JD6PGAY/KN7+Pc0xhb6OqxY9AptQvbc7Or39a9e6DJ/zPvd+iz6XX7g6kqsEP5LI1L7ICBk+1k5SP0lR0T43qYI+kbFLvcUh5L7+v90+5mnZveLTxj03yAS+phJLvW7x3b4m3J68GeeBvlrhgj05ac++0Yyfvcrz7L1/Y/i+ZjMKPhEy6j3ImRu+fRRuPkunGL5dMVG+Yd5Fv6ys1z6PXYI+JhzOvaGxDT4p38I+QcDHPtkxbb0XnjM/ogGYviZrLj291se+iNNqvpZuUb7nas8+lj4tvvyQ3D7w+FO9r4ybPs7MJD+WsIG9pGxHPqmQo75RdUG/gFs2vRXbrj7n87w9aGosPm8vDr/oUeO+2pWxPsk1RT7lvPS+YBmZvkDPU745ORi/BxbNPg83pD2KOSq9Nh0tPw6bSj+WVTk97hLcPnMDpT7GgXW8dL46vltPvb11QOu9CeYDPYDxwbx5UQ8+MnesPb+Ajj7Uv7m+qE+TvM+Qt77g88s+7940P8/1zj5p9+g+FugoPgNebT69zXg+IbhFvnHq6LsVozg+iIaBPau6Kr6tTOG+U1bhPS6zFD64rqY/FZebvhOPeL5DGXo+dwgLPjKu6z5+X78+iAsNPrs/Pb+RQoe+6MyqvWutu75ml7G+3Casvq63/b4exKi9+5lMv7V/yb4twI49cbIcv/+5/r5lWxE/78Q+PhjngT4SENI9xZKXPmmQEb9UJGK+eYE3vtOLiDxf4zo+9KX5Pl0APj9PhqA+i/wMv1iRsjzngaK+/ocBv8RUnr0hPdM+YAshv896DL1aukY+kiIJvsKhvD66FTi++84Fv5vWjL4lr6W+OLvyvba/krzwXgm9X8rUvv+XNb7jhSo/zfCAPLRlqD4Fn5S+DeQfP0847T7NIZ4+/gMAPxyfcT6VQOM+UOmWvWDtrD4TLFW9NGQSveJN9T7AuFm+MvUSv/TnFz8uw68+k05IPj26MTwDLsW+hsLFvifDqD7Z6d28z+AOv1DeZL8TnA++mrwBvT0BGL5ireW+PLbOOQjsJjzUmya/CcavOz8kwr70lmK+PHcmPsmi9r5VeAI+yly7PSGkIT6xV1Q/uHsKP4WFir4DBcc+SIJuPlP0Lb5Nufu+dKc3vk/X4L2Qvyo/jJSCPr3+Vr7NNA4/5AqcPoYisjuvO6g9JGKRPgxvQj/bUnG8yqAbP8wDO75rdkO+keIuPvrKxT4VCoQ9fx3XPih9K77kIOg99g2gPcrn4rxDzyy+TDdxPpzmHz//YWM+PIXFvTGs4z5SaaE9NAwkv4Qcub6gS3g+6Wa0vf3qJD8NDC2/q4z6PFVEob5p8yG+uSjhvjAMgD4GQ2Q/+EfRPlrsL79K2PO+FyOrPav1lT6vSzQ+nQOovRiVMD4Yfg4+weDxPv9V8b3ix407T0mFvEXdYT4DaKq+rE4YviLa2r4q/vI7hVWOvWgaV77A7QU/OU2iPp8QQT58RIA+Lbf+vo65Fz1RDRw+mv6WvdOImj4/IyY9a+vPO/pDuj6WiFe94SnbvW0cAb5HUcQ8croTvdeGIT6Q5p89/2EpPyPapj33gSS+q161vhFrSj00b5A9P6g4vssdob5sS5G+r72gvUDqCj+C5+a9lJHFPjtFxz10OYs+qXakvlUu5Trwp749nrcQPbAzwr5pCs8+UhoIvsHVdT7iw+i+UYxzPgTn5T50arg+R/4IP7kH2T2cguW+pQX+vFqQdr3z5yY+SdURProPID4CXhA9crIcP/7a4D6r/549Ly6lvXeFUb9n9xs/CC3oPrOgAj8iPwo/8nPXviKqAr8q6TQ+vrumPrdtHz8prJq+V1/oPUZWGr4Y4cU9nRopvtRCkz2jeTy+pJW0PgwDyz6XfIo+QmZevqCRSj1/pIa+KoufPllZvT5o244+nRIYP3TbM70N+8y+a7d2vcsSWj4Cdrw+AT8hPVoDwL0BxL2+G1pmPo/CZL66zSS+g2rFPvewar7nfGe+YEuevRgFIr7dyRS+KES0Pnu1p754F6s+/inJPXa3tL4Qd5A+OmbLPWvlnb75WsU9rRHMvsgqxD5MQ90+Y38LPnBkZj7fKIs9uJCHvdiuXr6D/Rw9hpVyPu9Vqr4Qzom85dP6vYymmr1yG5w+2gSMPlV5tT1D1ks+EKTZPm4gOb6ZC+w+k8EOPA8oXb6r9z2+h6Tgvm7Dvj7OzJQ+7tkIPvbDjz4TN6u9GneSPTIooD7GdRA/wYQ4vVr7b71F/QI+cRORPrRPWzxVX22+Yu2vPsHriL720za+oBlVPogMe72YNKM8r9aEO5uq1z7RegW+4aX1PqfYRD/wpfI9sVqvPCI99jpAtWC9eXJ2PBb++j6w+809iODsPfwV0b2kL7S9D+FLPQZECD4oYRA+V1Z+vjarEj5ZF/q8KJSAPkjENr7zNd28pKODPj8FPL8mgFY8kJVMvgBfQ75uooK++9TaPg/5Cr5Pzo6+1Yy3viONQL/Fvng+Bmn6vTpQkb0N7Oi94ZVHPYE2Hr7J/Rk+zQzKvL3Chj5d85o+Q/YRPrsjnj7YzJY+01w3PyVgGD6INkM+XtnevbmxiL7Z1NI+jpdgvggkdz0QnJq+35a8PZX0SL4+y78+grnOPYHzlD2VKRA/xRW4PqyCPL4Cowa/Ku+pvZabKz99894+sY/Vva/ezL1zsUw+er4IP8DL/D1qa2a+m6B3PK8Cq76mu2++gsjvvP0kBz8pWqe+SyotvKUdmz4pFXA7bkXCvbwSbj44g7c8mID4viXITL56E/G9zBVuPPD+u7wCmJc9v1nDuyyEX77G7Nq8GUwXvQJRVT3nTYY9/wK9Pct9sT1dCqU9aRsHvlmTFD2/B5M9PclmvNt2Jb8eqR2+bZhIvlmRVT4k0zU/OFSyvnCsHb/BfrK+ZZJGv10pNT8uXQk/AaVXvgbtG76M5kC+b6zpPfBICD8I1Lm8",Om={format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v4.2.0",convertedBy:null};const Pm="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);class Bm{inflect(e,t,n){return a(this,void 0,void 0,(function*(){const i=[],a=e.split("-");for(let e=0;e<a.length;e+=1){const s=yield this.inflectNamePart(a[e],t,n,e===a.length-1);i.push(s)}return i.join("-")}))}}const Um=/[ая]$/i,Wm=/(ой|ий|ій|их)$/i;const Gm=new class extends Bm{constructor(e){super(),this.wordInflector=e}inflectNamePart(e,t,n){return this.wordInflector.inflect(e,{grammaticalCase:n,gender:t,application:"givenName"})}}(b),Vm=new class extends Bm{constructor(e){super(),this.wordInflector=e}inflectNamePart(e,t,n){return this.wordInflector.inflect(e,{grammaticalCase:n,gender:t,application:"patronymicName",customRuleFilter:e=>e.application.includes("patronymicName")})}}(b),Km=new class{constructor(e){this.modelLoader=e,this.modelPromise=null,this.wordTransformer=new _m(20),this.familyNameClassTransformer=new Fm}classify(e){return a(this,void 0,void 0,(function*(){let t=this.getCached(e);if(null!=t)return t;const n=yield this.loadModel(),i=this.wordTransformer.encode(e),a=yield n.predict(Ks([i])).data();return t=this.familyNameClassTransformer.decode(a),t}))}getCached(e){let t=null;const n=Dm[e.toLowerCase()];return n&&(t={wordClass:n}),t}loadModel(){return a(this,void 0,void 0,(function*(){return null==this.modelPromise&&(this.modelPromise=kp(this.modelLoader)),this.modelPromise}))}}(new class{load(){return a(this,void 0,void 0,(function*(){const e={};if(e.modelTopology=Rm,e.weightSpecs=Lm,e.weightData=function(e){if(Pm){const t=Buffer.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n.set([t.charCodeAt(e)],e);return n.buffer}(Mm),null!=Om){const t=Om;e.format=t.format,e.generatedBy=t.generatedBy,e.convertedBy=t.convertedBy,null!=t.signature&&(e.signature=t.signature),null!=t.userDefinedMetadata&&(e.userDefinedMetadata=t.userDefinedMetadata),null!=t.modelInitializer&&(e.modelInitializer=t.modelInitializer),null!=t.initializerSignature&&(e.initializerSignature=t.initializerSignature),null!=t.trainingConfig&&(e.trainingConfig=t.trainingConfig)}return e}))}}),qm=new class extends Bm{constructor(e,t){super(),this.wordInflector=e,this.familyNameClassifier=t}inflectNamePart(e,t,n,i){return a(this,void 0,void 0,(function*(){if(!i&&l(e))return e;let a=null;return this.isUncertainFamilyNameClass(e,t)&&(a=yield this.familyNameClassifier.classify(e)),this.wordInflector.inflect(e,{grammaticalCase:n,gender:t,wordClass:null==a?void 0:a.wordClass,application:"familyName"})}))}isUncertainFamilyNameClass(t,n){return n===e.GrammaticalGender.FEMININE&&Um.test(t)||n===e.GrammaticalGender.MASCULINE&&Wm.test(t)}}(b,Km),Hm=new class{constructor(e,t,n){this.givenNameInflector=e,this.patronymicNameInflector=t,this.familyNameInflector=n}inflect(e,t,n){return a(this,void 0,void 0,(function*(){const i={};return null!=e.givenName&&(i.givenName=yield this.givenNameInflector.inflect(e.givenName,t,n)),null!=e.patronymicName&&(i.patronymicName=yield this.patronymicNameInflector.inflect(e.patronymicName,t,n)),null!=e.familyName&&(i.familyName=yield this.familyNameInflector.inflect(e.familyName,t,n)),i}))}}
|
|
4671
4671
|
/**
|
|
4672
4672
|
* @license
|
|
4673
4673
|
* Copyright 2020 Google LLC. All Rights Reserved.
|