brain-browser.js 359 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('gpu.js')) :
  3. typeof define === 'function' && define.amd ? define(['exports', 'gpu.js'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.brain = {}, global.gpu_js));
  5. }(this, (function (exports, gpu_js) { 'use strict';
  6. /**
  7. * Relu Activation, aka Rectified Linear Unit Activation
  8. * @description https://en.wikipedia.org/wiki/Rectifier_(neural_networks)
  9. */
  10. function activate$3(weight) {
  11. return Math.max(0, weight);
  12. }
  13. /**
  14. * Relu derivative
  15. */
  16. function measure$3(weight, delta) {
  17. if (weight <= 0) {
  18. return 0;
  19. }
  20. return delta;
  21. }
  22. var relu$2 = /*#__PURE__*/Object.freeze({
  23. __proto__: null,
  24. activate: activate$3,
  25. measure: measure$3
  26. });
  27. /**
  28. * sigmoid activation
  29. */
  30. function activate$2(value) {
  31. return 1 / (1 + Math.exp(-value));
  32. }
  33. /**
  34. * sigmoid derivative
  35. */
  36. function measure$2(weight, error) {
  37. return weight * (1 - weight) * error;
  38. }
  39. var sigmoid$2 = /*#__PURE__*/Object.freeze({
  40. __proto__: null,
  41. activate: activate$2,
  42. measure: measure$2
  43. });
  44. /**
  45. * Hyperbolic tan
  46. */
  47. function activate$1(weight) {
  48. return Math.tanh(weight);
  49. }
  50. /**
  51. * @description grad for z = tanh(x) is (1 - z^2)
  52. */
  53. function measure$1(weight, error) {
  54. return (1 - weight * weight) * error;
  55. }
  56. var tanh$2 = /*#__PURE__*/Object.freeze({
  57. __proto__: null,
  58. activate: activate$1,
  59. measure: measure$1
  60. });
  61. /**
  62. * Leaky Relu Activation, aka Leaky Rectified Linear Unit Activation
  63. * @description https://en.wikipedia.org/wiki/Rectifier_(neural_networks)
  64. */
  65. function activate(weight) {
  66. return weight > 0 ? weight : 0.01 * weight;
  67. }
  68. /**
  69. * Leaky Relu derivative
  70. */
  71. function measure(weight, error) {
  72. return weight > 0 ? error : 0.01 * error;
  73. }
  74. var leakyRelu$1 = /*#__PURE__*/Object.freeze({
  75. __proto__: null,
  76. activate: activate,
  77. measure: measure
  78. });
  79. var index$1 = /*#__PURE__*/Object.freeze({
  80. __proto__: null,
  81. relu: relu$2,
  82. sigmoid: sigmoid$2,
  83. tanh: tanh$2,
  84. leakyRelu: leakyRelu$1
  85. });
  86. class CrossValidate {
  87. constructor(initClassifier) {
  88. this.json = {
  89. avgs: {
  90. error: 0,
  91. iterations: 0,
  92. testTime: 0,
  93. trainTime: 0,
  94. },
  95. stats: {
  96. total: 0,
  97. testSize: 0,
  98. trainSize: 0,
  99. },
  100. sets: [],
  101. };
  102. this.initClassifier = initClassifier;
  103. }
  104. testPartition(trainOpts, trainSet, testSet) {
  105. const classifier = this.initClassifier();
  106. const beginTrain = Date.now();
  107. const trainingStats = classifier.train(trainSet, trainOpts);
  108. const beginTest = Date.now();
  109. const testStats = classifier.test(testSet);
  110. const endTest = Date.now();
  111. return {
  112. ...testStats,
  113. trainTime: beginTest - beginTrain,
  114. testTime: endTest - beginTest,
  115. iterations: trainingStats.iterations,
  116. error: trainingStats.error,
  117. total: testStats.total,
  118. network: classifier.toJSON(),
  119. };
  120. }
  121. /**
  122. * Randomize array element order in-place.
  123. * Using Durstenfeld shuffle algorithm.
  124. * source: http://stackoverflow.com/a/12646864/1324039
  125. */
  126. shuffleArray(array) {
  127. for (let i = array.length - 1; i > 0; i--) {
  128. const j = Math.floor(Math.random() * (i + 1));
  129. const temp = array[i];
  130. array[i] = array[j];
  131. array[j] = temp;
  132. }
  133. return array;
  134. }
  135. train(data, trainOpts = {}, k = 4) {
  136. if (data.length < k) {
  137. throw new Error(`Training set size is too small for ${data.length} k folds of ${k}`);
  138. }
  139. this.shuffleArray(data);
  140. const size = data.length / k;
  141. const avgs = {
  142. trainTime: 0,
  143. testTime: 0,
  144. iterations: 0,
  145. error: 0,
  146. };
  147. const stats = {
  148. total: 0,
  149. testSize: 0,
  150. trainSize: 0,
  151. };
  152. const binaryStats = {
  153. total: 0,
  154. testSize: 0,
  155. trainSize: 0,
  156. truePos: 0,
  157. trueNeg: 0,
  158. falsePos: 0,
  159. falseNeg: 0,
  160. precision: 0,
  161. recall: 0,
  162. accuracy: 0,
  163. };
  164. const results = [];
  165. let isBinary = null;
  166. for (let i = 0; i < k; i++) {
  167. const dclone = data.slice(0);
  168. const testSet = dclone.splice(i * size, size);
  169. const trainSet = dclone;
  170. const result = this.testPartition(trainOpts, trainSet, testSet);
  171. if (isBinary === null) {
  172. isBinary =
  173. result.hasOwnProperty('falseNeg') &&
  174. result.hasOwnProperty('falsePos') &&
  175. result.hasOwnProperty('trueNeg') &&
  176. result.hasOwnProperty('truePos');
  177. if (isBinary) {
  178. Object.assign(stats, binaryStats);
  179. }
  180. }
  181. avgs.iterations += result.iterations;
  182. avgs.testTime += result.testTime;
  183. avgs.trainTime += result.trainTime;
  184. avgs.error += result.error;
  185. stats.total += result.total;
  186. if (CrossValidate.isBinaryStats(stats) &&
  187. CrossValidate.isBinaryPartitionResults(result)) {
  188. stats.accuracy += result.accuracy;
  189. stats.falseNeg += result.falseNeg;
  190. stats.falsePos += result.falsePos;
  191. stats.precision += result.precision;
  192. stats.recall += result.recall;
  193. stats.trueNeg += result.trueNeg;
  194. stats.truePos += result.truePos;
  195. }
  196. results.push(result);
  197. }
  198. avgs.error /= k;
  199. avgs.iterations /= k;
  200. avgs.testTime /= k;
  201. avgs.trainTime /= k;
  202. if (CrossValidate.isBinaryStats(stats)) {
  203. stats.precision = stats.truePos / (stats.truePos + stats.falsePos);
  204. stats.recall = stats.truePos / (stats.truePos + stats.falseNeg);
  205. stats.accuracy = (stats.trueNeg + stats.truePos) / stats.total;
  206. }
  207. stats.testSize = size;
  208. stats.trainSize = data.length - size;
  209. this.json = {
  210. avgs: avgs,
  211. stats: stats,
  212. sets: results,
  213. };
  214. return this.json;
  215. }
  216. toNeuralNetwork() {
  217. return this.fromJSON(this.json);
  218. }
  219. toJSON() {
  220. return this.json;
  221. }
  222. fromJSON(crossValidateJson) {
  223. const winningJSON = crossValidateJson.sets.reduce((prev, cur) => (prev.error < cur.error ? prev : cur));
  224. return this.initClassifier().fromJSON(winningJSON.network);
  225. }
  226. }
  227. CrossValidate.isBinaryStats = (stats) => {
  228. return (stats.accuracy !== undefined);
  229. };
  230. CrossValidate.isBinaryResults = (stats) => stats.stats.accuracy !== undefined;
  231. CrossValidate.isBinaryPartitionResults = (stats) => stats.accuracy !==
  232. undefined;
  233. let gpuInstance = null;
  234. /**
  235. * Sets up the gpu.js instance
  236. */
  237. function setup(value) {
  238. gpuInstance = value;
  239. }
  240. function makeKernel(fn, settings) {
  241. let _gpuInstance = gpuInstance;
  242. if (_gpuInstance === null) {
  243. _gpuInstance = new gpu_js.GPU({ mode: 'gpu' });
  244. setup(_gpuInstance);
  245. }
  246. return _gpuInstance
  247. .createKernel(fn, settings)
  248. .setPipeline(true);
  249. }
  250. function makeKernelMap(map, fn, settings) {
  251. let _gpuInstance = gpuInstance;
  252. if (_gpuInstance === null) {
  253. _gpuInstance = new gpu_js.GPU({ mode: 'gpu' });
  254. setup(_gpuInstance);
  255. }
  256. return _gpuInstance
  257. .createKernelMap(map, fn, settings)
  258. .setPipeline(true);
  259. }
  260. /**
  261. * Compiles a function into a gpu.js dev mode kernel
  262. */
  263. // export function makeDevKernel(
  264. // fn: ThreadFunction,
  265. // settings: makeKernelSettings
  266. // ): IKernelRunShortcut {
  267. // if ('map' in settings) {
  268. // throw new Error('map kernels are not supported by dev kernels');
  269. // }
  270. // const gpu = new GPU({ mode: 'dev' });
  271. // return gpu.createKernel(fn, settings);
  272. // }
  273. function kernelInput(value, size) {
  274. return new gpu_js.Input(value, size);
  275. }
  276. /**
  277. * Deletes a gpu.js texture and frees VRAM
  278. */
  279. function release(possibleTexture) {
  280. if (possibleTexture instanceof gpu_js.Texture) {
  281. possibleTexture.delete();
  282. }
  283. }
  284. /**
  285. * Cleans ie sets all elements to 0 of a Texture or a js array
  286. */
  287. function clear(value) {
  288. if (value instanceof gpu_js.Texture) {
  289. value.clear();
  290. return;
  291. }
  292. // array
  293. if (Array.isArray(value)) {
  294. if (typeof value[0] === 'number') {
  295. value.fill(0);
  296. }
  297. else if (typeof value[0][0] === 'number') {
  298. for (let x = 0; x < value.length; x++) {
  299. value[x].fill(0);
  300. }
  301. return;
  302. }
  303. else if (typeof value[0][0][0] === 'number') {
  304. // cube
  305. for (let y = 0; y < value.length; y++) {
  306. const row = value[y];
  307. for (let x = 0; x < row.length; x++) {
  308. row[x].fill(0);
  309. }
  310. }
  311. return;
  312. }
  313. }
  314. if (value instanceof Float32Array) {
  315. value.fill(0);
  316. return;
  317. }
  318. throw new Error('unhandled value');
  319. }
  320. /**
  321. * Clones a value
  322. */
  323. function clone(value) {
  324. if (value instanceof gpu_js.Texture) {
  325. return value.clone();
  326. }
  327. if (value instanceof Float32Array) {
  328. return value.slice(0);
  329. }
  330. if (Array.isArray(value)) {
  331. if (typeof value[0] === 'number') {
  332. return value.slice(0);
  333. }
  334. else if (typeof value[0][0] === 'number') {
  335. const matrix = new Array(value.length);
  336. for (let x = 0; x < value.length; x++) {
  337. matrix[x] = value[x].slice(0);
  338. }
  339. return matrix;
  340. }
  341. else if (typeof value[0][0][0] === 'number') {
  342. const cube = new Array(value.length);
  343. for (let y = 0; y < value.length; y++) {
  344. const row = value[y];
  345. const matrix = new Array(row.length);
  346. for (let x = 0; x < row.length; x++) {
  347. matrix[x] = row[x].slice(0);
  348. }
  349. }
  350. return cube;
  351. }
  352. }
  353. throw new Error('unhandled value');
  354. }
  355. /**
  356. * 2D Mean Squared Error
  357. */
  358. function mse2d(errors) {
  359. let sum = 0;
  360. for (let y = 0; y < this.constants.height; y++) {
  361. for (let x = 0; x < this.constants.width; x++) {
  362. sum += errors[y][x] ** 2;
  363. }
  364. }
  365. return sum / this.constants.length;
  366. }
  367. class MeanSquaredError {
  368. constructor({ width, height }) {
  369. this.calculate = makeKernel(mse2d, {
  370. output: [1],
  371. constants: {
  372. width,
  373. height,
  374. length: width * height,
  375. },
  376. immutable: true,
  377. });
  378. this.addAbsolute = makeKernel(function (prevError, prevLayerErrors) {
  379. return prevError[0] + Math.abs(prevLayerErrors[0][0]);
  380. }, {
  381. output: [1],
  382. immutable: true,
  383. });
  384. this.add = makeKernel(function (value1, value2) {
  385. return value1[0] + value2[0];
  386. }, {
  387. output: [1],
  388. immutable: true,
  389. });
  390. this.divide = makeKernel(function (length, mseSum) {
  391. const value = mseSum[0];
  392. if (value > 0) {
  393. return value / length;
  394. }
  395. return 0;
  396. }, {
  397. output: [1],
  398. immutable: true,
  399. });
  400. }
  401. }
  402. const baseLayerDefaultSettings = {
  403. width: 1,
  404. height: 1,
  405. depth: null,
  406. weights: null,
  407. deltas: null,
  408. praxis: null,
  409. praxisOpts: null,
  410. cleanupDeltas: true,
  411. };
  412. class BaseLayer {
  413. constructor(settings) {
  414. this.praxis = null;
  415. this.predictKernel = null;
  416. this.compareKernel = null;
  417. if (settings) {
  418. this.settings = { ...baseLayerDefaultSettings, ...settings };
  419. }
  420. else {
  421. this.settings = { ...baseLayerDefaultSettings };
  422. }
  423. this.setupPraxis();
  424. }
  425. get width() {
  426. var _a;
  427. return (_a = this.settings.width) !== null && _a !== void 0 ? _a : 0;
  428. }
  429. get height() {
  430. var _a;
  431. return (_a = this.settings.height) !== null && _a !== void 0 ? _a : 0;
  432. }
  433. get depth() {
  434. var _a;
  435. return (_a = this.settings.depth) !== null && _a !== void 0 ? _a : 0;
  436. }
  437. get weights() {
  438. return this.settings.weights;
  439. }
  440. set weights(weights) {
  441. this.settings.weights = weights;
  442. if (this.settings.cleanupDeltas && this.deltas) {
  443. clear(this.deltas);
  444. }
  445. }
  446. get deltas() {
  447. return this.settings.deltas;
  448. }
  449. set deltas(deltas) {
  450. this.settings.deltas = deltas;
  451. }
  452. get id() {
  453. var _a;
  454. return (_a = this.settings.id) !== null && _a !== void 0 ? _a : '';
  455. }
  456. set id(title) {
  457. this.settings.id = title;
  458. }
  459. setupPraxis() {
  460. const { initPraxis, praxis, praxisOpts } = this.settings;
  461. if (!this.praxis) {
  462. if (initPraxis) {
  463. if (praxisOpts) {
  464. this.praxis = initPraxis(this, praxisOpts);
  465. }
  466. else {
  467. this.praxis = initPraxis(this);
  468. }
  469. }
  470. else if (praxis) {
  471. this.praxis = praxis;
  472. }
  473. }
  474. }
  475. /*
  476. get weights() {
  477. return this._weights;
  478. }
  479. set weights(value) {
  480. if (value) {
  481. if (value.dimensions) {
  482. if (value.dimensions[0] !== this.width) {
  483. throw new Error(`${this.constructor.name}.weights being set with improper value width`);
  484. }
  485. if (value.dimensions[1] !== this.height) {
  486. throw new Error(`${this.constructor.name}.weights being set with improper value height`);
  487. }
  488. } else {
  489. if (value[0].length !== this.width) {
  490. throw new Error(`${this.constructor.name}.weights being set with improper value width`);
  491. }
  492. if (value.length !== this.height) {
  493. throw new Error(`${this.constructor.name}.weights being set with improper value height`);
  494. }
  495. }
  496. }
  497. this._weights = value;
  498. }
  499. get deltas() {
  500. return this._deltas;
  501. }
  502. set deltas(value) {
  503. if (value) {
  504. if (value.dimensions) {
  505. if (value.dimensions[0] !== this.width) {
  506. throw new Error(`${this.constructor.name}.deltas being set with improper value width`);
  507. }
  508. if (value.dimensions[1] !== this.height) {
  509. throw new Error(`${this.constructor.name}.deltas being set with improper value height`);
  510. }
  511. } else {
  512. if (value[0].length !== this.width) {
  513. throw new Error(`${this.constructor.name}.deltas being set with improper value width`);
  514. }
  515. if (value.length !== this.height) {
  516. throw new Error(`${this.constructor.name}.deltas being set with improper value height`);
  517. }
  518. }
  519. }
  520. this._deltas = value;
  521. } */
  522. validate() {
  523. if (Number.isNaN(this.height)) {
  524. throw new Error(`${this.constructor.name} layer height is not a number`);
  525. }
  526. if (Number.isNaN(this.width)) {
  527. throw new Error(`${this.constructor.name} layer width is not a number`);
  528. }
  529. if (this.height < 1) {
  530. throw new Error(`${this.constructor.name} layer height is less than 1`);
  531. }
  532. if (this.width < 1) {
  533. throw new Error(`${this.constructor.name} layer width is less than 1`);
  534. }
  535. }
  536. setupKernels(isTraining) { }
  537. reuseKernels(layer) {
  538. if (layer.width !== this.width) {
  539. throw new Error(`${this.constructor.name} kernel width mismatch ${layer.width} is not ${this.width}`);
  540. }
  541. if (layer.height !== this.height) {
  542. throw new Error(`${this.constructor.name} kernel width mismatch ${layer.height} is not ${this.height}`);
  543. }
  544. if (layer.hasOwnProperty('predictKernel') && layer.predictKernel !== null) {
  545. if (!layer.predictKernel.immutable) {
  546. throw new Error(`${layer.constructor.name}.predictKernel is not reusable, set kernel.immutable = true`);
  547. }
  548. this.predictKernel = layer.predictKernel;
  549. }
  550. if (layer.hasOwnProperty('compareKernel') && layer.compareKernel !== null) {
  551. if (!layer.compareKernel.immutable) {
  552. throw new Error(`${layer.constructor.name}.compareKernel is not reusable, set kernel.immutable = true`);
  553. }
  554. this.compareKernel = layer.compareKernel;
  555. }
  556. this.praxis = layer.praxis;
  557. }
  558. predict(inputs) { }
  559. compare(targetValues) { }
  560. learn(learningRate) { }
  561. toArray() {
  562. return Array.isArray(this.weights)
  563. ? this.weights
  564. : this.weights.toArray();
  565. }
  566. toJSON() {
  567. return BaseLayer.toJSON(this);
  568. }
  569. static toJSON(layer) {
  570. const { weights } = layer;
  571. return {
  572. width: layer.width,
  573. height: layer.height,
  574. depth: layer.depth,
  575. weights: toUntypedArray((weights && weights instanceof gpu_js.Texture
  576. ? weights.toArray()
  577. : weights)),
  578. type: layer.constructor.name,
  579. praxisOpts: layer.praxis ? layer.praxis.toJSON() : null,
  580. };
  581. }
  582. }
  583. function toUntypedArray(weights) {
  584. if (weights === null)
  585. return null;
  586. if (Array.isArray(weights)) {
  587. if (typeof weights[0] === 'number') {
  588. return weights;
  589. }
  590. else if (Array.isArray(weights[0]) && typeof weights[0][0] === 'number') {
  591. return weights;
  592. }
  593. else if (Array.isArray(weights[0][0]) &&
  594. typeof weights[0][0][0] === 'number') {
  595. return weights;
  596. }
  597. else if (weights[0] instanceof Float32Array) {
  598. const matrix = weights;
  599. return matrix.map((row) => {
  600. return Array.from(row);
  601. });
  602. }
  603. else if (weights[0][0] instanceof Float32Array) {
  604. const cube = weights;
  605. return cube.map((matrix) => {
  606. return matrix.map((row) => {
  607. return Array.from(row);
  608. });
  609. });
  610. }
  611. }
  612. else if (weights) {
  613. return Array.from(weights);
  614. }
  615. throw new Error('unexpected value');
  616. }
  617. /**
  618. * Returns an array of zeros
  619. */
  620. function zeros$1(size) {
  621. return new Float32Array(size);
  622. }
  623. /**
  624. * Returns a 2D tensor(matrix) of zeros
  625. */
  626. function zeros2D(width, height) {
  627. const result = new Array(height);
  628. for (let y = 0; y < height; y++) {
  629. result[y] = zeros$1(width);
  630. }
  631. return result;
  632. }
  633. /**
  634. * Returns a 3D tensor of arrays
  635. */
  636. function zeros3D(width, height, depth) {
  637. const result = new Array(depth);
  638. for (let z = 0; z < depth; z++) {
  639. result[z] = zeros2D(width, height);
  640. }
  641. return result;
  642. }
  643. class Activation extends BaseLayer {
  644. constructor(inputLayer, settings) {
  645. super(settings);
  646. this.inputLayer = inputLayer;
  647. const { width, height, depth } = this;
  648. this.predictKernel = null;
  649. this.compareKernel = null;
  650. this.validate();
  651. if (depth > 0) {
  652. this.weights = zeros3D(width, height, depth);
  653. this.deltas = zeros3D(width, height, depth);
  654. }
  655. else if (height > 0) {
  656. this.weights = zeros2D(width, height);
  657. this.deltas = zeros2D(width, height);
  658. }
  659. this.setupPraxis();
  660. }
  661. get width() {
  662. return this.inputLayer.width;
  663. }
  664. get height() {
  665. return this.inputLayer.height;
  666. }
  667. get depth() {
  668. return this.inputLayer.depth;
  669. }
  670. }
  671. class Filter extends BaseLayer {
  672. constructor(settings, inputLayer) {
  673. super();
  674. this.settings = settings;
  675. this.inputLayer = inputLayer;
  676. }
  677. get width() {
  678. return this.inputLayer.width;
  679. }
  680. get height() {
  681. return this.inputLayer.height;
  682. }
  683. get depth() {
  684. return this.inputLayer.depth;
  685. }
  686. get filterCount() {
  687. return this.settings.filterCount;
  688. }
  689. get filterWidth() {
  690. return this.settings.filterWidth;
  691. }
  692. get filterHeight() {
  693. return this.settings.filterHeight;
  694. }
  695. get filters() {
  696. return this.settings.filters;
  697. }
  698. set filters(filters) {
  699. this.settings.filters = filters;
  700. }
  701. get filterDeltas() {
  702. return this.settings.filterDeltas;
  703. }
  704. set filterDeltas(filterDeltas) {
  705. this.settings.filterDeltas = filterDeltas;
  706. }
  707. }
  708. class Internal {
  709. constructor() {
  710. this.predictKernel = null;
  711. this.compareKernel = null;
  712. this.praxis = null;
  713. }
  714. get width() {
  715. return this.settings.width;
  716. }
  717. get height() {
  718. return this.settings.height;
  719. }
  720. get depth() {
  721. return this.settings.depth;
  722. }
  723. get weights() {
  724. return this.settings.weights;
  725. }
  726. set weights(weights) {
  727. this.settings.weights = weights;
  728. }
  729. get deltas() {
  730. return this.settings.deltas;
  731. }
  732. set deltas(deltas) {
  733. this.settings.deltas = deltas;
  734. }
  735. toJSON() {
  736. return BaseLayer.toJSON(this);
  737. }
  738. }
  739. class Modifier extends BaseLayer {
  740. constructor(inputLayer, settings) {
  741. super({
  742. ...settings,
  743. width: inputLayer.width,
  744. height: inputLayer.height,
  745. depth: inputLayer.depth,
  746. });
  747. this.inputLayer = inputLayer;
  748. }
  749. validate() {
  750. var _a;
  751. super.validate();
  752. if (this.width !== this.inputLayer.width) {
  753. throw new Error(`width of ${this.width} does not match inputLayer.width of ${this.inputLayer.width}`);
  754. }
  755. if (this.height !== this.inputLayer.height) {
  756. throw new Error(`height of ${this.height} does not match inputLayer.height of ${this.inputLayer.height}`);
  757. }
  758. if (this.depth !== ((_a = this.inputLayer.depth) !== null && _a !== void 0 ? _a : 0)) {
  759. throw new Error(`depth of ${this.depth} does not match inputLayer.depth of ${this.inputLayer.depth}`);
  760. }
  761. }
  762. }
  763. class Operator extends BaseLayer {
  764. constructor(inputLayer1, inputLayer2, settings) {
  765. super(settings);
  766. this.inputLayer1 = inputLayer1;
  767. this.inputLayer2 = inputLayer2;
  768. this.validate();
  769. this.weights = zeros2D(this.width, this.height);
  770. this.deltas = zeros2D(this.width, this.height);
  771. this.setupPraxis();
  772. }
  773. }
  774. function compare1D(weights, targetValues) {
  775. return weights[this.thread.y][this.thread.x] - targetValues[this.thread.x];
  776. }
  777. function compare2D$5(weights, targetValues) {
  778. return (weights[this.thread.y][this.thread.x] -
  779. targetValues[this.thread.y][this.thread.x]);
  780. }
  781. class Target extends BaseLayer {
  782. constructor(settings, inputLayer) {
  783. super(settings);
  784. this.inputLayer = inputLayer;
  785. this.validate();
  786. if (this.depth) {
  787. throw new Error('Target layer not implemented for depth');
  788. }
  789. else if (this.height) {
  790. this.weights = zeros2D(this.width, this.height);
  791. this.deltas = zeros2D(this.width, this.height);
  792. this.errors = zeros2D(this.width, this.height);
  793. }
  794. else {
  795. this.weights = zeros$1(this.width);
  796. this.deltas = zeros$1(this.width);
  797. this.errors = zeros$1(this.width);
  798. }
  799. }
  800. setupKernels() {
  801. if (this.width === 1) {
  802. this.compareKernel = makeKernel(compare1D, {
  803. output: [this.width, this.height],
  804. immutable: true,
  805. });
  806. }
  807. else {
  808. this.compareKernel = makeKernel(compare2D$5, {
  809. output: [this.width, this.height],
  810. immutable: true,
  811. });
  812. }
  813. }
  814. predict() {
  815. // TODO: should we clone here?
  816. // NOTE: this looks like it shouldn't be, but the weights are immutable, and this is where they are reused.
  817. release(this.weights);
  818. this.weights = clone(this.inputLayer.weights);
  819. }
  820. compare(targetValues) {
  821. // this is where weights attach to deltas
  822. // deltas will be zero on learn, so save it in error for comparing to mse later
  823. release(this.deltas);
  824. release(this.errors);
  825. release(this.inputLayer.deltas);
  826. this.deltas = this.compareKernel(this.weights, targetValues);
  827. this.inputLayer.deltas = clone(this.deltas);
  828. this.errors = clone(this.deltas);
  829. }
  830. setupPraxis() { }
  831. }
  832. function target(settings, inputLayer) {
  833. return new Target(settings, inputLayer);
  834. }
  835. // eslint-disable-next-line @typescript-eslint/no-extraneous-class
  836. class InternalModel {
  837. }
  838. // eslint-disable-next-line @typescript-eslint/no-extraneous-class
  839. class EntryPoint extends BaseLayer {
  840. }
  841. // eslint-disable-next-line @typescript-eslint/no-extraneous-class
  842. class Model extends BaseLayer {
  843. learn(learningRate) {
  844. // TODO: do we need to release here?
  845. const { weights: oldWeights } = this;
  846. if (!this.praxis)
  847. throw new Error('this.praxis not defined');
  848. this.weights = this.praxis.run(this, learningRate);
  849. release(oldWeights);
  850. }
  851. }
  852. /* Functions for turning sparse hashes into arrays and vice versa */
  853. const lookup = {
  854. /**
  855. * Performs `[{a: 1}, {b: 6, c: 7}] -> {a: 0, b: 1, c: 2}`
  856. * @param {Object} hashes
  857. * @returns {Object}
  858. */
  859. toTable(hashes) {
  860. const hash = hashes.reduce((memo, hash) => {
  861. return Object.assign(memo, hash);
  862. }, {});
  863. return lookup.toHash(hash);
  864. },
  865. /**
  866. * Performs `[{a: 1}, {b: 6, c: 7}] -> {a: 0, b: 1, c: 2}`
  867. */
  868. toTable2D(objects2D) {
  869. const table = {};
  870. let valueIndex = 0;
  871. for (let i = 0; i < objects2D.length; i++) {
  872. const objects = objects2D[i];
  873. for (let j = 0; j < objects.length; j++) {
  874. const object = objects[j];
  875. for (const p in object) {
  876. if (object.hasOwnProperty(p) && !table.hasOwnProperty(p)) {
  877. table[p] = valueIndex++;
  878. }
  879. }
  880. }
  881. }
  882. return table;
  883. },
  884. toInputTable2D(data) {
  885. const table = {};
  886. let tableIndex = 0;
  887. for (let dataIndex = 0; dataIndex < data.length; dataIndex++) {
  888. const input = data[dataIndex].input;
  889. for (let i = 0; i < input.length; i++) {
  890. const object = input[i];
  891. for (const p in object) {
  892. if (!object.hasOwnProperty(p))
  893. continue;
  894. if (!table.hasOwnProperty(p)) {
  895. table[p] = tableIndex++;
  896. }
  897. }
  898. }
  899. }
  900. return table;
  901. },
  902. toOutputTable2D(data) {
  903. const table = {};
  904. let tableIndex = 0;
  905. for (let dataIndex = 0; dataIndex < data.length; dataIndex++) {
  906. const output = data[dataIndex].output;
  907. for (let i = 0; i < output.length; i++) {
  908. const object = output[i];
  909. for (const p in object) {
  910. if (!object.hasOwnProperty(p))
  911. continue;
  912. if (!table.hasOwnProperty(p)) {
  913. table[p] = tableIndex++;
  914. }
  915. }
  916. }
  917. }
  918. return table;
  919. },
  920. /**
  921. * performs `{a: 6, b: 7} -> {a: 0, b: 1}`
  922. */
  923. toHash(hash) {
  924. const lookup = {};
  925. let index = 0;
  926. const keys = Object.keys(hash);
  927. for (let i = 0; i < keys.length; i++) {
  928. lookup[keys[i]] = index++;
  929. }
  930. return lookup;
  931. },
  932. /**
  933. * performs `{a: 0, b: 1}, {a: 6} -> [6, 0]`
  934. */
  935. toArray(lookup, object, arrayLength) {
  936. const result = new Float32Array(arrayLength);
  937. for (const p in lookup) {
  938. if (!lookup.hasOwnProperty(p))
  939. continue;
  940. result[lookup[p]] = object.hasOwnProperty(p) ? object[p] : 0;
  941. }
  942. return result;
  943. },
  944. toArrayShort(lookup, object) {
  945. const result = [];
  946. for (const p in lookup) {
  947. if (!lookup.hasOwnProperty(p))
  948. continue;
  949. if (!object.hasOwnProperty(p))
  950. break;
  951. result[lookup[p]] = object[p];
  952. }
  953. return Float32Array.from(result);
  954. },
  955. toArrays(lookup, objects, arrayLength) {
  956. const result = [];
  957. for (let i = 0; i < objects.length; i++) {
  958. result.push(this.toArray(lookup, objects[i], arrayLength));
  959. }
  960. return result;
  961. },
  962. /**
  963. * performs `{a: 0, b: 1}, [6, 7] -> {a: 6, b: 7}`
  964. * @param {Object} lookup
  965. * @param {Array} array
  966. * @returns {Object}
  967. */
  968. toObject(lookup, array) {
  969. const object = {};
  970. for (const p in lookup) {
  971. if (!lookup.hasOwnProperty(p))
  972. continue;
  973. object[p] = array[lookup[p]];
  974. }
  975. return object;
  976. },
  977. toObjectPartial(lookup, array, offset = 0, limit = 0) {
  978. const object = {};
  979. let i = 0;
  980. for (const p in lookup) {
  981. if (!lookup.hasOwnProperty(p))
  982. continue;
  983. if (offset > 0) {
  984. if (i++ < offset)
  985. continue;
  986. }
  987. if (limit > 0) {
  988. if (i++ >= limit)
  989. continue;
  990. }
  991. object[p] = array[lookup[p] - offset];
  992. }
  993. return object;
  994. },
  995. dataShape(data) {
  996. const shape = [];
  997. let lastData;
  998. if (data.hasOwnProperty('input')) {
  999. shape.push('datum');
  1000. lastData = data.input;
  1001. }
  1002. else if (Array.isArray(data)) {
  1003. if (data[0] &&
  1004. data[0].input) {
  1005. shape.push('array', 'datum');
  1006. lastData = data[0].input;
  1007. }
  1008. else if (Array.isArray(data[0])) {
  1009. shape.push('array');
  1010. lastData = data[0];
  1011. }
  1012. else {
  1013. lastData = data;
  1014. }
  1015. }
  1016. else {
  1017. lastData = data;
  1018. }
  1019. let p;
  1020. while (lastData) {
  1021. p = Object.keys(lastData)[0];
  1022. if (Array.isArray(lastData) ||
  1023. typeof lastData.buffer === 'object') {
  1024. shape.push('array');
  1025. const possibleNumber = lastData[parseInt(p)];
  1026. if (typeof possibleNumber === 'number') {
  1027. shape.push('number');
  1028. break;
  1029. }
  1030. else {
  1031. lastData = possibleNumber;
  1032. }
  1033. }
  1034. else if (typeof lastData === 'object' &&
  1035. typeof lastData.buffer !== 'object') {
  1036. shape.push('object');
  1037. const possibleNumber = lastData[p];
  1038. if (typeof possibleNumber === 'number') {
  1039. shape.push('number');
  1040. break;
  1041. }
  1042. else {
  1043. lastData = possibleNumber;
  1044. }
  1045. }
  1046. else {
  1047. throw new Error('unhandled signature');
  1048. }
  1049. }
  1050. return shape;
  1051. },
  1052. addKeys(value, table) {
  1053. if (Array.isArray(value))
  1054. return table;
  1055. let i = Object.keys(table).length;
  1056. for (const p in value) {
  1057. if (!value.hasOwnProperty(p))
  1058. continue;
  1059. if (table.hasOwnProperty(p))
  1060. continue;
  1061. table[p] = i++;
  1062. }
  1063. return table;
  1064. },
  1065. };
  1066. class BasePraxis {
  1067. constructor(layerTemplate, settings = {}) {
  1068. this.layerTemplate = layerTemplate;
  1069. this.settings = { ...settings };
  1070. this.kernel = null;
  1071. }
  1072. get width() {
  1073. return this.layerTemplate.width;
  1074. }
  1075. get height() {
  1076. return this.layerTemplate.height;
  1077. }
  1078. get depth() {
  1079. return this.layerTemplate.depth;
  1080. }
  1081. setupKernels() { }
  1082. reuseKernels(praxis) {
  1083. if (praxis.width !== this.width) {
  1084. throw new Error(`${this.constructor.name} kernel width mismatch ${praxis.width} is not ${this.width}`);
  1085. }
  1086. if (praxis.height !== this.height) {
  1087. throw new Error(`${this.constructor.name} kernel width mismatch ${praxis.height} is not ${this.height}`);
  1088. }
  1089. if (praxis.hasOwnProperty('kernel')) {
  1090. this.kernel = praxis.kernel;
  1091. }
  1092. }
  1093. toJSON() {
  1094. return { ...this.settings };
  1095. }
  1096. }
  1097. function update$2(weights, deltas) {
  1098. return (weights[this.thread.y][this.thread.x] +
  1099. this.constants.learningRate * deltas[this.thread.y][this.thread.x]);
  1100. }
  1101. const defaultSettings$1 = {
  1102. learningRate: 0.3,
  1103. };
  1104. class ArthurDeviationBiases extends BasePraxis {
  1105. constructor(layer, settings) {
  1106. super(layer);
  1107. this.settings = { ...defaultSettings$1, ...settings };
  1108. this.kernel = null;
  1109. }
  1110. run(layer) {
  1111. return this.kernel(layer.weights, layer.deltas);
  1112. }
  1113. setupKernels() {
  1114. this.kernel = makeKernel(update$2, {
  1115. output: [this.width, this.height],
  1116. constants: {
  1117. learningRate: this.settings.learningRate,
  1118. },
  1119. });
  1120. }
  1121. }
  1122. function arthurDeviationBiases(layer, settings) {
  1123. return new ArthurDeviationBiases(layer, settings);
  1124. }
  1125. function updateChange(value) {
  1126. return value;
  1127. }
  1128. function update$1(changes, weights, incomingWeights, inputDeltas) {
  1129. const lastChange = changes[this.thread.y][this.thread.x];
  1130. const inputDelta = inputDeltas[this.thread.y][0];
  1131. const weight = weights[this.thread.y][this.thread.x];
  1132. const incoming = incomingWeights[this.thread.x][0];
  1133. const change = this.constants.learningRate * inputDelta * incoming +
  1134. this.constants.momentum * lastChange;
  1135. return weight + change;
  1136. }
  1137. const defaultSettings = {
  1138. learningRate: 0.3,
  1139. momentum: 0.1,
  1140. weightsLayer: null,
  1141. incomingLayer: null,
  1142. deltaLayer: null,
  1143. };
  1144. class ArthurDeviationWeights extends BasePraxis {
  1145. constructor(layer, settings) {
  1146. super(layer);
  1147. this.kernelMap = null;
  1148. this.settings = { ...defaultSettings, ...settings };
  1149. this.changes = zeros2D(layer.width, layer.height);
  1150. }
  1151. get learningRate() {
  1152. return this.settings.learningRate;
  1153. }
  1154. get momentum() {
  1155. return this.settings.momentum;
  1156. }
  1157. get weightsLayer() {
  1158. return this.settings.weightsLayer;
  1159. }
  1160. set weightsLayer(layer) {
  1161. this.settings.weightsLayer = layer;
  1162. }
  1163. get deltaLayer() {
  1164. return this.settings.deltaLayer;
  1165. }
  1166. set deltaLayer(layer) {
  1167. this.settings.deltaLayer = layer;
  1168. }
  1169. get incomingLayer() {
  1170. return this.settings.incomingLayer;
  1171. }
  1172. set incomingLayer(layer) {
  1173. this.settings.incomingLayer = layer;
  1174. }
  1175. run() {
  1176. const output = this.kernelMap(this.changes, this.weightsLayer.weights, this.incomingLayer.weights, this.deltaLayer.deltas);
  1177. this.changes = output.changes;
  1178. return output.result;
  1179. }
  1180. setupKernels() {
  1181. this.kernelMap = makeKernelMap({
  1182. changes: updateChange,
  1183. }, update$1, {
  1184. output: [this.width, this.height],
  1185. constants: {
  1186. learningRate: this.learningRate,
  1187. momentum: this.momentum,
  1188. },
  1189. });
  1190. }
  1191. }
  1192. function arthurDeviationWeights(layer, settings) {
  1193. return new ArthurDeviationWeights(layer, settings);
  1194. }
  1195. function getMomentum(delta, decay, previousMomentum) {
  1196. return previousMomentum * decay + (1 - decay) * delta * delta;
  1197. }
  1198. function clipByValue(value, max, min) {
  1199. if (value > max) {
  1200. return max;
  1201. }
  1202. if (value < min) {
  1203. return min;
  1204. }
  1205. return value;
  1206. }
  1207. /**
  1208. * @description Momentum Root Mean Square Propagation Function
  1209. */
  1210. function update(weights, deltas, previousMomenta) {
  1211. const delta = deltas[this.thread.y][this.thread.x];
  1212. const clippedDelta = clipByValue(delta, this.constants.clipValue, -this.constants.clipValue);
  1213. const weight = weights[this.thread.y][this.thread.x];
  1214. const previousMomentum = previousMomenta[this.thread.y][this.thread.x];
  1215. const momentum = getMomentum(delta, this.constants.decayRate, previousMomentum);
  1216. return (weight +
  1217. (-this.constants.learningRate * clippedDelta) /
  1218. Math.sqrt(momentum + this.constants.smoothEps) -
  1219. this.constants.regularizationStrength * weight);
  1220. }
  1221. const defaults$8 = {
  1222. decayRate: 0.999,
  1223. regularizationStrength: 0.000001,
  1224. learningRate: 0.01,
  1225. smoothEps: 1e-8,
  1226. clipValue: 5,
  1227. };
  1228. class MomentumRootMeanSquaredPropagation extends BasePraxis {
  1229. constructor(layerTemplate, settings = {}) {
  1230. super(layerTemplate);
  1231. this.kernelMap = null;
  1232. this.settings = { ...defaults$8, ...settings };
  1233. this.momenta = zeros2D(layerTemplate.width, layerTemplate.height);
  1234. }
  1235. get clipValue() {
  1236. return this.settings.clipValue;
  1237. }
  1238. get decayRate() {
  1239. return this.settings.decayRate;
  1240. }
  1241. get learningRate() {
  1242. return this.settings.learningRate;
  1243. }
  1244. get regularizationStrength() {
  1245. return this.settings.regularizationStrength;
  1246. }
  1247. get smoothEps() {
  1248. return this.settings.smoothEps;
  1249. }
  1250. run(layer) {
  1251. const { momenta, result } = this.kernelMap(layer.weights, layer.deltas, this.momenta);
  1252. release(this.momenta);
  1253. this.momenta = momenta;
  1254. return result;
  1255. }
  1256. setupKernels() {
  1257. this.kernelMap = makeKernelMap({
  1258. momenta: getMomentum,
  1259. }, update, {
  1260. output: [this.width, this.height],
  1261. constants: {
  1262. clipValue: this.clipValue,
  1263. decayRate: this.decayRate,
  1264. learningRate: this.learningRate,
  1265. regularizationStrength: this.regularizationStrength,
  1266. smoothEps: this.smoothEps,
  1267. },
  1268. functions: [clipByValue],
  1269. immutable: true,
  1270. });
  1271. }
  1272. }
  1273. function momentumRootMeanSquaredPropagation(layer, settings) {
  1274. return new MomentumRootMeanSquaredPropagation(layer, settings);
  1275. }
  1276. /**
  1277. * @description Mathematician friendly name of MomentumRootMeanSquaredPropagation class. For those that are not mere mortals
  1278. */
  1279. const MRmsProp = MomentumRootMeanSquaredPropagation;
  1280. const mRmsProp = momentumRootMeanSquaredPropagation;
  1281. var index = /*#__PURE__*/Object.freeze({
  1282. __proto__: null,
  1283. ArthurDeviationBiases: ArthurDeviationBiases,
  1284. arthurDeviationBiases: arthurDeviationBiases,
  1285. ArthurDeviationWeights: ArthurDeviationWeights,
  1286. arthurDeviationWeights: arthurDeviationWeights,
  1287. MomentumRootMeanSquaredPropagation: MomentumRootMeanSquaredPropagation,
  1288. momentumRootMeanSquaredPropagation: momentumRootMeanSquaredPropagation,
  1289. MRmsProp: MRmsProp,
  1290. mRmsProp: mRmsProp
  1291. });
  1292. function traverseLayersFrom(layer, cb) {
  1293. if (layer.hasOwnProperty('inputLayer')) {
  1294. traverseLayersFrom(layer.inputLayer, cb);
  1295. }
  1296. else {
  1297. if (layer.hasOwnProperty('inputLayer1')) {
  1298. traverseLayersFrom(layer.inputLayer1, cb);
  1299. }
  1300. if (layer.hasOwnProperty('inputLayer2')) {
  1301. traverseLayersFrom(layer.inputLayer2, cb);
  1302. }
  1303. }
  1304. cb(layer);
  1305. }
  1306. function flattenLayers(layers) {
  1307. const result = layers.slice(0);
  1308. for (let i = 0; i < result.length; i++) {
  1309. let offset = 0;
  1310. traverseLayersFrom(result[i], (layer) => {
  1311. if (!result.includes(layer)) {
  1312. result.splice(i + offset, 0, layer);
  1313. offset++;
  1314. }
  1315. });
  1316. }
  1317. return result;
  1318. }
  1319. function checkSameSize(layer1, layer2) {
  1320. if (layer1.width !== layer2.width) {
  1321. throw new Error(`Layer width mismatch of ${layer1.width} and ${layer2.width}`);
  1322. }
  1323. if (layer1.height !== layer2.height) {
  1324. throw new Error(`Layer height mismatch of ${layer1.height} and ${layer2.height}`);
  1325. }
  1326. }
  1327. function predict$8(inputWeights1, inputWeights2) {
  1328. return (inputWeights1[this.thread.y][this.thread.x] +
  1329. inputWeights2[this.thread.y][this.thread.x]);
  1330. }
  1331. class Add extends Operator {
  1332. get width() {
  1333. return this.inputLayer1.width;
  1334. }
  1335. get height() {
  1336. return this.inputLayer1.height;
  1337. }
  1338. get depth() {
  1339. return this.inputLayer1.depth;
  1340. }
  1341. validate() {
  1342. super.validate();
  1343. checkSameSize(this.inputLayer1, this.inputLayer2);
  1344. }
  1345. setupKernels() {
  1346. this.predictKernel = makeKernel(predict$8, {
  1347. output: [this.width, this.height],
  1348. immutable: true,
  1349. });
  1350. }
  1351. predict() {
  1352. release(this.weights);
  1353. this.weights = this.predictKernel(this.inputLayer1.weights, this.inputLayer2.weights);
  1354. }
  1355. compare() {
  1356. // TODO: Do we need release and clone here?
  1357. release(this.inputLayer1.deltas);
  1358. release(this.inputLayer2.deltas);
  1359. this.inputLayer1.deltas = clone(this.deltas);
  1360. this.inputLayer2.deltas = clone(this.deltas);
  1361. }
  1362. }
  1363. function add$1(inputLayer1, inputLayer2, settings) {
  1364. return new Add(inputLayer1, inputLayer2, settings);
  1365. }
  1366. function randomWeight() {
  1367. return Math.random() * 0.4 - 0.2;
  1368. }
  1369. /**
  1370. * Returns a random float between given min and max bounds (inclusive)
  1371. * @param min Minimum value of the ranfom float
  1372. * @param max Maximum value of the random float
  1373. */
  1374. function randomFloat(min, max) {
  1375. return Math.random() * (max - min) + min;
  1376. }
  1377. /**
  1378. * Complicated math. All you need to know is that it returns a random number.
  1379. * More info: https://en.wikipedia.org/wiki/Normal_distribution
  1380. */
  1381. function gaussRandom() {
  1382. if (gaussRandom.returnV) {
  1383. gaussRandom.returnV = false;
  1384. return gaussRandom.vVal;
  1385. }
  1386. const u = 2 * Math.random() - 1;
  1387. const v = 2 * Math.random() - 1;
  1388. const r = u * u + v * v;
  1389. if (r === 0 || r > 1) {
  1390. return gaussRandom();
  1391. }
  1392. const c = Math.sqrt((-2 * Math.log(r)) / r);
  1393. gaussRandom.vVal = v * c; // cache this
  1394. gaussRandom.returnV = true;
  1395. return u * c;
  1396. }
  1397. /**
  1398. * Returns a random integer between given min and max bounds
  1399. * @param min Minimum value of the random integer
  1400. * @param max Maximum value of the random integer
  1401. */
  1402. function randomInteger(min, max) {
  1403. return Math.floor(Math.random() * (max - min) + min);
  1404. }
  1405. /**
  1406. * If you know what this is: https://en.wikipedia.org/wiki/Normal_distribution
  1407. * @param mu
  1408. * @param std
  1409. */
  1410. function randomN(mu, std) {
  1411. return mu + gaussRandom() * std;
  1412. }
  1413. gaussRandom.returnV = false;
  1414. gaussRandom.vVal = 0;
  1415. var random$1 = /*#__PURE__*/Object.freeze({
  1416. __proto__: null,
  1417. randomFloat: randomFloat,
  1418. gaussRandom: gaussRandom,
  1419. randomInteger: randomInteger,
  1420. randomN: randomN
  1421. });
  1422. /**
  1423. * Returns an array of given size, full of randomness
  1424. */
  1425. function randos(size, std = null) {
  1426. const array = new Float32Array(size);
  1427. if (std === null) {
  1428. for (let i = 0; i < size; i++) {
  1429. array[i] = randomWeight();
  1430. }
  1431. }
  1432. else {
  1433. for (let i = 0; i < size; i++) {
  1434. array[i] = randomFloat(-std, std);
  1435. }
  1436. }
  1437. return array;
  1438. }
  1439. /**
  1440. * Returns a 2D matrix of given size, full of randomness
  1441. */
  1442. function randos2D(width, height, std) {
  1443. const result = new Array(height);
  1444. for (let y = 0; y < height; y++) {
  1445. result[y] = randos(width, std);
  1446. }
  1447. return result;
  1448. }
  1449. /**
  1450. * Returns a 3D tensor of given size, full of randomness
  1451. */
  1452. function randos3D(width, height, depth, std) {
  1453. const result = new Array(depth);
  1454. for (let z = 0; z < depth; z++) {
  1455. result[z] = randos2D(width, height, std);
  1456. }
  1457. return result;
  1458. }
  1459. const defaults$7 = {
  1460. ...baseLayerDefaultSettings,
  1461. std: null,
  1462. };
  1463. class Random extends Model {
  1464. constructor(settings) {
  1465. super();
  1466. this.settings = { ...defaults$7, ...settings };
  1467. this.setupPraxis();
  1468. this.validate();
  1469. if (!this.weights) {
  1470. this.weights = randos2D(this.width, this.height, settings.std);
  1471. }
  1472. if (!this.deltas) {
  1473. this.deltas = zeros2D(this.width, this.height);
  1474. }
  1475. }
  1476. predict() { }
  1477. compare() { }
  1478. }
  1479. function random(settings) {
  1480. return new Random(settings);
  1481. }
  1482. function predict$7(weights1, weights2) {
  1483. let sum = 0;
  1484. for (let i = 0; i < this.constants.size; i++) {
  1485. sum += weights1[this.thread.y][i] * weights2[i][this.thread.x];
  1486. }
  1487. return sum;
  1488. }
  1489. function compareFromX(deltas, inputDeltas, inputWeights) {
  1490. let sum = inputDeltas[this.thread.y][this.thread.x];
  1491. for (let i = 0; i < this.constants.size; i++) {
  1492. sum += deltas[this.thread.y][i] * inputWeights[this.thread.x][i];
  1493. }
  1494. return sum;
  1495. }
  1496. function compareFromY(deltas, inputDeltas, inputWeights) {
  1497. let sum = inputDeltas[this.thread.y][this.thread.x];
  1498. for (let i = 0; i < this.constants.size; i++) {
  1499. sum += deltas[i][this.thread.x] * inputWeights[i][this.thread.y];
  1500. }
  1501. return sum;
  1502. }
  1503. class Multiply extends Operator {
  1504. constructor() {
  1505. super(...arguments);
  1506. this.compareKernel1 = null;
  1507. this.compareKernel2 = null;
  1508. }
  1509. get width() {
  1510. return this.inputLayer2.width;
  1511. }
  1512. set width(width) {
  1513. throw new Error('Cannot set width on Multiply');
  1514. }
  1515. get height() {
  1516. return this.inputLayer1.height;
  1517. }
  1518. set height(height) {
  1519. throw new Error('Cannot set height on Multiply');
  1520. }
  1521. get depth() {
  1522. return this.inputLayer1.depth;
  1523. }
  1524. set depth(depth) {
  1525. throw new Error('Cannot set depth on Multiply');
  1526. }
  1527. validate() {
  1528. super.validate();
  1529. if (this.inputLayer1.width !== this.inputLayer2.height) {
  1530. throw new Error(`Layer width mismatch of ${this.inputLayer1.width} and ${this.inputLayer2.height}`);
  1531. }
  1532. }
  1533. setupKernels() {
  1534. this.predictKernel = makeKernel(predict$7, {
  1535. output: [this.width, this.height],
  1536. constants: {
  1537. size: this.inputLayer2.height,
  1538. },
  1539. immutable: true,
  1540. });
  1541. this.compareKernel1 = makeKernel(compareFromX, {
  1542. output: [this.inputLayer1.width, this.inputLayer1.height],
  1543. constants: {
  1544. size: this.inputLayer2.width,
  1545. },
  1546. immutable: true,
  1547. });
  1548. this.compareKernel2 = makeKernel(compareFromY, {
  1549. output: [this.inputLayer2.width, this.inputLayer2.height],
  1550. constants: {
  1551. size: this.inputLayer1.height,
  1552. },
  1553. immutable: true,
  1554. });
  1555. }
  1556. reuseKernels(layer) {
  1557. super.reuseKernels(layer);
  1558. this.compareKernel1 = layer.compareKernel1;
  1559. this.compareKernel2 = layer.compareKernel2;
  1560. }
  1561. predict() {
  1562. release(this.weights);
  1563. if (!this.predictKernel)
  1564. throw new Error('this.predictKernel is not set');
  1565. this.weights = this.predictKernel(this.inputLayer1.weights, this.inputLayer2.weights);
  1566. }
  1567. compare() {
  1568. if (!this.compareKernel1)
  1569. throw new Error('this.compareKernel1 not set');
  1570. if (!this.compareKernel2)
  1571. throw new Error('this.compareKernel2 not set');
  1572. const inputLayer1Deltas = this.inputLayer1.deltas;
  1573. const inputLayer2Deltas = this.inputLayer2.deltas;
  1574. const newDeltas1 = this.compareKernel1(this.deltas, this.inputLayer1.deltas, this.inputLayer2.weights);
  1575. const newDeltas2 = this.compareKernel2(this.deltas, this.inputLayer2.deltas, this.inputLayer1.weights);
  1576. this.inputLayer2.deltas = newDeltas2;
  1577. this.inputLayer1.deltas = newDeltas1;
  1578. release(inputLayer1Deltas);
  1579. release(inputLayer2Deltas);
  1580. }
  1581. setupPraxis() { }
  1582. toJSON() {
  1583. return {
  1584. ...super.toJSON(),
  1585. width: this.width,
  1586. height: this.height,
  1587. };
  1588. }
  1589. }
  1590. function multiply$1(inputLayer1, inputLayer2, settings) {
  1591. return new Multiply(inputLayer1, inputLayer2, settings);
  1592. }
  1593. function predict2D$4(inputs) {
  1594. return 1 / (1 + Math.exp(-inputs[this.thread.y][this.thread.x]));
  1595. }
  1596. function predict3D$5(inputs) {
  1597. return (1 / (1 + Math.exp(-inputs[this.thread.z][this.thread.y][this.thread.x])));
  1598. }
  1599. function compare2D$4(weights, deltas) {
  1600. const weight = weights[this.thread.y][this.thread.x];
  1601. const delta = deltas[this.thread.y][this.thread.x];
  1602. return weight * (1 - weight) * delta;
  1603. }
  1604. function compare3D$4(weights, deltas) {
  1605. const weight = weights[this.thread.z][this.thread.y][this.thread.x];
  1606. const delta = deltas[this.thread.z][this.thread.y][this.thread.x];
  1607. return weight * (1 - weight) * delta;
  1608. }
  1609. class Sigmoid extends Activation {
  1610. setupKernels() {
  1611. if (this.depth > 0) {
  1612. this.predictKernel = makeKernel(predict3D$5, {
  1613. output: [this.width, this.height, this.depth],
  1614. functions: [activate$2],
  1615. immutable: true,
  1616. });
  1617. this.compareKernel = makeKernel(compare3D$4, {
  1618. output: [this.width, this.height, this.depth],
  1619. functions: [measure$2],
  1620. immutable: true,
  1621. });
  1622. }
  1623. else {
  1624. this.predictKernel = makeKernel(predict2D$4, {
  1625. output: [this.width, this.height],
  1626. functions: [activate$2],
  1627. immutable: true,
  1628. });
  1629. this.compareKernel = makeKernel(compare2D$4, {
  1630. output: [this.width, this.height],
  1631. functions: [measure$2],
  1632. immutable: true,
  1633. });
  1634. }
  1635. }
  1636. predict() {
  1637. release(this.weights);
  1638. this.weights = this.predictKernel(this.inputLayer.weights);
  1639. }
  1640. compare() {
  1641. release(this.inputLayer.deltas);
  1642. this.inputLayer.deltas = this.compareKernel(this.weights, this.deltas);
  1643. }
  1644. learn(learningRate) { }
  1645. }
  1646. function sigmoid$1(inputLayer, settings) {
  1647. return new Sigmoid(inputLayer, settings);
  1648. }
  1649. function arthurFeedForward(settings, inputLayer) {
  1650. const { height } = settings;
  1651. function initWeightsPraxis(layerTemplate, settings) {
  1652. const praxis = arthurDeviationWeights(layerTemplate, settings);
  1653. praxis.setupKernels();
  1654. return praxis;
  1655. }
  1656. function initBiasesPraxis(layerTemplate, settings) {
  1657. const praxis = arthurDeviationBiases(layerTemplate, settings);
  1658. praxis.setupKernels();
  1659. return praxis;
  1660. }
  1661. const weightsLayer = random({
  1662. id: 'weights',
  1663. height,
  1664. width: inputLayer.height,
  1665. initPraxis: initWeightsPraxis,
  1666. });
  1667. const biasesLayer = random({
  1668. id: 'biases',
  1669. height,
  1670. initPraxis: initBiasesPraxis,
  1671. });
  1672. const multiplyLayer = multiply$1(weightsLayer, inputLayer);
  1673. const addLayer = add$1(multiplyLayer, biasesLayer);
  1674. const sigmoidLayer = sigmoid$1(addLayer);
  1675. const weightsPraxis = weightsLayer.praxis;
  1676. weightsPraxis.weightsLayer = weightsLayer;
  1677. weightsPraxis.incomingLayer = inputLayer;
  1678. weightsPraxis.deltaLayer = sigmoidLayer;
  1679. return sigmoidLayer;
  1680. }
  1681. function getStride(settings, defaults) {
  1682. if (typeof settings.stride === 'number') {
  1683. return { strideX: settings.stride, strideY: settings.stride };
  1684. }
  1685. else {
  1686. let strideX = defaults.stride;
  1687. let strideY = defaults.stride;
  1688. if (typeof settings.strideX === 'number') {
  1689. strideX = settings.strideX;
  1690. }
  1691. if (typeof settings.strideY === 'number') {
  1692. strideY = settings.strideY;
  1693. }
  1694. return { strideX, strideY };
  1695. }
  1696. }
  1697. function getPadding(settings, defaults) {
  1698. if (typeof settings.padding === 'number') {
  1699. return { paddingX: settings.padding, paddingY: settings.padding };
  1700. }
  1701. else {
  1702. let paddingX = defaults.padding;
  1703. let paddingY = defaults.padding;
  1704. if (typeof settings.paddingX === 'number') {
  1705. paddingX = settings.paddingX;
  1706. }
  1707. if (typeof settings.paddingY === 'number') {
  1708. paddingY = settings.paddingY;
  1709. }
  1710. return { paddingX, paddingY };
  1711. }
  1712. }
  1713. /**
  1714. * Returns an array of a given size with each element filled with a single value
  1715. */
  1716. function values(size, value) {
  1717. return new Float32Array(size).fill(value);
  1718. }
  1719. function predict$6(inputs, filters, biases) {
  1720. const startFilterX = this.constants.paddingX - this.thread.x * this.constants.strideX;
  1721. const startInputX = this.thread.x * this.constants.strideX - this.constants.paddingX;
  1722. const endFilterX = Math.min(this.constants.filterWidth, startFilterX + this.constants.inputWidth);
  1723. const startFilterY = this.constants.paddingY - this.thread.y * this.constants.strideY;
  1724. const startInputY = this.thread.y * this.constants.strideY - this.constants.paddingY;
  1725. const endFilterY = Math.min(this.constants.filterHeight, startFilterY + this.constants.inputHeight);
  1726. let sum = 0;
  1727. for (let z = 0; z < this.constants.inputDepth; z++) {
  1728. for (let filterY = Math.max(0, startFilterY), inputY = Math.max(0, startInputY); filterY < endFilterY; filterY++, inputY++) {
  1729. for (let filterX = Math.max(0, startFilterX), inputX = Math.max(0, startInputX); filterX < endFilterX; filterX++, inputX++) {
  1730. sum += filters[z][filterY][filterX] * inputs[z][inputY][inputX];
  1731. }
  1732. }
  1733. }
  1734. return sum + biases[this.thread.z];
  1735. }
  1736. function compareFilterDeltas$1(filterDeltas, inputs, deltas) {
  1737. const startDeltaX = Math.max(0, Math.ceil((this.constants.paddingX - this.thread.x) / this.constants.strideX));
  1738. const startInputX = startDeltaX * this.constants.strideX +
  1739. this.thread.x -
  1740. this.constants.paddingX;
  1741. const endDeltaX = Math.min(this.constants.deltaWidth, Math.floor((this.constants.inputWidth -
  1742. 1 -
  1743. this.thread.x +
  1744. this.constants.paddingX) /
  1745. this.constants.strideX) + 1);
  1746. const startDeltaY = Math.max(0, Math.ceil((this.constants.paddingY - this.thread.y) / this.constants.strideY));
  1747. const startInputY = startDeltaY * this.constants.strideY +
  1748. this.thread.y -
  1749. this.constants.paddingY;
  1750. const endDeltaY = Math.min(this.constants.deltaHeight, Math.floor((this.constants.inputHeight -
  1751. 1 -
  1752. this.thread.y +
  1753. this.constants.paddingY) /
  1754. this.constants.strideY) + 1);
  1755. let sum = filterDeltas[this.thread.z][this.thread.y][this.thread.x];
  1756. for (let deltaY = startDeltaY, inputY = startInputY; deltaY < endDeltaY; deltaY++, inputY += this.constants.strideY) {
  1757. for (let deltaX = startDeltaX, inputX = startInputX; deltaX < endDeltaX; deltaX++, inputX += this.constants.strideX) {
  1758. sum +=
  1759. inputs[this.thread.z][inputY][inputX] *
  1760. deltas[this.constants.deltaZ][deltaY][deltaX];
  1761. }
  1762. }
  1763. return sum;
  1764. }
  1765. function compareInputDeltas$1(inputDeltas, filters, deltas) {
  1766. const x = this.thread.x + this.constants.paddingX;
  1767. const startDeltaX = x < this.constants.filterWidth
  1768. ? 0
  1769. : Math.floor((x - this.constants.filterWidth + this.constants.strideX) /
  1770. this.constants.strideX);
  1771. const startFilterX = x - startDeltaX * this.constants.strideX;
  1772. const endDeltaX = Math.min(startDeltaX + Math.floor(startFilterX / this.constants.strideX) + 1, this.constants.deltaWidth);
  1773. const y = this.thread.y + this.constants.paddingY;
  1774. const startDeltaY = y < this.constants.filterHeight
  1775. ? 0
  1776. : Math.floor((y - this.constants.filterHeight + this.constants.strideY) /
  1777. this.constants.strideY);
  1778. const startFilterY = y - startDeltaY * this.constants.strideY;
  1779. const endDeltaY = Math.min(startDeltaY + Math.floor(startFilterY / this.constants.strideY) + 1, this.constants.deltaHeight);
  1780. let sum = inputDeltas[this.thread.z][this.thread.y][this.thread.x];
  1781. let deltaY = startDeltaY;
  1782. for (let filterY = startFilterY; deltaY < endDeltaY; filterY -= this.constants.strideY, deltaY++) {
  1783. let deltaX = startDeltaX;
  1784. for (let filterX = startFilterX; deltaX < endDeltaX; filterX -= this.constants.strideX, deltaX++) {
  1785. sum +=
  1786. filters[this.thread.z][filterY][filterX] *
  1787. deltas[this.constants.deltaZ][deltaY][deltaX];
  1788. }
  1789. }
  1790. return sum;
  1791. }
  1792. function compareBiases$1(biasDeltas, deltas) {
  1793. let sum = 0;
  1794. for (let y = 0; y < this.constants.deltaHeight; y++) {
  1795. for (let x = 0; x < this.constants.deltaWidth; x++) {
  1796. sum += deltas[this.thread.z][y][x];
  1797. }
  1798. }
  1799. return biasDeltas[this.thread.z][this.thread.y][this.thread.x] + sum;
  1800. }
  1801. const defaults$6 = {
  1802. stride: 0,
  1803. padding: 0,
  1804. bias: 0.1,
  1805. filterCount: 1,
  1806. filterWidth: 0,
  1807. filterHeight: 0,
  1808. };
  1809. class Convolution extends Filter {
  1810. constructor(settings, inputLayer) {
  1811. var _a, _b, _c;
  1812. super(settings, inputLayer);
  1813. this.compareFilterDeltasKernel = null;
  1814. this.compareInputDeltasKernel = null;
  1815. this.compareBiasesKernel = null;
  1816. this.settings = {
  1817. ...defaults$6,
  1818. ...settings,
  1819. ...getPadding(settings, defaults$6),
  1820. ...getStride(settings, defaults$6),
  1821. };
  1822. this.weights = (_a = settings.weights) !== null && _a !== void 0 ? _a : randos3D(this.width, this.height, this.depth);
  1823. this.deltas = zeros3D(this.width, this.height, this.depth);
  1824. this.biases = values(this.depth, this.bias);
  1825. this.biasDeltas = (_b = settings.biasDeltas) !== null && _b !== void 0 ? _b : randos(this.depth);
  1826. this.filters = (_c = settings.filters) !== null && _c !== void 0 ? _c : randos3D(this.filterWidth, this.filterHeight, this.filterCount);
  1827. this.filterDeltas = zeros3D(this.filterWidth, this.filterHeight, this.filterCount);
  1828. this.validate();
  1829. }
  1830. get strideX() {
  1831. return this.settings.strideX;
  1832. }
  1833. get strideY() {
  1834. return this.settings.strideY;
  1835. }
  1836. get paddingX() {
  1837. return this.settings.paddingX;
  1838. }
  1839. get paddingY() {
  1840. return this.settings.paddingX;
  1841. }
  1842. get width() {
  1843. return Math.floor((this.inputLayer.width + this.paddingX * 2 - this.filterWidth) /
  1844. this.strideX +
  1845. 1);
  1846. }
  1847. get height() {
  1848. return Math.floor((this.inputLayer.height + this.paddingY * 2 - this.filterHeight) /
  1849. this.strideY +
  1850. 1);
  1851. }
  1852. get bias() {
  1853. return this.settings.bias;
  1854. }
  1855. get depth() {
  1856. return this.filterCount;
  1857. }
  1858. get biases() {
  1859. return this.settings.biases;
  1860. }
  1861. set biases(biases) {
  1862. this.settings.biases = biases;
  1863. }
  1864. get biasDeltas() {
  1865. return this.settings.biasDeltas;
  1866. }
  1867. set biasDeltas(weights) {
  1868. this.settings.biasDeltas = weights;
  1869. }
  1870. get filters() {
  1871. return this.settings.filters;
  1872. }
  1873. set filters(filters) {
  1874. this.settings.filters = filters;
  1875. }
  1876. get filterDeltas() {
  1877. return this.settings.filterDeltas;
  1878. }
  1879. set filterDeltas(filterDeltas) {
  1880. this.settings.filterDeltas = filterDeltas;
  1881. }
  1882. setupKernels() {
  1883. this.predictKernel = makeKernel(predict$6, {
  1884. constants: {
  1885. inputWidth: this.inputLayer.width,
  1886. inputHeight: this.inputLayer.height,
  1887. inputDepth: this.inputLayer.depth,
  1888. strideX: this.strideX,
  1889. strideY: this.strideY,
  1890. paddingX: this.paddingX,
  1891. paddingY: this.paddingY,
  1892. filterWidth: this.filterWidth,
  1893. filterHeight: this.filterHeight,
  1894. },
  1895. output: [this.width, this.height, this.depth],
  1896. immutable: true,
  1897. });
  1898. this.compareFilterDeltasKernel = makeKernel(compareFilterDeltas$1, {
  1899. constants: {
  1900. deltasWidth: this.width,
  1901. deltasHeight: this.height,
  1902. deltasDepth: this.depth,
  1903. inputWidth: this.inputLayer.width,
  1904. inputHeight: this.inputLayer.height,
  1905. inputDepth: this.inputLayer.depth,
  1906. strideX: this.strideX,
  1907. strideY: this.strideY,
  1908. paddingX: this.paddingX,
  1909. paddingY: this.paddingY,
  1910. filterWidth: this.filterWidth,
  1911. filterHeight: this.filterHeight,
  1912. },
  1913. output: [this.width, this.height, this.depth],
  1914. immutable: true,
  1915. });
  1916. this.compareInputDeltasKernel = makeKernel(compareInputDeltas$1, {
  1917. constants: {
  1918. filterCount: this.filterCount,
  1919. },
  1920. output: [
  1921. this.inputLayer.width,
  1922. this.inputLayer.height,
  1923. this.inputLayer.depth,
  1924. ],
  1925. immutable: true,
  1926. });
  1927. this.compareBiasesKernel = makeKernel(compareBiases$1, {
  1928. output: [1, 1, this.depth],
  1929. constants: {
  1930. deltaWidth: this.width,
  1931. deltaHeight: this.height,
  1932. },
  1933. immutable: true,
  1934. });
  1935. }
  1936. predict() {
  1937. this.weights = this.predictKernel(this.inputLayer.weights, this.filters, this.biases);
  1938. }
  1939. compare() {
  1940. const { filterDeltas, biasDeltas } = this;
  1941. this.filterDeltas = this.compareFilterDeltasKernel(filterDeltas, this.inputLayer.weights, this.deltas);
  1942. release(filterDeltas);
  1943. this.biasDeltas = this.compareBiasesKernel(biasDeltas, this.deltas);
  1944. release(biasDeltas);
  1945. release(this.deltas);
  1946. this.deltas = this.compareInputDeltasKernel(this.filters, this.inputLayer.deltas);
  1947. release(this.inputLayer.deltas);
  1948. // TODO: do we need to clone here?
  1949. this.inputLayer.deltas = clone(this.deltas);
  1950. }
  1951. learn(learningRate) {
  1952. // TODO: handle filters
  1953. // TODO: do we need to release here?
  1954. const { weights: oldWeights } = this;
  1955. this.weights = this.praxis.run(this, learningRate);
  1956. release(oldWeights);
  1957. }
  1958. }
  1959. function convolution(settings, inputLayer) {
  1960. return new Convolution(settings, inputLayer);
  1961. }
  1962. function setDropout(dropout) {
  1963. return dropout;
  1964. }
  1965. function trainingPredict(inputs) {
  1966. if (setDropout(Math.random()) < this.constants.probability) {
  1967. return 0;
  1968. }
  1969. return inputs[this.thread.y][this.thread.x];
  1970. }
  1971. function predict$5(inputs) {
  1972. return inputs[this.thread.y][this.thread.x] * this.constants.probability;
  1973. }
  1974. function compare$3(dropouts, deltas) {
  1975. if (dropouts[this.thread.y][this.thread.x] === 0) {
  1976. return 0;
  1977. }
  1978. return deltas[this.thread.y][this.thread.x];
  1979. }
  1980. const dropoutDefaults = {
  1981. ...baseLayerDefaultSettings,
  1982. probability: 0.5,
  1983. };
  1984. class Dropout extends Filter {
  1985. constructor(inputLayer, settings) {
  1986. super(settings, inputLayer);
  1987. this.predictKernelMap = null;
  1988. this.settings = { ...dropoutDefaults, ...settings };
  1989. this.dropouts = null;
  1990. this.validate();
  1991. }
  1992. setupKernels(isTraining) {
  1993. const output = [this.width, this.height];
  1994. if (isTraining) {
  1995. this.predictKernelMap = makeKernelMap({ dropouts: setDropout }, trainingPredict, {
  1996. output,
  1997. immutable: true,
  1998. });
  1999. this.compareKernel = makeKernel(compare$3, { output, immutable: true });
  2000. }
  2001. else {
  2002. this.predictKernelMap = makeKernelMap({}, predict$5, { output, immutable: true });
  2003. }
  2004. }
  2005. predict() {
  2006. release(this.weights);
  2007. if (this.dropouts) {
  2008. release(this.dropouts);
  2009. }
  2010. const { result, dropouts } = this
  2011. .predictKernelMap(this.inputLayer.weights);
  2012. this.weights = result;
  2013. this.dropouts = dropouts;
  2014. }
  2015. compare() {
  2016. release(this.deltas);
  2017. this.deltas = this.compareKernel(this.dropouts, this.inputLayer.deltas);
  2018. }
  2019. }
  2020. function dropout(inputLayer, settings) {
  2021. return new Dropout(inputLayer, settings);
  2022. }
  2023. function feedForward(settings, input) {
  2024. const { height, praxisOpts = null } = settings;
  2025. const weights = random({
  2026. id: 'weights',
  2027. height,
  2028. width: input.height,
  2029. praxisOpts,
  2030. });
  2031. const biases = random({ id: 'biases', height, praxisOpts });
  2032. return sigmoid$1(add$1(multiply$1(weights, input, { praxisOpts }), biases, { praxisOpts }), { praxisOpts });
  2033. }
  2034. function predict$4(inputs, filters, biases) {
  2035. let output = 0;
  2036. let i = 0;
  2037. for (let y = 0; y < this.constants.inputHeight; y++) {
  2038. for (let x = 0; x < this.constants.inputWidth; x++) {
  2039. output += inputs[y][x] * filters[this.thread.x][i];
  2040. i++;
  2041. }
  2042. }
  2043. return output + biases[this.thread.x];
  2044. }
  2045. function predict3D$4(inputs, filters, biases) {
  2046. let output = 0;
  2047. let i = 0;
  2048. for (let z = 0; z < this.constants.inputDepth; z++) {
  2049. for (let y = 0; y < this.constants.inputHeight; y++) {
  2050. for (let x = 0; x < this.constants.inputWidth; x++) {
  2051. output += inputs[z][y][x] * filters[this.thread.x][i];
  2052. i++;
  2053. }
  2054. }
  2055. }
  2056. return output + biases[this.thread.x];
  2057. }
  2058. function compareInputDeltas(inputDeltas, deltas, filters) {
  2059. let sum = 0;
  2060. const filterX = this.thread.x + this.thread.y * this.output.x;
  2061. for (let filterY = 0; filterY < this.constants.filterCount; filterY++) {
  2062. sum += filters[filterY][filterX] * deltas[0][filterY];
  2063. }
  2064. return sum + inputDeltas[this.thread.y][this.thread.x];
  2065. }
  2066. function compareInputDeltas3D(inputDeltas, deltas, filters) {
  2067. let sum = 0;
  2068. const filterX = this.thread.x + this.thread.y * this.output.x;
  2069. for (let filterY = 0; filterY < this.constants.filterCount; filterY++) {
  2070. sum += filters[filterY][filterX] * deltas[0][filterY];
  2071. }
  2072. return sum + inputDeltas[this.thread.z][this.thread.y][this.thread.x];
  2073. }
  2074. function compareBiases(biases, deltas) {
  2075. return biases[this.thread.x] + deltas[this.thread.y][this.thread.x];
  2076. }
  2077. function compareFilterDeltas(filterDeltas, inputWeights, deltas) {
  2078. return (filterDeltas[this.thread.y][this.thread.x] +
  2079. inputWeights[this.thread.y][this.thread.x] *
  2080. deltas[this.constants.deltaY][this.constants.deltaX]);
  2081. }
  2082. function compareFilterDeltas3D(filterDeltas, inputWeights, deltas) {
  2083. const inputZ = Math.floor(this.thread.x / (this.constants.inputWidth * this.constants.inputHeight));
  2084. const inputY = Math.floor((this.thread.x -
  2085. inputZ * this.constants.inputWidth * this.constants.inputHeight) /
  2086. this.constants.inputWidth);
  2087. const inputX = this.thread.x -
  2088. this.constants.inputWidth * (inputY + this.constants.inputHeight * inputZ);
  2089. return (filterDeltas[this.thread.y][this.thread.x] +
  2090. inputWeights[inputZ][inputY][inputX] * deltas[0][this.thread.y]);
  2091. }
  2092. class FullyConnected extends Filter {
  2093. constructor(settings, inputLayer) {
  2094. super(settings, inputLayer);
  2095. this.compareFilterDeltasKernel = null;
  2096. this.compareInputDeltasKernel = null;
  2097. this.compareBiasesKernel = null;
  2098. this.settings = { ...settings };
  2099. this.validate();
  2100. const connectionCount = inputLayer.width * inputLayer.height * inputLayer.depth;
  2101. this.biases = values(this.height, this.bias);
  2102. this.biasDeltas = zeros$1(this.height);
  2103. this.filters = randos2D(connectionCount, this.height);
  2104. this.filterDeltas = zeros2D(connectionCount, this.height);
  2105. if (this.depth > 0) {
  2106. this.weights = randos3D(this.width, this.height, this.depth);
  2107. this.deltas = zeros3D(this.width, this.height, this.depth);
  2108. }
  2109. else if (this.height > 0) {
  2110. this.weights = randos2D(this.width, this.height);
  2111. this.deltas = zeros2D(this.width, this.height);
  2112. }
  2113. }
  2114. get bias() {
  2115. return this.settings.bias;
  2116. }
  2117. get biases() {
  2118. return this.settings.biases;
  2119. }
  2120. set biases(biases) {
  2121. this.settings.biases = biases;
  2122. }
  2123. get biasDeltas() {
  2124. return this.settings.biases;
  2125. }
  2126. set biasDeltas(biasDeltas) {
  2127. this.settings.biasDeltas = biasDeltas;
  2128. }
  2129. validate() {
  2130. super.validate();
  2131. if (this.depth > 0)
  2132. throw new Error('depth not supported');
  2133. }
  2134. setupKernels() {
  2135. const { inputLayer } = this;
  2136. const connectionCount = inputLayer.width * inputLayer.height * inputLayer.depth;
  2137. if (inputLayer.depth > 0) {
  2138. this.predictKernel = makeKernel(predict3D$4, {
  2139. output: [this.width, this.height],
  2140. constants: {
  2141. inputHeight: inputLayer.height,
  2142. inputWidth: inputLayer.width,
  2143. inputDepth: inputLayer.depth,
  2144. },
  2145. });
  2146. this.compareFilterDeltasKernel = makeKernel(compareFilterDeltas3D, {
  2147. output: [connectionCount, this.height],
  2148. constants: {
  2149. inputWidth: inputLayer.width,
  2150. inputHeight: inputLayer.height,
  2151. },
  2152. immutable: true,
  2153. });
  2154. this.compareInputDeltasKernel = makeKernel(compareInputDeltas3D, {
  2155. output: [inputLayer.width, inputLayer.height, inputLayer.depth],
  2156. constants: {
  2157. filterCount: this.height,
  2158. },
  2159. immutable: true,
  2160. });
  2161. }
  2162. else {
  2163. this.predictKernel = makeKernel(predict$4, {
  2164. output: [this.width, this.height],
  2165. constants: {
  2166. inputHeight: inputLayer.height,
  2167. inputWidth: inputLayer.width,
  2168. },
  2169. });
  2170. this.compareFilterDeltasKernel = makeKernel(compareFilterDeltas, {
  2171. output: [connectionCount, this.height],
  2172. constants: {
  2173. inputWidth: inputLayer.width,
  2174. },
  2175. });
  2176. this.compareInputDeltasKernel = makeKernel(compareInputDeltas, {
  2177. output: [inputLayer.width, inputLayer.height],
  2178. constants: {
  2179. filterCount: this.height,
  2180. },
  2181. });
  2182. }
  2183. this.compareBiasesKernel = makeKernel(compareBiases, {
  2184. output: [this.width, this.height],
  2185. });
  2186. }
  2187. predict() {
  2188. this.weights = this.predictKernel(this.inputLayer.weights, this.filters, this.biases);
  2189. }
  2190. compare() {
  2191. const inputLayerDeltas = this.inputLayer.deltas;
  2192. this.inputLayer.deltas = this
  2193. .compareInputDeltasKernel(inputLayerDeltas, this.deltas, this.filters);
  2194. release(inputLayerDeltas);
  2195. const { biasDeltas, filterDeltas } = this;
  2196. // TODO: handle biasDeltas learn
  2197. this.biasDeltas = this.compareBiasesKernel(this.biases, this.deltas);
  2198. // TODO: handle filterDeltas learn
  2199. this.filterDeltas = this.compareFilterDeltasKernel(filterDeltas, this.inputLayer.weights, this.deltas);
  2200. release(biasDeltas);
  2201. release(filterDeltas);
  2202. }
  2203. }
  2204. function fullyConnected(settings, inputLayer) {
  2205. return new FullyConnected(settings, inputLayer);
  2206. }
  2207. function predict$3(weights) {
  2208. return -weights[this.thread.y][this.thread.x];
  2209. }
  2210. class Negative extends Modifier {
  2211. constructor(inputLayer, settings) {
  2212. super(inputLayer, settings);
  2213. this.validate();
  2214. }
  2215. setupKernels() {
  2216. this.predictKernel = makeKernel(predict$3, {
  2217. output: [this.width, this.height],
  2218. });
  2219. }
  2220. predict() {
  2221. this.weights = this.predictKernel(this.inputLayer.weights);
  2222. }
  2223. }
  2224. function negative(inputLayer, settings) {
  2225. return new Negative(inputLayer, settings);
  2226. }
  2227. function predict$2(inputLayerWeights1, inputLayerWeights2) {
  2228. return (inputLayerWeights1[this.thread.y][this.thread.x] *
  2229. inputLayerWeights2[this.thread.y][this.thread.x]);
  2230. }
  2231. function compare$2(weights, deltas) {
  2232. return (weights[this.thread.y][this.thread.x] * deltas[this.thread.y][this.thread.x]);
  2233. }
  2234. class MultiplyElement extends Operator {
  2235. get width() {
  2236. return this.inputLayer1.width;
  2237. }
  2238. get height() {
  2239. return this.inputLayer1.height;
  2240. }
  2241. get depth() {
  2242. return this.inputLayer1.depth;
  2243. }
  2244. validate() {
  2245. super.validate();
  2246. checkSameSize(this.inputLayer1, this.inputLayer2);
  2247. }
  2248. setupKernels() {
  2249. this.predictKernel = makeKernel(predict$2, {
  2250. output: [this.width, this.height],
  2251. immutable: true,
  2252. });
  2253. this.compareKernel = makeKernel(compare$2, {
  2254. output: [this.width, this.height],
  2255. immutable: true,
  2256. });
  2257. }
  2258. predict() {
  2259. release(this.weights);
  2260. this.weights = this.predictKernel(this.inputLayer1.weights, this.inputLayer2.weights);
  2261. }
  2262. compare() {
  2263. release(this.inputLayer1.deltas);
  2264. release(this.inputLayer2.deltas);
  2265. this.inputLayer1.deltas = this.compareKernel(this.inputLayer2.weights, this.deltas);
  2266. this.inputLayer2.deltas = this.compareKernel(this.inputLayer1.weights, this.deltas);
  2267. }
  2268. }
  2269. function multiplyElement$1(inputLayer1, inputLayer2, settings) {
  2270. return new MultiplyElement(inputLayer1, inputLayer2, settings);
  2271. }
  2272. function ones$1(size) {
  2273. return new Float32Array(size).fill(1);
  2274. }
  2275. function ones2D(width, height) {
  2276. const result = new Array(height);
  2277. for (let y = 0; y < height; y++) {
  2278. result[y] = ones$1(width);
  2279. }
  2280. return result;
  2281. }
  2282. class Ones extends Model {
  2283. constructor(settings) {
  2284. super(settings);
  2285. this.validate();
  2286. this.weights = ones2D(this.width, this.height);
  2287. this.deltas = zeros2D(this.width, this.height);
  2288. }
  2289. }
  2290. function ones(settings) {
  2291. return new Ones(settings);
  2292. }
  2293. function predict2D$3(inputs) {
  2294. return activate$1(inputs[this.thread.y][this.thread.x]);
  2295. }
  2296. function predict3D$3(inputs) {
  2297. return activate$1(inputs[this.thread.z][this.thread.y][this.thread.x]);
  2298. }
  2299. function compare2D$3(weights, errors) {
  2300. return measure$1(weights[this.thread.y][this.thread.x], errors[this.thread.y][this.thread.x]);
  2301. }
  2302. function compare3D$3(weights, errors) {
  2303. return measure$1(weights[this.thread.z][this.thread.y][this.thread.x], errors[this.thread.z][this.thread.y][this.thread.x]);
  2304. }
  2305. class Tanh extends Activation {
  2306. setupKernels() {
  2307. if (this.depth > 0) {
  2308. this.predictKernel = makeKernel(predict3D$3, {
  2309. output: [this.width, this.height, this.depth],
  2310. functions: [activate$1],
  2311. immutable: true,
  2312. });
  2313. this.compareKernel = makeKernel(compare3D$3, {
  2314. output: [this.width, this.height, this.depth],
  2315. functions: [measure$1],
  2316. immutable: true,
  2317. });
  2318. }
  2319. else {
  2320. this.predictKernel = makeKernel(predict2D$3, {
  2321. output: [this.width, this.height],
  2322. functions: [activate$1],
  2323. immutable: true,
  2324. });
  2325. this.compareKernel = makeKernel(compare2D$3, {
  2326. output: [this.width, this.height],
  2327. functions: [measure$1],
  2328. immutable: true,
  2329. });
  2330. }
  2331. }
  2332. predict() {
  2333. release(this.weights);
  2334. this.weights = this.predictKernel(this.inputLayer.weights);
  2335. }
  2336. compare() {
  2337. release(this.inputLayer.deltas);
  2338. this.inputLayer.deltas = this.compareKernel(this.weights, this.deltas);
  2339. }
  2340. }
  2341. function tanh$1(inputLayer, settings) {
  2342. return new Tanh(inputLayer, settings);
  2343. }
  2344. class Zeros extends Model {
  2345. constructor(settings) {
  2346. super(settings);
  2347. this.validate();
  2348. this.weights = zeros2D(this.width, this.height);
  2349. this.deltas = zeros2D(this.width, this.height);
  2350. }
  2351. predict() {
  2352. // throw new Error(`${this.constructor.name}-predict is not yet implemented`)
  2353. }
  2354. compare() {
  2355. // throw new Error(`${this.constructor.name}-compare is not yet implemented`)
  2356. }
  2357. }
  2358. function zeros(settings) {
  2359. return new Zeros(settings);
  2360. }
  2361. function gru(settings, recurrentInput, input) {
  2362. const { height } = settings;
  2363. const updateGateWeights = random({ height, width: input.height });
  2364. const updateGatePeepholes = random({ width: height, height });
  2365. const updateGateBias = zeros({ height });
  2366. const updateGate = sigmoid$1(add$1(add$1(multiply$1(updateGateWeights, input), multiply$1(updateGatePeepholes, recurrentInput)), updateGateBias));
  2367. const resetGateWeights = random({ height, width: input.height });
  2368. const resetGatePeepholes = random({ width: height, height });
  2369. const resetGateBias = zeros({ height });
  2370. const resetGate = sigmoid$1(add$1(add$1(multiply$1(resetGateWeights, input), multiply$1(resetGatePeepholes, recurrentInput)), resetGateBias));
  2371. const cellWeights = random({ height, width: input.height });
  2372. const cellPeepholes = random({ width: height, height });
  2373. const cellBias = zeros({ height });
  2374. const cell = tanh$1(add$1(add$1(multiply$1(cellWeights, input), multiply$1(cellPeepholes, multiplyElement$1(resetGate, recurrentInput))), cellBias));
  2375. // compute hidden state as gated, saturated cell activations
  2376. // negate updateGate
  2377. return add$1(multiplyElement$1(add$1(ones({ width: updateGate.width, height: updateGate.height }), negative(updateGate)), cell), multiplyElement$1(recurrentInput, updateGate));
  2378. }
  2379. const defaults$5 = {
  2380. weights: null,
  2381. };
  2382. class Input extends EntryPoint {
  2383. constructor(settings) {
  2384. super({ ...defaults$5, ...settings });
  2385. this.reshapeInput = null;
  2386. this.validate();
  2387. this.reshapeInput = null;
  2388. this.deltas = zeros2D(this.width, this.height);
  2389. }
  2390. setupKernels() {
  2391. if (this.width === 1) {
  2392. this.predict = this.predict1D;
  2393. this.reshapeInput = makeKernel(function (value) {
  2394. return value[this.thread.y];
  2395. }, {
  2396. output: [1, this.height],
  2397. immutable: true,
  2398. });
  2399. }
  2400. }
  2401. reuseKernels(layer) {
  2402. // super.reuseKernels(layer);
  2403. this.reshapeInput = layer.reshapeInput;
  2404. }
  2405. predict(inputs) {
  2406. if ((Array.isArray(inputs) || inputs instanceof Float32Array) &&
  2407. typeof inputs[0] === 'number' &&
  2408. inputs.length === this.height * this.width) {
  2409. release(this.weights);
  2410. this.weights = kernelInput(inputs, [this.width, this.height]);
  2411. }
  2412. else if (Array.isArray(inputs) &&
  2413. inputs.length === this.height &&
  2414. (Array.isArray(inputs[0]) || inputs[0] instanceof Float32Array) &&
  2415. inputs[0].length === this.width) {
  2416. this.weights = clone(inputs);
  2417. }
  2418. else {
  2419. throw new Error('Inputs are not of sized correctly');
  2420. }
  2421. }
  2422. predict1D(inputs) {
  2423. if (this.weights)
  2424. release(this.weights);
  2425. if (this.reshapeInput) {
  2426. this.weights = this.reshapeInput(inputs);
  2427. }
  2428. else {
  2429. this.weights = inputs;
  2430. }
  2431. }
  2432. compare() {
  2433. // throw new Error(`${this.constructor.name}-compare is not yet implemented`)
  2434. }
  2435. learn() { }
  2436. }
  2437. function input(settings) {
  2438. return new Input(settings);
  2439. }
  2440. function predict2D$2(inputs) {
  2441. return activate(inputs[this.thread.y][this.thread.x]);
  2442. }
  2443. function predict3D$2(inputs) {
  2444. return activate(inputs[this.thread.z][this.thread.y][this.thread.x]);
  2445. }
  2446. function compare2D$2(weights, deltas) {
  2447. return measure(weights[this.thread.y][this.thread.x], deltas[this.thread.y][this.thread.x]);
  2448. }
  2449. function compare3D$2(weights, deltas) {
  2450. return measure(weights[this.thread.z][this.thread.y][this.thread.x], deltas[this.thread.z][this.thread.y][this.thread.x]);
  2451. }
  2452. class LeakyRelu extends Activation {
  2453. setupKernels() {
  2454. const { width, height, depth } = this.inputLayer;
  2455. if (this.depth > 0) {
  2456. this.predictKernel = makeKernel(predict3D$2, {
  2457. output: [width, height, depth],
  2458. functions: [activate],
  2459. immutable: true,
  2460. });
  2461. this.compareKernel = makeKernel(compare3D$2, {
  2462. output: [width, height, depth],
  2463. functions: [measure],
  2464. immutable: true,
  2465. });
  2466. }
  2467. else {
  2468. this.predictKernel = makeKernel(predict2D$2, {
  2469. output: [width, height],
  2470. functions: [activate],
  2471. immutable: true,
  2472. });
  2473. this.compareKernel = makeKernel(compare2D$2, {
  2474. output: [width, height],
  2475. functions: [measure],
  2476. immutable: true,
  2477. });
  2478. }
  2479. }
  2480. predict() {
  2481. release(this.weights);
  2482. this.weights = this.predictKernel(this.inputLayer.weights);
  2483. }
  2484. compare() {
  2485. const { deltas } = this;
  2486. this.deltas = this.compareKernel(this.weights, deltas);
  2487. release(deltas);
  2488. }
  2489. }
  2490. function leakyRelu(inputLayer, settings) {
  2491. return new LeakyRelu(inputLayer, settings);
  2492. }
  2493. function lstmCell(settings, input, recurrentInput) {
  2494. const { height } = settings;
  2495. if (typeof height !== 'number') {
  2496. throw new Error('no settings.height given');
  2497. }
  2498. if (recurrentInput.setDimensions) {
  2499. recurrentInput.setDimensions(1, height);
  2500. }
  2501. const inputGateWeights = random({
  2502. width: input.height,
  2503. height,
  2504. std: 0.08,
  2505. id: 'inputGateWeights',
  2506. });
  2507. const inputGatePeepholes = random({
  2508. width: height,
  2509. height,
  2510. std: 0.08,
  2511. id: 'inputGatePeepholes',
  2512. });
  2513. const inputGateBias = zeros({ width: 1, height, id: 'inputGateBias' });
  2514. const inputGate = sigmoid$1(add$1(add$1(multiply$1(inputGateWeights, input), multiply$1(inputGatePeepholes, recurrentInput)), inputGateBias), { id: 'inputGate' });
  2515. const forgetGateWeights = random({
  2516. width: input.height,
  2517. height,
  2518. std: 0.08,
  2519. id: 'forgetGateWeights',
  2520. });
  2521. const forgetGatePeepholes = random({
  2522. width: height,
  2523. height,
  2524. std: 0.08,
  2525. id: 'forgetGatePeepholes',
  2526. });
  2527. const forgetGateBias = zeros({ width: 1, height, id: 'forgetGateBias' });
  2528. const forgetGate = sigmoid$1(add$1(add$1(multiply$1(forgetGateWeights, input), multiply$1(forgetGatePeepholes, recurrentInput)), forgetGateBias), { id: 'forgetGate' });
  2529. const outputGateWeights = random({
  2530. width: input.height,
  2531. height,
  2532. std: 0.08,
  2533. id: 'outputGateWeights',
  2534. });
  2535. const outputGatePeepholes = random({
  2536. width: height,
  2537. height,
  2538. std: 0.08,
  2539. id: 'outputGatePeepholes',
  2540. });
  2541. const outputGateBias = zeros({ width: 1, height, id: 'outputGateBias' });
  2542. const outputGate = sigmoid$1(add$1(add$1(multiply$1(outputGateWeights, input), multiply$1(outputGatePeepholes, recurrentInput)), outputGateBias), { id: 'outputGate' });
  2543. const memoryWeights = random({
  2544. width: input.height,
  2545. height,
  2546. std: 0.08,
  2547. id: 'memoryWeights',
  2548. });
  2549. const memoryPeepholes = random({
  2550. width: height,
  2551. height,
  2552. std: 0.08,
  2553. id: 'memoryPeepholes',
  2554. });
  2555. const memoryBias = zeros({ width: 1, height, id: 'memoryBias' });
  2556. const memory = tanh$1(add$1(add$1(multiply$1(memoryWeights, input), multiply$1(memoryPeepholes, recurrentInput)), memoryBias), { id: 'memory' });
  2557. // compute new cell activation
  2558. const retainCell = multiplyElement$1(forgetGate, recurrentInput, {
  2559. id: 'retainCell',
  2560. }); // what do we keep from cell
  2561. const writeCell = multiplyElement$1(inputGate, memory, { id: 'writeCell' }); // what do we write to cell
  2562. const cell = add$1(retainCell, writeCell, { id: 'cell' }); // new cell contents
  2563. // compute hidden state as gated, saturated cell activations
  2564. return multiplyElement$1(outputGate, tanh$1(cell), { id: 'activations' });
  2565. }
  2566. function output(settings, inputLayer) {
  2567. const { height } = settings;
  2568. const outputGate = random({
  2569. height,
  2570. width: inputLayer.height,
  2571. id: 'outputGate',
  2572. std: 0.08,
  2573. });
  2574. const output = random({ height, id: 'output', std: 0.08 });
  2575. const outputGateConnector = multiply$1(outputGate, inputLayer, {
  2576. id: 'outputGateConnected',
  2577. });
  2578. return target({ id: 'target', ...settings }, add$1(outputGateConnector, output));
  2579. }
  2580. function setSwitchY(value) {
  2581. return value;
  2582. }
  2583. function setSwitchX(value) {
  2584. return value;
  2585. }
  2586. function predict$1(inputs) {
  2587. const startFilterX = this.constants.paddingX - this.thread.x * this.constants.strideX;
  2588. const startInputX = this.thread.x * this.constants.strideX - this.constants.paddingX;
  2589. const endFilterX = Math.min(this.constants.filterWidth, startFilterX + this.constants.inputWidth);
  2590. const startFilterY = this.constants.paddingY - this.thread.y * this.constants.strideY;
  2591. const startInputY = this.thread.y * this.constants.strideY - this.constants.paddingY;
  2592. const endFilterY = Math.min(this.constants.filterHeight, startFilterY + this.constants.inputHeight);
  2593. let largestValue = -99999;
  2594. // convolve centered at this particular location
  2595. for (let filterY = Math.max(0, startFilterY), inputY = Math.max(0, startInputY); filterY < endFilterY; filterY++, inputY++) {
  2596. for (let filterX = Math.max(0, startFilterX), inputX = Math.max(0, startInputX); filterX < endFilterX; filterX++, inputX++) {
  2597. if (inputY >= 0 &&
  2598. inputY < this.constants.inputHeight &&
  2599. inputX >= 0 &&
  2600. inputX < this.constants.inputWidth) {
  2601. const input = inputs[this.thread.z][inputY][inputX];
  2602. if (input > largestValue) {
  2603. largestValue = input;
  2604. }
  2605. }
  2606. }
  2607. }
  2608. return largestValue;
  2609. }
  2610. function compare$1(deltas, switchY, switchX) {
  2611. const x = Math.floor((this.thread.x / this.output.x) * this.constants.outputWidth);
  2612. const y = Math.floor((this.thread.y / this.output.y) * this.constants.outputHeight);
  2613. let value = 0;
  2614. for (let deltasY = 0; deltasY < this.constants.inputHeight; deltasY++) {
  2615. for (let deltasX = 0; deltasX < this.constants.inputWidth; deltasX++) {
  2616. const switchXValue = switchX[deltasY][deltasX];
  2617. const switchYValue = switchY[deltasY][deltasX];
  2618. if (switchXValue === x && switchYValue === y) {
  2619. value += deltas[deltasY][deltasX];
  2620. }
  2621. }
  2622. }
  2623. return value;
  2624. }
  2625. const defaults$4 = {
  2626. padding: 0,
  2627. stride: 0,
  2628. filterWidth: 0,
  2629. filterHeight: 0,
  2630. filterCount: 0,
  2631. };
  2632. class Pool extends Filter {
  2633. constructor(settings, inputLayer) {
  2634. super(settings, inputLayer);
  2635. this.predictKernelMap = null;
  2636. this.settings = {
  2637. ...settings,
  2638. ...getStride(settings, defaults$4),
  2639. ...getPadding(settings, defaults$4),
  2640. };
  2641. this.weights = randos3D(this.width, this.height, this.depth);
  2642. this.deltas = zeros3D(this.width, this.height, this.depth);
  2643. this.filters = randos3D(this.filterWidth, this.filterHeight, this.filterCount);
  2644. this.filterDeltas = zeros3D(this.filterWidth, this.filterHeight, this.filterCount);
  2645. this.validate();
  2646. }
  2647. get strideX() {
  2648. return this.settings.strideX;
  2649. }
  2650. get strideY() {
  2651. return this.settings.strideY;
  2652. }
  2653. get paddingX() {
  2654. return this.settings.paddingX;
  2655. }
  2656. get paddingY() {
  2657. return this.settings.paddingY;
  2658. }
  2659. get width() {
  2660. return Math.floor((this.inputLayer.width + this.paddingX * 2 - this.filterWidth) /
  2661. this.strideX +
  2662. 1);
  2663. }
  2664. get height() {
  2665. return Math.floor((this.inputLayer.height + this.paddingY * 2 - this.filterHeight) /
  2666. this.strideY +
  2667. 1);
  2668. }
  2669. get depth() {
  2670. return this.settings.filterCount;
  2671. }
  2672. get filterCount() {
  2673. // TODO: handle 1 depth?
  2674. return this.settings.filterCount;
  2675. }
  2676. get switchX() {
  2677. return this.settings.switchX;
  2678. }
  2679. set switchX(switchX) {
  2680. this.settings.switchX = switchX;
  2681. }
  2682. get switchY() {
  2683. return this.settings.switchY;
  2684. }
  2685. set switchY(switchY) {
  2686. this.settings.switchY = switchY;
  2687. }
  2688. setupKernels() {
  2689. this.predictKernelMap = makeKernelMap({
  2690. switchX: setSwitchX,
  2691. switchY: setSwitchY,
  2692. }, predict$1, {
  2693. output: [this.width, this.height, this.depth],
  2694. constants: {
  2695. inputWidth: this.inputLayer.width,
  2696. inputHeight: this.inputLayer.height,
  2697. paddingX: this.paddingX,
  2698. paddingY: this.paddingY,
  2699. filterHeight: this.filterHeight,
  2700. filterWidth: this.filterWidth,
  2701. },
  2702. });
  2703. this.compareKernel = makeKernel(compare$1, {
  2704. output: [
  2705. this.inputLayer.width,
  2706. this.inputLayer.height,
  2707. this.inputLayer.depth,
  2708. ],
  2709. constants: {
  2710. inputWidth: this.inputLayer.width,
  2711. inputHeight: this.inputLayer.height,
  2712. outputWidth: this.width,
  2713. outputHeight: this.height,
  2714. },
  2715. });
  2716. }
  2717. predict() {
  2718. const { result: weights, switchX, switchY } = this
  2719. .predictKernelMap(this.inputLayer.weights);
  2720. this.switchX = switchX;
  2721. this.switchY = switchY;
  2722. this.weights = weights;
  2723. }
  2724. compare() {
  2725. // debugger;
  2726. // const depth = this.inputLayer.deltas.length;
  2727. // const height = this.inputLayer.deltas[0].length;
  2728. // const width = this.inputLayer.deltas[0][0].length;
  2729. // const type = typeof this.inputLayer.deltas[0][0][0];
  2730. const inputLayerDeltas = this.inputLayer.deltas;
  2731. this.inputLayer.deltas = this.compareKernel(this.deltas, this.switchX, this.switchY);
  2732. release(inputLayerDeltas);
  2733. // debugger;
  2734. // if (depth !== this.inputLayer.deltas.length) debugger;
  2735. // if (height !== this.inputLayer.deltas[0].length) debugger;
  2736. // if (width !== this.inputLayer.deltas[0][0].length) debugger;
  2737. // if (type !== typeof this.inputLayer.deltas[0][0][0]) debugger;
  2738. }
  2739. }
  2740. function pool(settings, inputLayer) {
  2741. return new Pool(settings, inputLayer);
  2742. }
  2743. class RecurrentInput extends Internal {
  2744. constructor(recurrentInput) {
  2745. super();
  2746. this.praxis = null;
  2747. this.predictKernel = null;
  2748. this.compareKernel = null;
  2749. this.settings = {};
  2750. this.recurrentInput = recurrentInput;
  2751. this.validate();
  2752. }
  2753. get width() {
  2754. return this.recurrentInput.width;
  2755. }
  2756. get height() {
  2757. return this.recurrentInput.height;
  2758. }
  2759. get depth() {
  2760. return this.recurrentInput.depth;
  2761. }
  2762. get deltas() {
  2763. return this.recurrentInput.deltas;
  2764. }
  2765. set deltas(deltas) {
  2766. const recurrentInputDeltas = this.recurrentInput.deltas;
  2767. this.recurrentInput.deltas = deltas;
  2768. release(recurrentInputDeltas);
  2769. }
  2770. get weights() {
  2771. return this.recurrentInput.weights;
  2772. }
  2773. set weights(weights) {
  2774. const recurrentInputWeights = this.recurrentInput.weights;
  2775. this.recurrentInput.weights = weights;
  2776. release(recurrentInputWeights);
  2777. }
  2778. validate() {
  2779. BaseLayer.prototype.validate.call(this);
  2780. if (this.width !== this.recurrentInput.width) {
  2781. throw new Error(`${this.constructor.name} layer width ${this.width} and ${this.recurrentInput.constructor.name} width (${this.recurrentInput.width}) are not same`);
  2782. }
  2783. if (this.height !== this.recurrentInput.height) {
  2784. throw new Error(`${this.constructor.name} layer height ${this.height} and ${this.recurrentInput.constructor.name} width (${this.recurrentInput.height}) are not same`);
  2785. }
  2786. }
  2787. setDimensions(width, height) {
  2788. this.recurrentInput.width = width;
  2789. this.recurrentInput.height = height;
  2790. }
  2791. predict() {
  2792. // throw new Error(`${this.constructor.name}-predict is not yet implemented`)
  2793. }
  2794. compare() {
  2795. // throw new Error(`${this.constructor.name}-compare is not yet implemented`)
  2796. }
  2797. learn() {
  2798. // throw new Error(`${this.constructor.name}-learn is not yet implemented`)
  2799. }
  2800. setupKernels() {
  2801. // throw new Error(
  2802. // `${this.constructor.name}-setupKernels is not yet implemented`
  2803. // )
  2804. }
  2805. reuseKernels() {
  2806. // throw new Error(
  2807. // `${this.constructor.name}-reuseKernels is not yet implemented`
  2808. // )
  2809. }
  2810. }
  2811. class RecurrentZeros extends Internal {
  2812. constructor(settings) {
  2813. super();
  2814. this.praxis = null;
  2815. this.settings = {};
  2816. this.predictKernel = null;
  2817. this.compareKernel = null;
  2818. if (settings) {
  2819. this.settings = { ...settings };
  2820. }
  2821. }
  2822. setDimensions(width, height) {
  2823. this.praxis = null;
  2824. this.settings = {
  2825. ...this.settings,
  2826. width,
  2827. height,
  2828. weights: zeros2D(width, height),
  2829. deltas: zeros2D(width, height),
  2830. };
  2831. }
  2832. setupKernels() {
  2833. // throw new Error(
  2834. // `${this.constructor.name}-setupKernels is not yet implemented`
  2835. // )
  2836. }
  2837. reuseKernels() {
  2838. // throw new Error(
  2839. // `${this.constructor.name}-reuseKernels is not yet implemented`
  2840. // )
  2841. }
  2842. predict() {
  2843. // throw new Error(`${this.constructor.name}-predict is not yet implemented`)
  2844. }
  2845. compare() {
  2846. // throw new Error(`${this.constructor.name}-compare is not yet implemented`)
  2847. }
  2848. learn(learningRate) {
  2849. const { weights: oldWeights } = this;
  2850. this.weights = this.praxis.run(this, learningRate);
  2851. // this.deltas = deltas;
  2852. release(oldWeights);
  2853. }
  2854. }
  2855. function recurrentZeros() {
  2856. return new RecurrentZeros();
  2857. }
  2858. function predict2D$1(inputs) {
  2859. return activate$3(inputs[this.thread.y][this.thread.x]);
  2860. }
  2861. function compare2D$1(weights, deltas) {
  2862. return measure$3(weights[this.thread.y][this.thread.x], deltas[this.thread.y][this.thread.x]);
  2863. }
  2864. function predict3D$1(inputs) {
  2865. return activate$3(inputs[this.thread.z][this.thread.y][this.thread.x]);
  2866. }
  2867. function compare3D$1(weights, deltas) {
  2868. return measure$3(weights[this.thread.z][this.thread.y][this.thread.x], deltas[this.thread.z][this.thread.y][this.thread.x]);
  2869. }
  2870. class Relu extends Activation {
  2871. setupKernels() {
  2872. const { width, height, depth } = this.inputLayer;
  2873. if (depth > 0) {
  2874. this.predictKernel = makeKernel(predict3D$1, {
  2875. output: [width, height, depth],
  2876. functions: [activate$3],
  2877. immutable: true,
  2878. });
  2879. this.compareKernel = makeKernel(compare3D$1, {
  2880. output: [width, height, depth],
  2881. functions: [measure$3],
  2882. immutable: true,
  2883. });
  2884. }
  2885. else {
  2886. this.predictKernel = makeKernel(predict2D$1, {
  2887. output: [width, height],
  2888. functions: [activate$3],
  2889. immutable: true,
  2890. });
  2891. this.compareKernel = makeKernel(compare2D$1, {
  2892. output: [width, height],
  2893. functions: [measure$3],
  2894. immutable: true,
  2895. });
  2896. }
  2897. }
  2898. predict() {
  2899. release(this.weights);
  2900. this.weights = this.predictKernel(this.inputLayer.weights);
  2901. }
  2902. compare() {
  2903. release(this.inputLayer.deltas);
  2904. this.inputLayer.deltas = this.compareKernel(this.weights, this.deltas);
  2905. }
  2906. }
  2907. function relu$1(inputLayer, settings) {
  2908. return new Relu(inputLayer, settings);
  2909. }
  2910. function rnnCell(settings, input, recurrentInput) {
  2911. const { height } = settings;
  2912. if (typeof height !== 'number')
  2913. throw new Error('height not set');
  2914. if (recurrentInput.setDimensions) {
  2915. recurrentInput.setDimensions(1, height);
  2916. }
  2917. // wxh
  2918. const weight = random({
  2919. id: 'weight',
  2920. height,
  2921. width: input.height,
  2922. std: 0.08,
  2923. });
  2924. // whh
  2925. const transition = random({
  2926. id: 'transition',
  2927. height,
  2928. width: height,
  2929. std: 0.08,
  2930. });
  2931. // bhh
  2932. const bias = zeros({ id: 'bias', height });
  2933. return relu$1(add$1(add$1(multiply$1(weight, input), multiply$1(transition, recurrentInput)), bias));
  2934. }
  2935. class Regression extends BaseLayer {
  2936. constructor(settings, inputLayer) {
  2937. super(settings);
  2938. this.inputLayer = inputLayer;
  2939. this.validate();
  2940. }
  2941. predict() {
  2942. release(this.weights);
  2943. this.weights = clone(this.inputLayer.weights);
  2944. }
  2945. learn() {
  2946. // throw new Error(`${this.constructor.name}-learn is not yet implemented`)
  2947. }
  2948. }
  2949. // TODO: handle `loss += 0.5*dy*dy;` total and sum in learn
  2950. function regression(settings, inputLayer) {
  2951. return new Regression(settings, inputLayer);
  2952. }
  2953. function getMaxValue2D(inputs) {
  2954. let maxInput = -Infinity;
  2955. for (let y = 0; y < this.constants.inputHeight; y++) {
  2956. for (let x = 0; x < this.constants.inputWidth; x++) {
  2957. const input = inputs[y][x];
  2958. if (input > maxInput) {
  2959. maxInput = input;
  2960. }
  2961. }
  2962. }
  2963. return maxInput;
  2964. }
  2965. function getMaxValue3D(inputs) {
  2966. let maxInput = -Infinity;
  2967. for (let z = 0; z < this.constants.inputDepth; z++) {
  2968. for (let y = 0; y < this.constants.inputHeight; y++) {
  2969. for (let x = 0; x < this.constants.inputWidth; x++) {
  2970. const input = inputs[z][y][x];
  2971. if (input > maxInput) {
  2972. maxInput = input;
  2973. }
  2974. }
  2975. }
  2976. }
  2977. return maxInput;
  2978. }
  2979. function getSum2D(inputs) {
  2980. let sum = 0;
  2981. for (let y = 0; y < this.constants.inputHeight; y++) {
  2982. for (let x = 0; x < this.constants.inputWidth; x++) {
  2983. sum += inputs[y][x];
  2984. }
  2985. }
  2986. return sum;
  2987. }
  2988. function getSum3D(inputs) {
  2989. let sum = 0;
  2990. for (let z = 0; z < this.constants.inputDepth; z++) {
  2991. for (let y = 0; y < this.constants.inputHeight; y++) {
  2992. for (let x = 0; x < this.constants.inputWidth; x++) {
  2993. sum += inputs[z][y][x];
  2994. }
  2995. }
  2996. }
  2997. return sum;
  2998. }
  2999. function getExponentials(inputs, maxInput) {
  3000. return Math.exp(inputs[this.thread.x] - maxInput[0]);
  3001. }
  3002. function getExponentials3D(inputs, maxInput) {
  3003. return Math.exp(inputs[this.thread.z][this.thread.y][this.thread.x] - maxInput[0]);
  3004. }
  3005. function predict2D(exponentials, exponentialsSum) {
  3006. return exponentials[this.thread.y][this.thread.x] / exponentialsSum[0];
  3007. }
  3008. function predict3D(exponentials, exponentialsSum) {
  3009. return (exponentials[this.thread.z][this.thread.y][this.thread.x] /
  3010. exponentialsSum[0]);
  3011. }
  3012. function compare2D(target, exponentials) {
  3013. let indicator = 0;
  3014. const index = this.thread.x + this.thread.y * this.output.x;
  3015. if (index === target) {
  3016. indicator = 1;
  3017. }
  3018. return -(indicator - exponentials[this.thread.y][this.thread.x]);
  3019. }
  3020. function compare3D(target, exponentials) {
  3021. let indicator = 0;
  3022. const index = this.thread.x +
  3023. this.thread.y * this.output.x +
  3024. this.thread.z * this.output.x * this.output.y;
  3025. if (index === target) {
  3026. indicator = 1;
  3027. }
  3028. return -(indicator - exponentials[this.thread.z][this.thread.y][this.thread.x]);
  3029. }
  3030. // TODO: handle: `return -Math.log(this.es[y]);` in learn
  3031. class SoftMax extends Modifier {
  3032. constructor(inputLayer, settings) {
  3033. super(inputLayer, settings);
  3034. this.errors = null;
  3035. this.getExponentialsKernel = null;
  3036. this.getMaxValueKernel = null;
  3037. this.getSumKernel = null;
  3038. this.validate();
  3039. if (this.depth > 0) {
  3040. this.weights = randos3D(this.width, this.height, this.depth);
  3041. this.deltas = zeros3D(this.width, this.height, this.depth);
  3042. }
  3043. else if (this.height > 0) {
  3044. this.weights = randos2D(this.width, this.height);
  3045. this.deltas = zeros2D(this.width, this.height);
  3046. }
  3047. else {
  3048. this.weights = randos(this.width);
  3049. this.deltas = zeros$1(this.width);
  3050. }
  3051. }
  3052. setupKernels() {
  3053. const { width, height, depth } = this;
  3054. if (depth > 0) {
  3055. this.getExponentialsKernel = makeKernel(getExponentials3D, {
  3056. output: [width, height, depth],
  3057. });
  3058. this.getMaxValueKernel = makeKernel(getMaxValue3D, {
  3059. output: [1, 1, 1],
  3060. constants: {
  3061. inputWidth: width,
  3062. inputHeight: height,
  3063. inputDepth: depth,
  3064. },
  3065. });
  3066. this.getSumKernel = makeKernel(getSum3D, {
  3067. output: [1, 1, 1],
  3068. constants: {
  3069. inputWidth: width,
  3070. inputHeight: height,
  3071. inputDepth: depth,
  3072. },
  3073. });
  3074. this.predictKernel = makeKernel(predict3D, {
  3075. output: [width, height, depth],
  3076. });
  3077. this.compareKernel = makeKernel(compare3D, {
  3078. output: [width, height, depth],
  3079. immutable: true,
  3080. });
  3081. }
  3082. else {
  3083. this.getExponentialsKernel = makeKernel(getExponentials, {
  3084. output: [width, height],
  3085. });
  3086. this.getMaxValueKernel = makeKernel(getMaxValue2D, {
  3087. output: [1, 1],
  3088. constants: {
  3089. inputWidth: width,
  3090. inputHeight: height,
  3091. },
  3092. });
  3093. this.getSumKernel = makeKernel(getSum2D, {
  3094. output: [1, 1],
  3095. constants: {
  3096. inputWidth: width,
  3097. inputHeight: height,
  3098. },
  3099. });
  3100. this.predictKernel = makeKernel(predict2D, {
  3101. output: [width, height],
  3102. });
  3103. this.compareKernel = makeKernel(compare2D, {
  3104. output: [width, height],
  3105. immutable: true,
  3106. });
  3107. }
  3108. }
  3109. predict() {
  3110. const maxValue = this.getMaxValueKernel(this.inputLayer.weights);
  3111. const exponentials = this.getExponentialsKernel(this.inputLayer.weights, maxValue);
  3112. const exponentialsSum = this.getSumKernel(exponentials);
  3113. this.weights = this.predictKernel(exponentials, exponentialsSum);
  3114. }
  3115. compare(targetValues) {
  3116. const { deltas, errors } = this;
  3117. this.errors = this.compareKernel(targetValues[0], deltas);
  3118. this.deltas = clone(this.errors);
  3119. release(deltas);
  3120. release(errors);
  3121. const inputLayerDeltas = this.inputLayer.deltas;
  3122. this.inputLayer.deltas = clone(this.deltas);
  3123. release(inputLayerDeltas);
  3124. }
  3125. }
  3126. function softMax(inputLayer, settings) {
  3127. return new SoftMax(inputLayer, settings);
  3128. }
  3129. class SVM extends BaseLayer {
  3130. constructor(inputLayer, settings) {
  3131. super(settings);
  3132. this.inputLayer = inputLayer;
  3133. }
  3134. predict() {
  3135. release(this.weights);
  3136. this.weights = clone(this.inputLayer.weights);
  3137. this.validate();
  3138. }
  3139. learn() {
  3140. // throw new Error(`${this.constructor.name}-learn is not yet implemented`)
  3141. }
  3142. }
  3143. // function learn(target) {
  3144. // if (y === i) {
  3145. // continue;
  3146. // }
  3147. // const ydiff = -yscore + x.w[i] + margin;
  3148. // if (ydiff > 0) {
  3149. // // violating dimension, apply loss
  3150. // x.dw[i] += 1;
  3151. // x.dw[y] -= 1;
  3152. // loss += ydiff;
  3153. // }
  3154. // }
  3155. function svm(inputLayer, settings) {
  3156. return new SVM(inputLayer, settings);
  3157. }
  3158. function predict(value) {
  3159. return value[this.thread.x][this.thread.y];
  3160. }
  3161. const compare = predict;
  3162. class Transpose extends Modifier {
  3163. get width() {
  3164. return this.inputLayer.height;
  3165. }
  3166. get height() {
  3167. return this.inputLayer.width;
  3168. }
  3169. constructor(inputLayer) {
  3170. super(inputLayer);
  3171. this.validate();
  3172. }
  3173. setupKernels() {
  3174. this.predictKernel = makeKernel(predict, {
  3175. output: [this.height, this.width],
  3176. });
  3177. this.compareKernel = makeKernel(compare, {
  3178. output: [this.width, this.height],
  3179. });
  3180. }
  3181. predict() {
  3182. this.weights = this.predictKernel(this.inputLayer.weights);
  3183. }
  3184. compare() {
  3185. this.inputLayer.deltas = this.compareKernel(this.deltas);
  3186. }
  3187. }
  3188. function transpose(inputLayer) {
  3189. return new Transpose(inputLayer);
  3190. }
  3191. const layerTypes = {
  3192. Activation,
  3193. Internal,
  3194. InternalModel,
  3195. EntryPoint,
  3196. Filter,
  3197. Model,
  3198. Modifier,
  3199. Operator,
  3200. Target,
  3201. };
  3202. var layer = /*#__PURE__*/Object.freeze({
  3203. __proto__: null,
  3204. layerTypes: layerTypes,
  3205. Add: Add,
  3206. add: add$1,
  3207. arthurFeedForward: arthurFeedForward,
  3208. BaseLayer: BaseLayer,
  3209. baseLayerDefaultSettings: baseLayerDefaultSettings,
  3210. Convolution: Convolution,
  3211. convolution: convolution,
  3212. Dropout: Dropout,
  3213. dropout: dropout,
  3214. feedForward: feedForward,
  3215. FullyConnected: FullyConnected,
  3216. fullyConnected: fullyConnected,
  3217. gru: gru,
  3218. Input: Input,
  3219. input: input,
  3220. LeakyRelu: LeakyRelu,
  3221. leakyRelu: leakyRelu,
  3222. lstmCell: lstmCell,
  3223. Multiply: Multiply,
  3224. multiply: multiply$1,
  3225. MultiplyElement: MultiplyElement,
  3226. multiplyElement: multiplyElement$1,
  3227. Negative: Negative,
  3228. negative: negative,
  3229. Ones: Ones,
  3230. ones: ones,
  3231. output: output,
  3232. Pool: Pool,
  3233. pool: pool,
  3234. Random: Random,
  3235. random: random,
  3236. RecurrentInput: RecurrentInput,
  3237. RecurrentZeros: RecurrentZeros,
  3238. rnnCell: rnnCell,
  3239. Regression: Regression,
  3240. regression: regression,
  3241. Relu: Relu,
  3242. relu: relu$1,
  3243. Sigmoid: Sigmoid,
  3244. sigmoid: sigmoid$1,
  3245. SoftMax: SoftMax,
  3246. softMax: softMax,
  3247. SVM: SVM,
  3248. svm: svm,
  3249. Tanh: Tanh,
  3250. tanh: tanh$1,
  3251. Target: Target,
  3252. target: target,
  3253. Transpose: Transpose,
  3254. transpose: transpose,
  3255. Zeros: Zeros,
  3256. zeros: zeros
  3257. });
  3258. const layerNameTypes = Object.keys(layer);
  3259. function layerFromJSON(jsonLayer, inputLayer1, inputLayer2) {
  3260. if (!layerNameTypes.find((layerNameType) => layerNameType === jsonLayer.type)) {
  3261. return null;
  3262. }
  3263. const Layer = layer[jsonLayer.type];
  3264. if (Layer.prototype instanceof layerTypes.Filter) {
  3265. if (!inputLayer1)
  3266. throw new Error('inputLayer missing');
  3267. return new Layer(jsonLayer, inputLayer1);
  3268. }
  3269. else if (Layer.prototype instanceof layerTypes.Activation ||
  3270. Layer.prototype instanceof layerTypes.Modifier) {
  3271. if (!inputLayer1)
  3272. throw new Error('inputLayer missing');
  3273. return new Layer(inputLayer1, jsonLayer);
  3274. }
  3275. else if (Layer.prototype instanceof layerTypes.Internal) {
  3276. return new Layer(jsonLayer);
  3277. }
  3278. else if (Layer.prototype instanceof layerTypes.Operator) {
  3279. if (!inputLayer1)
  3280. throw new Error('inputLayer1 missing');
  3281. if (!inputLayer2)
  3282. throw new Error('inputLayer2 missing');
  3283. return new Layer(inputLayer1, inputLayer2, jsonLayer);
  3284. }
  3285. else if (Layer.prototype instanceof layerTypes.InternalModel ||
  3286. Layer.prototype instanceof layerTypes.EntryPoint ||
  3287. Layer.prototype instanceof layerTypes.Model) {
  3288. return new Layer(jsonLayer);
  3289. }
  3290. else if (Layer === Target) {
  3291. if (!inputLayer1)
  3292. throw new Error('inputLayer missing');
  3293. return new Layer(jsonLayer, inputLayer1);
  3294. }
  3295. return null;
  3296. }
  3297. class LookupTable {
  3298. constructor(data, prop) {
  3299. this.prop = null;
  3300. this.table = {};
  3301. this.length = 0;
  3302. const table = this.table;
  3303. if (prop) {
  3304. this.prop = prop;
  3305. for (let i = 0; i < data.length; i++) {
  3306. const datum = data[i];
  3307. const object = datum[prop];
  3308. for (const p in object) {
  3309. if (!object.hasOwnProperty(p))
  3310. continue;
  3311. if (table.hasOwnProperty(p))
  3312. continue;
  3313. table[p] = this.length++;
  3314. }
  3315. }
  3316. }
  3317. else if (Array.isArray(data) && Array.isArray(data[0])) {
  3318. for (let i = 0; i < data.length; i++) {
  3319. const array = data[i];
  3320. for (let j = 0; j < array.length; j++) {
  3321. const object = array[j];
  3322. for (const p in object) {
  3323. if (!object.hasOwnProperty(p))
  3324. continue;
  3325. if (table.hasOwnProperty(p))
  3326. continue;
  3327. table[p] = this.length++;
  3328. }
  3329. }
  3330. }
  3331. }
  3332. else {
  3333. for (let i = 0; i < data.length; i++) {
  3334. const object = data[i];
  3335. for (const p in object) {
  3336. if (!object.hasOwnProperty(p))
  3337. continue;
  3338. if (table.hasOwnProperty(p))
  3339. continue;
  3340. table[p] = this.length++;
  3341. }
  3342. }
  3343. }
  3344. }
  3345. }
  3346. const defaults$3 = {
  3347. learningRate: 0.3,
  3348. binaryThresh: 0.5,
  3349. initPraxis: (layerTemplate, settings) => {
  3350. var _a;
  3351. return momentumRootMeanSquaredPropagation(layerTemplate, (_a = layerTemplate.settings.praxisOpts) !== null && _a !== void 0 ? _a : settings);
  3352. },
  3353. };
  3354. const trainDefaults$3 = {
  3355. iterations: 20000,
  3356. errorThresh: 0.005,
  3357. log: false,
  3358. logPeriod: 10,
  3359. learningRate: 0.3,
  3360. callbackPeriod: 10,
  3361. errorCheckInterval: 100,
  3362. timeout: Infinity,
  3363. };
  3364. class FeedForward {
  3365. constructor(options = {}) {
  3366. this.trainOpts = {};
  3367. this.layers = null;
  3368. this._inputLayer = null;
  3369. this._hiddenLayers = null;
  3370. this._outputLayer = null;
  3371. this._model = null;
  3372. this.meanSquaredError = null;
  3373. this.inputLookup = null;
  3374. this.inputLookupLength = null;
  3375. this.outputLookup = null;
  3376. this.outputLookupLength = null;
  3377. this.options = { ...defaults$3, ...options };
  3378. this._updateTrainingOptions({
  3379. ...trainDefaults$3,
  3380. ...options,
  3381. });
  3382. }
  3383. static _validateTrainingOptions(options) {
  3384. const { iterations, errorThresh, log, logPeriod, learningRate, callback, callbackPeriod, timeout, } = options;
  3385. const validations = {
  3386. iterations: () => typeof iterations === 'number' && iterations > 0,
  3387. errorThresh: () => typeof errorThresh === 'number' && errorThresh > 0 && errorThresh < 1,
  3388. log: () => typeof log === 'function' || typeof log === 'boolean',
  3389. logPeriod: () => typeof logPeriod === 'number' && logPeriod > 0,
  3390. learningRate: () => typeof learningRate === 'number' &&
  3391. learningRate > 0 &&
  3392. learningRate < 1,
  3393. callback: () => typeof callback === 'function' || callback === null,
  3394. callbackPeriod: () => typeof callbackPeriod === 'number' && callbackPeriod > 0,
  3395. timeout: () => typeof timeout === 'number' && timeout > 0,
  3396. };
  3397. Object.keys(trainDefaults$3).forEach((key) => {
  3398. if (validations.hasOwnProperty(key) && !validations[key]()) {
  3399. const val = options[key];
  3400. throw new Error(`[${key}, ${(val !== null && val !== void 0 ? val : 'undefined').toString()}] is out of normal training range, your network will probably not train.`);
  3401. }
  3402. });
  3403. }
  3404. /**
  3405. * if a method is passed in method is used
  3406. * if false passed in nothing is logged
  3407. */
  3408. _setLogMethod(log) {
  3409. if (typeof log === 'function') {
  3410. this.trainOpts.log = log;
  3411. }
  3412. else if (log) {
  3413. // eslint-disable-next-line
  3414. this.trainOpts.log = console.log;
  3415. }
  3416. else {
  3417. this.trainOpts.log = false;
  3418. }
  3419. }
  3420. _updateTrainingOptions(opts) {
  3421. var _a;
  3422. this.trainOpts = { ...trainDefaults$3, ...this.trainOpts, ...opts };
  3423. FeedForward._validateTrainingOptions(this.trainOpts);
  3424. this._setLogMethod((_a = opts.log) !== null && _a !== void 0 ? _a : this.trainOpts.log);
  3425. const { callback, callbackPeriod, errorCheckInterval } = this.trainOpts;
  3426. if (callback && callbackPeriod !== errorCheckInterval) {
  3427. console.warn(`options.callbackPeriod with value of ${(callbackPeriod !== null && callbackPeriod !== void 0 ? callbackPeriod : 'undefined').toString()} does not match options.errorCheckInterval with value of ${(errorCheckInterval !== null && errorCheckInterval !== void 0 ? errorCheckInterval : 'undefined').toString()}, if logging error, it will repeat. These values may need to match`);
  3428. }
  3429. }
  3430. _connectOptionsLayers() {
  3431. const { inputLayerIndex, outputLayerIndex, layers } = this.options;
  3432. if (!layers)
  3433. throw new Error('this.options.layers in unexpected state');
  3434. if (typeof inputLayerIndex !== 'number')
  3435. throw new Error('inputLayerIndex not a number');
  3436. if (typeof outputLayerIndex !== 'number')
  3437. throw new Error('inputLayerIndex not a number');
  3438. const inputLayer = layers[inputLayerIndex];
  3439. if (!inputLayer) {
  3440. throw new Error('inputLayer not found in this.options.layers');
  3441. }
  3442. const outputLayer = layers[outputLayerIndex];
  3443. if (!outputLayer) {
  3444. throw new Error('outputLayer not found in this.options.layers');
  3445. }
  3446. this._inputLayer = inputLayer;
  3447. this._hiddenLayers = layers.slice(inputLayerIndex, outputLayerIndex - inputLayerIndex);
  3448. this._outputLayer = outputLayer;
  3449. return layers;
  3450. }
  3451. _connectNewLayers() {
  3452. const { inputLayer, outputLayer } = this.options;
  3453. if (!inputLayer)
  3454. throw new Error('inputLayer not defined');
  3455. const layers = [];
  3456. this._inputLayer = inputLayer();
  3457. const hiddenLayers = this._connectHiddenLayers(this._inputLayer);
  3458. if (!outputLayer)
  3459. throw new Error('outputLayer not defined');
  3460. this._outputLayer = outputLayer(hiddenLayers[hiddenLayers.length - 1], hiddenLayers.length);
  3461. layers.push(this._inputLayer);
  3462. layers.push(...hiddenLayers);
  3463. layers.push(this._outputLayer);
  3464. return flattenLayers(layers);
  3465. }
  3466. _connectHiddenLayers(previousLayer) {
  3467. this._hiddenLayers = [];
  3468. const result = [];
  3469. const { hiddenLayers } = this.options;
  3470. if (!hiddenLayers)
  3471. throw new Error('hiddenLayers not defined');
  3472. for (let i = 0; i < hiddenLayers.length; i++) {
  3473. const hiddenLayer = hiddenLayers[i](previousLayer, i);
  3474. result.push(hiddenLayer);
  3475. this._hiddenLayers.push(hiddenLayer);
  3476. previousLayer = hiddenLayer;
  3477. }
  3478. return result;
  3479. }
  3480. initialize() {
  3481. this.layers = this.options.layers
  3482. ? this._connectOptionsLayers()
  3483. : this._connectNewLayers();
  3484. this.initializeLayers(this.layers);
  3485. this._model = this.layers.filter((l) => l instanceof Model);
  3486. }
  3487. initializeLayers(layers) {
  3488. var _a, _b;
  3489. for (let i = 0; i < layers.length; i++) {
  3490. const layer = layers[i];
  3491. // TODO: optimize for when training or just running
  3492. layer.setupKernels(true);
  3493. if (layer instanceof Model &&
  3494. layer.praxis === null &&
  3495. typeof this.options.initPraxis === 'function') {
  3496. layer.praxis = this.options.initPraxis(layer, (_b = (_a = layer.settings.praxisOpts) !== null && _a !== void 0 ? _a : this.options.praxisOpts) !== null && _b !== void 0 ? _b : {});
  3497. layer.praxis.setupKernels();
  3498. }
  3499. }
  3500. const lastLayer = layers[layers.length - 1];
  3501. this.meanSquaredError = new MeanSquaredError({
  3502. width: lastLayer.width,
  3503. height: lastLayer.height,
  3504. });
  3505. }
  3506. run(input) {
  3507. let typeSafeInput;
  3508. if (Array.isArray(input) || input.buffer) {
  3509. typeSafeInput = input;
  3510. }
  3511. else {
  3512. if (this.inputLookup) {
  3513. typeSafeInput = lookup.toArray(this.inputLookup, input, this.inputLookupLength);
  3514. }
  3515. else {
  3516. throw new Error('input is incompatible with net');
  3517. }
  3518. }
  3519. let output = this.runInput(typeSafeInput);
  3520. if (output instanceof gpu_js.Texture) {
  3521. output = output.toArray();
  3522. }
  3523. if (this.outputLookup) {
  3524. return lookup.toObject(this.outputLookup, output);
  3525. }
  3526. return output;
  3527. }
  3528. runInput(input) {
  3529. if (!this.layers)
  3530. throw new Error('not initialized');
  3531. this.layers[0].predict(input);
  3532. for (let i = 1; i < this.layers.length; i++) {
  3533. this.layers[i].predict();
  3534. }
  3535. return this.layers[this.layers.length - 1].weights;
  3536. }
  3537. train(data, options = {}) {
  3538. const { preparedData, status, endTime } = this._prepTraining(data, options);
  3539. let continueTicking = true;
  3540. const calculateError = () => this._calculateTrainingError(preparedData);
  3541. const trainPatters = () => this._trainPatterns(preparedData);
  3542. while (continueTicking) {
  3543. continueTicking = this._trainingTick(status, endTime, calculateError, trainPatters);
  3544. }
  3545. return status;
  3546. }
  3547. _trainingTick(status, endTime, calculateError, trainPatterns) {
  3548. const { trainOpts } = this;
  3549. if (status.iterations >= trainOpts.iterations ||
  3550. status.error <= trainOpts.errorThresh ||
  3551. Date.now() >= endTime) {
  3552. return false;
  3553. }
  3554. if (typeof trainOpts.log === 'function' &&
  3555. status.iterations % trainOpts.logPeriod === 0) {
  3556. status.error = calculateError();
  3557. trainOpts.log(`iterations: ${status.iterations}, training error: ${status.error}`);
  3558. }
  3559. else if (status.iterations % trainOpts.errorCheckInterval ===
  3560. 0) {
  3561. status.error = calculateError();
  3562. }
  3563. else {
  3564. trainPatterns();
  3565. }
  3566. if (trainOpts.callback &&
  3567. status.iterations % trainOpts.callbackPeriod === 0) {
  3568. trainOpts.callback(Object.assign(status));
  3569. }
  3570. status.iterations++;
  3571. return true;
  3572. }
  3573. _prepTraining(data, options) {
  3574. this._updateTrainingOptions(options);
  3575. const formattedData = this.formatData(data);
  3576. const endTime = this.trainOpts.timeout
  3577. ? Date.now() + this.trainOpts.timeout
  3578. : 0;
  3579. const status = {
  3580. error: 1,
  3581. iterations: 0,
  3582. };
  3583. this.verifyIsInitialized();
  3584. return {
  3585. preparedData: this.transferData(formattedData),
  3586. status,
  3587. endTime,
  3588. };
  3589. }
  3590. verifyIsInitialized() {
  3591. if (!this._model) {
  3592. this.initialize();
  3593. }
  3594. }
  3595. _calculateTrainingError(preparedData) {
  3596. let sum = new Float32Array([0]);
  3597. const meanSquaredError = this.meanSquaredError;
  3598. for (let i = 0; i < preparedData.length; ++i) {
  3599. const prevSum = sum;
  3600. const error = this._trainPattern(preparedData[i].input, preparedData[i].output, true);
  3601. sum = meanSquaredError.add(sum, error);
  3602. release(error);
  3603. release(prevSum);
  3604. }
  3605. const result = meanSquaredError.divide(preparedData.length, sum);
  3606. release(sum);
  3607. if (result instanceof gpu_js.Texture) {
  3608. const resultArray = result.toArray();
  3609. release(result);
  3610. return resultArray[0];
  3611. }
  3612. return result[0];
  3613. }
  3614. /**
  3615. * @param data
  3616. * @private
  3617. */
  3618. _trainPatterns(data) {
  3619. for (let i = 0; i < data.length; ++i) {
  3620. this._trainPattern(data[i].input, data[i].output, false);
  3621. }
  3622. }
  3623. _trainPattern(input, target, logErrorRate) {
  3624. var _a;
  3625. // forward propagate
  3626. this.runInput(input);
  3627. // back propagate
  3628. this._calculateDeltas(target);
  3629. this.adjustWeights();
  3630. if (logErrorRate) {
  3631. if (!((_a = this._outputLayer) === null || _a === void 0 ? void 0 : _a.errors)) {
  3632. throw new Error('outputLayer.errors not defined');
  3633. }
  3634. return this.meanSquaredError.calculate(this._outputLayer.errors);
  3635. }
  3636. return null;
  3637. }
  3638. _calculateDeltas(target) {
  3639. const layers = this.layers;
  3640. for (let i = layers.length - 1; i > -1; i--) {
  3641. layers[i].compare(target);
  3642. }
  3643. }
  3644. /**
  3645. *
  3646. */
  3647. adjustWeights() {
  3648. const _model = this._model;
  3649. for (let i = 0; i < _model.length; i++) {
  3650. _model[i].learn(this.trainOpts.learningRate);
  3651. }
  3652. }
  3653. /**
  3654. *
  3655. * @param data
  3656. * @returns {*}
  3657. */
  3658. formatData(data) {
  3659. if (!Array.isArray(data)) {
  3660. // turn stream datum into array
  3661. const tmp = [];
  3662. tmp.push(data);
  3663. data = tmp;
  3664. }
  3665. // turn sparse hash input into arrays with 0s as filler
  3666. const inputDatumCheck = data[0].input;
  3667. let formattedData;
  3668. if (Array.isArray(data) &&
  3669. !Array.isArray(inputDatumCheck) &&
  3670. !(inputDatumCheck instanceof Float32Array)) {
  3671. if (!this.inputLookup) {
  3672. const lookupTable = new LookupTable(data, 'input');
  3673. this.inputLookup = lookupTable.table;
  3674. this.inputLookupLength = lookupTable.length;
  3675. }
  3676. formattedData = data.map((datumParam) => {
  3677. const array = lookup.toArray(this.inputLookup, datumParam.input, this.inputLookupLength);
  3678. return { input: array };
  3679. }, this);
  3680. }
  3681. else {
  3682. formattedData = data;
  3683. }
  3684. const outputDatumCheck = data[0].output;
  3685. if (!Array.isArray(outputDatumCheck) &&
  3686. !(outputDatumCheck instanceof Float32Array)) {
  3687. if (!this.outputLookup) {
  3688. const lookupTable = new LookupTable(data, 'output');
  3689. this.outputLookup = lookupTable.table;
  3690. this.outputLookupLength = lookupTable.length;
  3691. }
  3692. formattedData = data.map((datumParam, index) => {
  3693. const array = lookup.toArray(this.outputLookup, datumParam.output, this.inputLookupLength);
  3694. return {
  3695. input: formattedData[index].input,
  3696. output: array,
  3697. };
  3698. }, this);
  3699. }
  3700. return formattedData;
  3701. }
  3702. transferData(formattedData) {
  3703. const transferredData = new Array(formattedData.length);
  3704. const transferInput = makeKernel(function (value) {
  3705. return value[this.thread.x];
  3706. }, {
  3707. output: [formattedData[0].input.length],
  3708. immutable: true,
  3709. });
  3710. const transferOutput = makeKernel(function (value) {
  3711. return value[this.thread.x];
  3712. }, {
  3713. output: [formattedData[0].output.length],
  3714. immutable: true,
  3715. });
  3716. for (let i = 0; i < formattedData.length; i++) {
  3717. const formattedDatum = formattedData[i];
  3718. transferredData[i] = {
  3719. input: transferInput(formattedDatum.input),
  3720. output: transferOutput(formattedDatum.output),
  3721. };
  3722. }
  3723. return transferredData;
  3724. }
  3725. /**
  3726. *
  3727. * @param data
  3728. * @returns {
  3729. * {
  3730. * error: number,
  3731. * misclasses: Array
  3732. * }
  3733. * }
  3734. */
  3735. test() {
  3736. throw new Error(`${this.constructor.name}-test is not yet implemented`);
  3737. }
  3738. /**
  3739. *
  3740. */
  3741. toJSON() {
  3742. var _a;
  3743. if (!this.layers) {
  3744. this.initialize();
  3745. }
  3746. if (!this._model ||
  3747. !this.layers ||
  3748. !this._inputLayer ||
  3749. !this._hiddenLayers ||
  3750. !this._outputLayer) {
  3751. throw new Error('network is not initialized');
  3752. }
  3753. const jsonLayers = [];
  3754. for (let i = 0; i < this.layers.length; i++) {
  3755. const layer = this.layers[i];
  3756. const jsonLayer = layer.toJSON();
  3757. if (layer.hasOwnProperty('inputLayer')) {
  3758. jsonLayer.inputLayerIndex = this.layers.indexOf(layer.inputLayer);
  3759. }
  3760. else if (layer.hasOwnProperty('inputLayer1') &&
  3761. layer.hasOwnProperty('inputLayer2')) {
  3762. jsonLayer.inputLayer1Index = this.layers.indexOf(layer.inputLayer1);
  3763. jsonLayer.inputLayer2Index = this.layers.indexOf(layer.inputLayer2);
  3764. }
  3765. jsonLayers.push(jsonLayer);
  3766. }
  3767. return {
  3768. type: this.constructor.name,
  3769. sizes: (_a = this.options.sizes) !== null && _a !== void 0 ? _a : [this._inputLayer.height]
  3770. .concat(this._hiddenLayers.map((l) => l.height))
  3771. .concat([this._outputLayer.height]),
  3772. outputLayerIndex: this.layers.indexOf(this._outputLayer),
  3773. layers: jsonLayers,
  3774. inputLayerIndex: this.layers.indexOf(this._inputLayer),
  3775. };
  3776. }
  3777. static fromJSON(json, getLayer) {
  3778. var _a, _b, _c, _d;
  3779. const jsonLayers = json.layers;
  3780. const layers = [];
  3781. const inputLayer = getLayer
  3782. ? (_a = layerFromJSON(jsonLayers[0])) !== null && _a !== void 0 ? _a : getLayer(jsonLayers[0]) : layerFromJSON(jsonLayers[0]);
  3783. if (!inputLayer)
  3784. throw new Error('unable to find layer');
  3785. layers.push(inputLayer);
  3786. for (let i = 1; i < jsonLayers.length; i++) {
  3787. const jsonLayer = jsonLayers[i];
  3788. if (typeof jsonLayer.inputLayerIndex === 'undefined' &&
  3789. typeof jsonLayer.inputLayer1Index === 'undefined' &&
  3790. typeof jsonLayer.inputLayer2Index === 'undefined') {
  3791. const layer = getLayer
  3792. ? (_b = layerFromJSON(jsonLayer)) !== null && _b !== void 0 ? _b : getLayer(jsonLayer) : layerFromJSON(jsonLayer);
  3793. if (!layer)
  3794. throw new Error('unable to find layer');
  3795. layers.push(layer);
  3796. }
  3797. else if (typeof jsonLayer.inputLayerIndex === 'number') {
  3798. const inputLayer = layers[jsonLayer.inputLayerIndex];
  3799. if (!inputLayer) {
  3800. throw new Error('inputLayer1 not found');
  3801. }
  3802. const layer = getLayer
  3803. ? (_c = layerFromJSON(jsonLayer, inputLayer)) !== null && _c !== void 0 ? _c : getLayer(jsonLayer, inputLayer) : layerFromJSON(jsonLayer, inputLayer);
  3804. if (!layer)
  3805. throw new Error('unable to find layer');
  3806. layers.push(layer);
  3807. }
  3808. else {
  3809. if (typeof jsonLayer.inputLayer1Index !== 'number') {
  3810. throw new Error('Cannot create network from provided JSON. inputLayer1Index not defined.');
  3811. }
  3812. if (typeof jsonLayer.inputLayer2Index !== 'number') {
  3813. throw new Error('Cannot create network from provided JSON. inputLayer2Index not defined.');
  3814. }
  3815. const inputLayer1 = layers[jsonLayer.inputLayer1Index];
  3816. const inputLayer2 = layers[jsonLayer.inputLayer2Index];
  3817. if (inputLayer1 === undefined)
  3818. throw new Error(`Cannot create network from provided JSON. layer of index ${jsonLayer.inputLayer1Index} not found.`);
  3819. if (inputLayer2 === undefined)
  3820. throw new Error(`Cannot create network from provided JSON. layer of index ${jsonLayer.inputLayer2Index} not found.`);
  3821. const layer = getLayer
  3822. ? (_d = layerFromJSON(jsonLayer, inputLayer1, inputLayer2)) !== null && _d !== void 0 ? _d : getLayer(jsonLayer, inputLayer1, inputLayer2) : layerFromJSON(jsonLayer, inputLayer1, inputLayer2);
  3823. if (!layer)
  3824. throw new Error('unable to find layer');
  3825. layers.push(layer);
  3826. }
  3827. }
  3828. return new this({ ...json, layers });
  3829. }
  3830. /**
  3831. *
  3832. * @returns {Function}
  3833. */
  3834. toFunction() {
  3835. throw new Error(`${this.constructor.name}-toFunction is not yet implemented`);
  3836. }
  3837. /**
  3838. * This will create a TrainStream (WriteStream) for us to send the training data to.
  3839. * @param opts training options
  3840. * @returns {TrainStream|*}
  3841. */
  3842. createTrainStream() {
  3843. throw new Error(`${this.constructor.name}-createTrainStream is not yet implemented`);
  3844. }
  3845. }
  3846. function likely(input, net) {
  3847. if (!net) {
  3848. throw new TypeError(`Required parameter 'net' is of type ${typeof net}. Must be of type 'brain.NeuralNetwork'`);
  3849. }
  3850. const output = net.run(input);
  3851. let maxProp = null;
  3852. let maxValue = -1;
  3853. Object.entries(output).forEach(([key, value]) => {
  3854. if (typeof value !== 'undefined' &&
  3855. typeof value === 'number' &&
  3856. value > maxValue) {
  3857. maxProp = key;
  3858. maxValue = value;
  3859. }
  3860. });
  3861. return maxProp;
  3862. }
  3863. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  3864. function createCommonjsModule(fn, basedir, module) {
  3865. return module = {
  3866. path: basedir,
  3867. exports: {},
  3868. require: function (path, base) {
  3869. return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  3870. }
  3871. }, fn(module, module.exports), module.exports;
  3872. }
  3873. function commonjsRequire () {
  3874. throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  3875. }
  3876. var browser = createCommonjsModule(function (module, exports) {
  3877. var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () {
  3878. __assign = Object.assign || function(t) {
  3879. for (var s, i = 1, n = arguments.length; i < n; i++) {
  3880. s = arguments[i];
  3881. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  3882. t[p] = s[p];
  3883. }
  3884. return t;
  3885. };
  3886. return __assign.apply(this, arguments);
  3887. };
  3888. Object.defineProperty(exports, "__esModule", { value: true });
  3889. exports.thaw = exports.Block = exports.Thaw = void 0;
  3890. /**
  3891. * thaw an array of items
  3892. */
  3893. var Thaw = /** @class */ (function () {
  3894. function Thaw(items, options) {
  3895. var _this = this;
  3896. if (options === void 0) { options = {}; }
  3897. var _a = __assign(__assign({}, Thaw.defaultSettings), options), each = _a.each, done = _a.done;
  3898. this.i = 0;
  3899. this.isStopped = false;
  3900. this.items = items;
  3901. this.options = options;
  3902. this.tick = function () {
  3903. if (_this.isStopped)
  3904. return;
  3905. _this.timeout = setTimeout(_this.tick, 0);
  3906. if (Thaw.thawing)
  3907. return;
  3908. var item = _this.items[_this.i];
  3909. if (_this.i >= _this.items.length) {
  3910. if (done !== null) {
  3911. Thaw.thawing = true;
  3912. done();
  3913. Thaw.thawing = false;
  3914. }
  3915. _this.isStopped = true;
  3916. clearTimeout(_this.timeout);
  3917. return;
  3918. }
  3919. if (each !== null) {
  3920. Thaw.thawing = true;
  3921. each(item, _this.i);
  3922. Thaw.thawing = false;
  3923. }
  3924. else if (item !== undefined) {
  3925. item();
  3926. }
  3927. _this.i++;
  3928. };
  3929. Thaw.thaws.push(this);
  3930. if (!options.delay) {
  3931. this.tick();
  3932. }
  3933. }
  3934. Object.defineProperty(Thaw, "isThawing", {
  3935. /**
  3936. * returns if Thaw.js is thawing
  3937. */
  3938. get: function () {
  3939. return Thaw.thawing;
  3940. },
  3941. enumerable: false,
  3942. configurable: true
  3943. });
  3944. /**
  3945. * Stops all Thaw instances
  3946. */
  3947. Thaw.stopAll = function () {
  3948. for (var i = 0; i < Thaw.thaws.length; i++) {
  3949. Thaw.thaws[i].stop();
  3950. }
  3951. };
  3952. /**
  3953. * readies thaw to continue
  3954. */
  3955. Thaw.prototype.makeReady = function () {
  3956. if (this.isStopped) {
  3957. this.isStopped = false;
  3958. return true;
  3959. }
  3960. return false;
  3961. };
  3962. /**
  3963. * Adds an item to the end of this instance of Thaw and readies Thaw to process it
  3964. */
  3965. Thaw.prototype.add = function (item) {
  3966. this.items.push(item);
  3967. if (this.makeReady()) {
  3968. this.tick();
  3969. }
  3970. return this;
  3971. };
  3972. /**
  3973. * Inserts an item just after the current item being processed in Thaw and readies Thaw to process it
  3974. */
  3975. Thaw.prototype.insert = function (item) {
  3976. this.items.splice(this.i, 0, item);
  3977. if (this.makeReady()) {
  3978. this.tick();
  3979. }
  3980. return this;
  3981. };
  3982. /**
  3983. * Adds an Array to the end of this instance of Thaw and readies Thaw to process it
  3984. */
  3985. Thaw.prototype.addArray = function (items) {
  3986. this.items = this.items.concat(items);
  3987. if (this.makeReady()) {
  3988. this.tick();
  3989. }
  3990. return this;
  3991. };
  3992. /**
  3993. * Inserts an Array just after the current item being processed in Thaw and readies Thaw to process them
  3994. */
  3995. Thaw.prototype.insertArray = function (items) {
  3996. var before = this.items.splice(0, this.i);
  3997. var after = this.items;
  3998. this.items = before.concat(items, after);
  3999. if (this.makeReady()) {
  4000. this.tick();
  4001. }
  4002. return this;
  4003. };
  4004. /**
  4005. * Stops this instance of Thaw
  4006. */
  4007. Thaw.prototype.stop = function () {
  4008. this.isStopped = true;
  4009. clearTimeout(this.timeout);
  4010. if (this.options.done) {
  4011. this.options.done();
  4012. }
  4013. return this;
  4014. };
  4015. Thaw.thawing = false;
  4016. Thaw.thaws = [];
  4017. Thaw.defaultSettings = {
  4018. each: null,
  4019. done: null
  4020. };
  4021. return Thaw;
  4022. }());
  4023. exports.Thaw = Thaw;
  4024. /**
  4025. * simple thaw
  4026. */
  4027. function thaw(items, options) {
  4028. return new Thaw(items, options);
  4029. }
  4030. exports.thaw = thaw;
  4031. var Block = /** @class */ (function () {
  4032. function Block(options, count) {
  4033. if (count === void 0) { count = 200; }
  4034. this.index = 0;
  4035. this.thaws = [];
  4036. this.count = count;
  4037. this.options = options;
  4038. }
  4039. /**
  4040. * add an item to the end of items
  4041. */
  4042. Block.prototype.add = function (item) {
  4043. var next = this.next();
  4044. next.add(item);
  4045. return this;
  4046. };
  4047. /**
  4048. * add an Array to the end of items
  4049. */
  4050. Block.prototype.addArray = function (items) {
  4051. var next = this.next();
  4052. next.addArray(items);
  4053. return this;
  4054. };
  4055. /**
  4056. * insert an item into items @ current position
  4057. */
  4058. Block.prototype.insert = function (item) {
  4059. var next = this.next();
  4060. next.insert(item);
  4061. return this;
  4062. };
  4063. /**
  4064. * insert and array into items @ current position
  4065. */
  4066. Block.prototype.insertArray = function (items) {
  4067. var next = this.next();
  4068. next.insertArray(items);
  4069. return this;
  4070. };
  4071. /**
  4072. * Stops all thaws in this block
  4073. */
  4074. Block.prototype.stop = function () {
  4075. for (var i = 0; i < this.thaws.length; i++) {
  4076. this.thaws[i].stop();
  4077. }
  4078. return this;
  4079. };
  4080. /**
  4081. * Get next available in block
  4082. */
  4083. Block.prototype.next = function () {
  4084. var thaw;
  4085. var thaws = this.thaws;
  4086. if (thaws.length < this.count) {
  4087. thaw = new Thaw([], this.options);
  4088. thaws.push(thaw);
  4089. }
  4090. else {
  4091. thaw = thaws[this.index] || null;
  4092. }
  4093. this.index++;
  4094. if (this.index >= this.count) {
  4095. this.index = 0;
  4096. }
  4097. return thaw;
  4098. };
  4099. return Block;
  4100. }());
  4101. exports.Block = Block;
  4102. if (typeof window !== 'undefined') {
  4103. // @ts-ignore
  4104. window.Thaw = Thaw;
  4105. // @ts-ignore
  4106. window.thaw = thaw;
  4107. // @ts-ignore
  4108. window.Thaw.Block = Block;
  4109. }
  4110. });
  4111. function arraysToFloat32Arrays(arrays) {
  4112. const result = [];
  4113. for (let i = 0; i < arrays.length; i++) {
  4114. result.push(Float32Array.from(arrays[i]));
  4115. }
  4116. return result;
  4117. }
  4118. function inputOutputArraysToFloat32Arrays(input, output) {
  4119. const result = [];
  4120. for (let i = 0; i < input.length; i++) {
  4121. result.push(Float32Array.from(input[i]));
  4122. }
  4123. for (let i = 0; i < output.length; i++) {
  4124. result.push(Float32Array.from(output[i]));
  4125. }
  4126. return result;
  4127. }
  4128. function arrayToFloat32Arrays(array) {
  4129. const result = [];
  4130. for (let i = 0; i < array.length; i++) {
  4131. result.push(Float32Array.from([array[i]]));
  4132. }
  4133. return result;
  4134. }
  4135. function inputOutputArrayToFloat32Arrays(input, output) {
  4136. const result = [];
  4137. for (let i = 0; i < input.length; i++) {
  4138. result.push(Float32Array.from([input[i]]));
  4139. }
  4140. for (let i = 0; i < output.length; i++) {
  4141. result.push(Float32Array.from([output[i]]));
  4142. }
  4143. return result;
  4144. }
  4145. function arrayToFloat32Array(array) {
  4146. return Float32Array.from(array);
  4147. }
  4148. function inputOutputObjectsToFloat32Arrays(input, output, inputTable, outputTable, inputLength, outputLength) {
  4149. const results = [];
  4150. for (let i = 0; i < input.length; i++) {
  4151. const object = input[i];
  4152. const result = new Float32Array(inputLength);
  4153. for (const p in object) {
  4154. if (object.hasOwnProperty(p)) {
  4155. result[inputTable[p]] = object[p];
  4156. }
  4157. }
  4158. results.push(result);
  4159. }
  4160. for (let i = 0; i < output.length; i++) {
  4161. const object = output[i];
  4162. const result = new Float32Array(outputLength);
  4163. for (const p in object) {
  4164. if (object.hasOwnProperty(p)) {
  4165. result[outputTable[p]] = object[p];
  4166. }
  4167. }
  4168. results.push(result);
  4169. }
  4170. return results;
  4171. }
  4172. function objectToFloat32Arrays(object) {
  4173. const result = [];
  4174. for (const p in object) {
  4175. if (!object.hasOwnProperty(p))
  4176. continue;
  4177. result.push(Float32Array.from([object[p]]));
  4178. }
  4179. return result;
  4180. }
  4181. function inputOutputObjectToFloat32Arrays(input, output) {
  4182. const result = [];
  4183. for (const p in input) {
  4184. if (!input.hasOwnProperty(p))
  4185. continue;
  4186. result.push(Float32Array.from([input[p]]));
  4187. }
  4188. for (const p in output) {
  4189. if (!output.hasOwnProperty(p))
  4190. continue;
  4191. result.push(Float32Array.from([output[p]]));
  4192. }
  4193. return result;
  4194. }
  4195. function objectToFloat32Array(object, table, length) {
  4196. const result = new Float32Array(length);
  4197. for (const p in object) {
  4198. if (object.hasOwnProperty(p)) {
  4199. result[table[p]] = object[p];
  4200. }
  4201. }
  4202. return result;
  4203. }
  4204. function max(values) {
  4205. if (Array.isArray(values) || values instanceof Float32Array) {
  4206. return Math.max(...values);
  4207. }
  4208. else {
  4209. return Math.max(...Object.values(values));
  4210. }
  4211. }
  4212. function mse$1(errors) {
  4213. // mean squared error
  4214. let sum = 0;
  4215. for (let i = 0; i < errors.length; i++) {
  4216. sum += errors[i] ** 2;
  4217. }
  4218. return sum / errors.length;
  4219. }
  4220. function getTypedArrayFn(value, table) {
  4221. if (value.buffer instanceof ArrayBuffer) {
  4222. return null;
  4223. }
  4224. if (Array.isArray(value)) {
  4225. return arrayToFloat32Array;
  4226. }
  4227. if (!table)
  4228. throw new Error('table is not Object');
  4229. const { length } = Object.keys(table);
  4230. return (v) => {
  4231. const array = new Float32Array(length);
  4232. for (const p in table) {
  4233. if (!table.hasOwnProperty(p))
  4234. continue;
  4235. array[table[p]] = v[p] || 0;
  4236. }
  4237. return array;
  4238. };
  4239. }
  4240. function defaults$2() {
  4241. return {
  4242. inputSize: 0,
  4243. outputSize: 0,
  4244. binaryThresh: 0.5,
  4245. };
  4246. }
  4247. function trainDefaults$2() {
  4248. return {
  4249. activation: 'sigmoid',
  4250. iterations: 20000,
  4251. errorThresh: 0.005,
  4252. log: false,
  4253. logPeriod: 10,
  4254. leakyReluAlpha: 0.01,
  4255. learningRate: 0.3,
  4256. momentum: 0.1,
  4257. callbackPeriod: 10,
  4258. timeout: Infinity,
  4259. beta1: 0.9,
  4260. beta2: 0.999,
  4261. epsilon: 1e-8,
  4262. };
  4263. }
  4264. class NeuralNetwork {
  4265. constructor(options = {}) {
  4266. this.options = defaults$2();
  4267. this.trainOpts = trainDefaults$2();
  4268. this.sizes = [];
  4269. this.outputLayer = -1;
  4270. this.biases = [];
  4271. this.weights = []; // weights for bias nodes
  4272. this.outputs = [];
  4273. // state for training
  4274. this.deltas = [];
  4275. this.changes = []; // for momentum
  4276. this.errors = [];
  4277. this.errorCheckInterval = 1;
  4278. this.inputLookup = null;
  4279. this.inputLookupLength = 0;
  4280. this.outputLookup = null;
  4281. this.outputLookupLength = 0;
  4282. this._formatInput = null;
  4283. this._formatOutput = null;
  4284. this.runInput = (input) => {
  4285. this.setActivation();
  4286. return this.runInput(input);
  4287. };
  4288. this.calculateDeltas = (output) => {
  4289. this.setActivation();
  4290. return this.calculateDeltas(output);
  4291. };
  4292. // adam
  4293. this.biasChangesLow = [];
  4294. this.biasChangesHigh = [];
  4295. this.changesLow = [];
  4296. this.changesHigh = [];
  4297. this.iterations = 0;
  4298. this.options = { ...this.options, ...options };
  4299. this.updateTrainingOptions(options);
  4300. const { inputSize, hiddenLayers, outputSize } = this.options;
  4301. if (inputSize && outputSize) {
  4302. this.sizes = [inputSize].concat(hiddenLayers !== null && hiddenLayers !== void 0 ? hiddenLayers : []).concat([outputSize]);
  4303. }
  4304. }
  4305. /**
  4306. *
  4307. * Expects this.sizes to have been set
  4308. */
  4309. initialize() {
  4310. if (!this.sizes.length) {
  4311. throw new Error('Sizes must be set before initializing');
  4312. }
  4313. this.outputLayer = this.sizes.length - 1;
  4314. this.biases = new Array(this.outputLayer); // weights for bias nodes
  4315. this.weights = new Array(this.outputLayer);
  4316. this.outputs = new Array(this.outputLayer);
  4317. // state for training
  4318. this.deltas = new Array(this.outputLayer);
  4319. this.changes = new Array(this.outputLayer); // for momentum
  4320. this.errors = new Array(this.outputLayer);
  4321. for (let layerIndex = 0; layerIndex <= this.outputLayer; layerIndex++) {
  4322. const size = this.sizes[layerIndex];
  4323. this.deltas[layerIndex] = zeros$1(size);
  4324. this.errors[layerIndex] = zeros$1(size);
  4325. this.outputs[layerIndex] = zeros$1(size);
  4326. if (layerIndex > 0) {
  4327. this.biases[layerIndex] = randos(size);
  4328. this.weights[layerIndex] = new Array(size);
  4329. this.changes[layerIndex] = new Array(size);
  4330. for (let nodeIndex = 0; nodeIndex < size; nodeIndex++) {
  4331. const prevSize = this.sizes[layerIndex - 1];
  4332. this.weights[layerIndex][nodeIndex] = randos(prevSize);
  4333. this.changes[layerIndex][nodeIndex] = zeros$1(prevSize);
  4334. }
  4335. }
  4336. }
  4337. this.setActivation();
  4338. if (this.trainOpts.praxis === 'adam') {
  4339. this._setupAdam();
  4340. }
  4341. }
  4342. setActivation(activation) {
  4343. const value = activation !== null && activation !== void 0 ? activation : this.trainOpts.activation;
  4344. switch (value) {
  4345. case 'sigmoid':
  4346. this.runInput = this._runInputSigmoid;
  4347. this.calculateDeltas = this._calculateDeltasSigmoid;
  4348. break;
  4349. case 'relu':
  4350. this.runInput = this._runInputRelu;
  4351. this.calculateDeltas = this._calculateDeltasRelu;
  4352. break;
  4353. case 'leaky-relu':
  4354. this.runInput = this._runInputLeakyRelu;
  4355. this.calculateDeltas = this._calculateDeltasLeakyRelu;
  4356. break;
  4357. case 'tanh':
  4358. this.runInput = this._runInputTanh;
  4359. this.calculateDeltas = this._calculateDeltasTanh;
  4360. break;
  4361. default:
  4362. throw new Error(`Unknown activation ${value}. Available activations are: 'sigmoid', 'relu', 'leaky-relu', 'tanh'`);
  4363. }
  4364. }
  4365. get isRunnable() {
  4366. return this.sizes.length > 0;
  4367. }
  4368. run(input) {
  4369. if (!this.isRunnable) {
  4370. throw new Error('network not runnable');
  4371. }
  4372. let formattedInput;
  4373. if (this.inputLookup) {
  4374. formattedInput = lookup.toArray(this.inputLookup, input, this.inputLookupLength);
  4375. }
  4376. else {
  4377. formattedInput = input;
  4378. }
  4379. if (formattedInput.length !== this.sizes[0]) {
  4380. throw new Error(`input is not in correct length of ${this.sizes[0]}`);
  4381. }
  4382. const output = this.runInput(formattedInput).slice(0);
  4383. if (this.outputLookup) {
  4384. return lookup.toObject(this.outputLookup, output);
  4385. }
  4386. return output;
  4387. }
  4388. _runInputSigmoid(input) {
  4389. this.outputs[0] = input; // set output state of input layer
  4390. let output = null;
  4391. for (let layer = 1; layer <= this.outputLayer; layer++) {
  4392. const activeLayer = this.sizes[layer];
  4393. const activeWeights = this.weights[layer];
  4394. const activeBiases = this.biases[layer];
  4395. const activeOutputs = this.outputs[layer];
  4396. for (let node = 0; node < activeLayer; node++) {
  4397. const weights = activeWeights[node];
  4398. let sum = activeBiases[node];
  4399. for (let k = 0; k < weights.length; k++) {
  4400. sum += weights[k] * input[k];
  4401. }
  4402. // sigmoid
  4403. activeOutputs[node] = 1 / (1 + Math.exp(-sum));
  4404. }
  4405. output = input = activeOutputs;
  4406. }
  4407. if (!output) {
  4408. throw new Error('output was empty');
  4409. }
  4410. return output;
  4411. }
  4412. _runInputRelu(input) {
  4413. this.outputs[0] = input; // set output state of input layer
  4414. let output = null;
  4415. for (let layer = 1; layer <= this.outputLayer; layer++) {
  4416. const activeSize = this.sizes[layer];
  4417. const activeWeights = this.weights[layer];
  4418. const activeBiases = this.biases[layer];
  4419. const activeOutputs = this.outputs[layer];
  4420. for (let node = 0; node < activeSize; node++) {
  4421. const weights = activeWeights[node];
  4422. let sum = activeBiases[node];
  4423. for (let k = 0; k < weights.length; k++) {
  4424. sum += weights[k] * input[k];
  4425. }
  4426. // relu
  4427. activeOutputs[node] = sum < 0 ? 0 : sum;
  4428. }
  4429. output = input = activeOutputs;
  4430. }
  4431. if (!output) {
  4432. throw new Error('output was empty');
  4433. }
  4434. return output;
  4435. }
  4436. _runInputLeakyRelu(input) {
  4437. this.outputs[0] = input; // set output state of input layer
  4438. const { leakyReluAlpha } = this.trainOpts;
  4439. let output = null;
  4440. for (let layer = 1; layer <= this.outputLayer; layer++) {
  4441. const activeSize = this.sizes[layer];
  4442. const activeWeights = this.weights[layer];
  4443. const activeBiases = this.biases[layer];
  4444. const activeOutputs = this.outputs[layer];
  4445. for (let node = 0; node < activeSize; node++) {
  4446. const weights = activeWeights[node];
  4447. let sum = activeBiases[node];
  4448. for (let k = 0; k < weights.length; k++) {
  4449. sum += weights[k] * input[k];
  4450. }
  4451. // leaky relu
  4452. activeOutputs[node] = Math.max(sum, leakyReluAlpha * sum);
  4453. }
  4454. output = input = activeOutputs;
  4455. }
  4456. if (!output) {
  4457. throw new Error('output was empty');
  4458. }
  4459. return output;
  4460. }
  4461. _runInputTanh(input) {
  4462. this.outputs[0] = input; // set output state of input layer
  4463. let output = null;
  4464. for (let layer = 1; layer <= this.outputLayer; layer++) {
  4465. const activeSize = this.sizes[layer];
  4466. const activeWeights = this.weights[layer];
  4467. const activeBiases = this.biases[layer];
  4468. const activeOutputs = this.outputs[layer];
  4469. for (let node = 0; node < activeSize; node++) {
  4470. const weights = activeWeights[node];
  4471. let sum = activeBiases[node];
  4472. for (let k = 0; k < weights.length; k++) {
  4473. sum += weights[k] * input[k];
  4474. }
  4475. // tanh
  4476. activeOutputs[node] = Math.tanh(sum);
  4477. }
  4478. output = input = activeOutputs;
  4479. }
  4480. if (!output) {
  4481. throw new Error('output was empty');
  4482. }
  4483. return output;
  4484. }
  4485. /**
  4486. *
  4487. * Verifies network sizes are initialized
  4488. * If they are not it will initialize them based off the data set.
  4489. */
  4490. verifyIsInitialized(preparedData) {
  4491. if (this.sizes.length)
  4492. return;
  4493. this.sizes = [];
  4494. this.sizes.push(preparedData[0].input.length);
  4495. if (!this.options.hiddenLayers) {
  4496. this.sizes.push(Math.max(3, Math.floor(preparedData[0].input.length / 2)));
  4497. }
  4498. else {
  4499. this.options.hiddenLayers.forEach((size) => {
  4500. this.sizes.push(size);
  4501. });
  4502. }
  4503. this.sizes.push(preparedData[0].output.length);
  4504. this.initialize();
  4505. }
  4506. updateTrainingOptions(trainOpts) {
  4507. const merged = { ...this.trainOpts, ...trainOpts };
  4508. this.validateTrainingOptions(merged);
  4509. this.trainOpts = merged;
  4510. this.setLogMethod(this.trainOpts.log);
  4511. }
  4512. validateTrainingOptions(options) {
  4513. const validations = {
  4514. activation: () => {
  4515. return ['sigmoid', 'relu', 'leaky-relu', 'tanh'].includes(options.activation);
  4516. },
  4517. iterations: () => {
  4518. const val = options.iterations;
  4519. return typeof val === 'number' && val > 0;
  4520. },
  4521. errorThresh: () => {
  4522. const val = options.errorThresh;
  4523. return typeof val === 'number' && val > 0 && val < 1;
  4524. },
  4525. log: () => {
  4526. const val = options.log;
  4527. return typeof val === 'function' || typeof val === 'boolean';
  4528. },
  4529. logPeriod: () => {
  4530. const val = options.logPeriod;
  4531. return typeof val === 'number' && val > 0;
  4532. },
  4533. leakyReluAlpha: () => {
  4534. const val = options.leakyReluAlpha;
  4535. return typeof val === 'number' && val > 0 && val < 1;
  4536. },
  4537. learningRate: () => {
  4538. const val = options.learningRate;
  4539. return typeof val === 'number' && val > 0 && val < 1;
  4540. },
  4541. momentum: () => {
  4542. const val = options.momentum;
  4543. return typeof val === 'number' && val > 0 && val < 1;
  4544. },
  4545. callback: () => {
  4546. const val = options.callback;
  4547. return typeof val === 'function' || val === undefined;
  4548. },
  4549. callbackPeriod: () => {
  4550. const val = options.callbackPeriod;
  4551. return typeof val === 'number' && val > 0;
  4552. },
  4553. timeout: () => {
  4554. const val = options.timeout;
  4555. return typeof val === 'number' && val > 0;
  4556. },
  4557. praxis: () => {
  4558. const val = options.praxis;
  4559. return !val || val === 'adam';
  4560. },
  4561. beta1: () => {
  4562. const val = options.beta1;
  4563. return val > 0 && val < 1;
  4564. },
  4565. beta2: () => {
  4566. const val = options.beta2;
  4567. return val > 0 && val < 1;
  4568. },
  4569. epsilon: () => {
  4570. const val = options.epsilon;
  4571. return val > 0 && val < 1;
  4572. },
  4573. };
  4574. for (const p in validations) {
  4575. const v = options;
  4576. if (!validations[p]()) {
  4577. throw new Error(`[${p}, ${v[p]}] is out of normal training range, your network will probably not train.`);
  4578. }
  4579. }
  4580. }
  4581. /**
  4582. *
  4583. * Gets JSON of trainOpts object
  4584. * NOTE: Activation is stored directly on JSON object and not in the training options
  4585. */
  4586. getTrainOptsJSON() {
  4587. const { activation, iterations, errorThresh, log, logPeriod, leakyReluAlpha, learningRate, momentum, callbackPeriod, timeout, praxis, beta1, beta2, epsilon, } = this.trainOpts;
  4588. return {
  4589. activation,
  4590. iterations,
  4591. errorThresh,
  4592. log: typeof log === 'function'
  4593. ? true
  4594. : typeof log === 'boolean'
  4595. ? log
  4596. : false,
  4597. logPeriod,
  4598. leakyReluAlpha,
  4599. learningRate,
  4600. momentum,
  4601. callbackPeriod,
  4602. timeout: timeout === Infinity ? 'Infinity' : timeout,
  4603. praxis,
  4604. beta1,
  4605. beta2,
  4606. epsilon,
  4607. };
  4608. }
  4609. setLogMethod(log) {
  4610. if (typeof log === 'function') {
  4611. this.trainOpts.log = log;
  4612. }
  4613. else if (log) {
  4614. this.trainOpts.log = this.logTrainingStatus;
  4615. }
  4616. else {
  4617. this.trainOpts.log = false;
  4618. }
  4619. }
  4620. logTrainingStatus(status) {
  4621. console.log(`iterations: ${status.iterations}, training error: ${status.error}`);
  4622. }
  4623. calculateTrainingError(data) {
  4624. let sum = 0;
  4625. for (let i = 0; i < data.length; ++i) {
  4626. sum += this.trainPattern(data[i], true);
  4627. }
  4628. return sum / data.length;
  4629. }
  4630. trainPatterns(data) {
  4631. for (let i = 0; i < data.length; ++i) {
  4632. this.trainPattern(data[i]);
  4633. }
  4634. }
  4635. trainingTick(data, status, endTime) {
  4636. const { callback, callbackPeriod, errorThresh, iterations, log, logPeriod, } = this.trainOpts;
  4637. if (status.iterations >= iterations ||
  4638. status.error <= errorThresh ||
  4639. Date.now() >= endTime) {
  4640. return false;
  4641. }
  4642. status.iterations++;
  4643. if (log && status.iterations % logPeriod === 0) {
  4644. status.error = this.calculateTrainingError(data);
  4645. log(status);
  4646. }
  4647. else if (status.iterations % this.errorCheckInterval === 0) {
  4648. status.error = this.calculateTrainingError(data);
  4649. }
  4650. else {
  4651. this.trainPatterns(data);
  4652. }
  4653. if (callback && status.iterations % callbackPeriod === 0) {
  4654. callback({
  4655. iterations: status.iterations,
  4656. error: status.error,
  4657. });
  4658. }
  4659. return true;
  4660. }
  4661. prepTraining(data, options = {}) {
  4662. this.updateTrainingOptions(options);
  4663. const preparedData = this.formatData(data);
  4664. const endTime = Date.now() + this.trainOpts.timeout;
  4665. const status = {
  4666. error: 1,
  4667. iterations: 0,
  4668. };
  4669. this.verifyIsInitialized(preparedData);
  4670. return {
  4671. preparedData,
  4672. status,
  4673. endTime,
  4674. };
  4675. }
  4676. train(data, options = {}) {
  4677. const { preparedData, status, endTime } = this.prepTraining(data, options);
  4678. while (true) {
  4679. if (!this.trainingTick(preparedData, status, endTime)) {
  4680. break;
  4681. }
  4682. }
  4683. return status;
  4684. }
  4685. async trainAsync(data, options = {}) {
  4686. const { preparedData, status, endTime } = this.prepTraining(data, options);
  4687. return await new Promise((resolve, reject) => {
  4688. try {
  4689. const thawedTrain = new browser.Thaw(new Array(this.trainOpts.iterations), {
  4690. delay: true,
  4691. each: () => this.trainingTick(preparedData, status, endTime) ||
  4692. thawedTrain.stop(),
  4693. done: () => resolve(status),
  4694. });
  4695. thawedTrain.tick();
  4696. }
  4697. catch (trainError) {
  4698. reject(trainError);
  4699. }
  4700. });
  4701. }
  4702. trainPattern(value, logErrorRate) {
  4703. // forward propagate
  4704. this.runInput(value.input);
  4705. // back propagate
  4706. this.calculateDeltas(value.output);
  4707. this.adjustWeights();
  4708. if (logErrorRate) {
  4709. return mse$1(this.errors[this.outputLayer]);
  4710. }
  4711. return null;
  4712. }
  4713. _calculateDeltasSigmoid(target) {
  4714. for (let layer = this.outputLayer; layer >= 0; layer--) {
  4715. const activeSize = this.sizes[layer];
  4716. const activeOutput = this.outputs[layer];
  4717. const activeError = this.errors[layer];
  4718. const activeDeltas = this.deltas[layer];
  4719. const nextLayer = this.weights[layer + 1];
  4720. for (let node = 0; node < activeSize; node++) {
  4721. const output = activeOutput[node];
  4722. let error = 0;
  4723. if (layer === this.outputLayer) {
  4724. error = target[node] - output;
  4725. }
  4726. else {
  4727. const deltas = this.deltas[layer + 1];
  4728. for (let k = 0; k < deltas.length; k++) {
  4729. error += deltas[k] * nextLayer[k][node];
  4730. }
  4731. }
  4732. activeError[node] = error;
  4733. activeDeltas[node] = error * output * (1 - output);
  4734. }
  4735. }
  4736. }
  4737. _calculateDeltasRelu(target) {
  4738. for (let layer = this.outputLayer; layer >= 0; layer--) {
  4739. const currentSize = this.sizes[layer];
  4740. const currentOutputs = this.outputs[layer];
  4741. const nextWeights = this.weights[layer + 1];
  4742. const nextDeltas = this.deltas[layer + 1];
  4743. const currentErrors = this.errors[layer];
  4744. const currentDeltas = this.deltas[layer];
  4745. for (let node = 0; node < currentSize; node++) {
  4746. const output = currentOutputs[node];
  4747. let error = 0;
  4748. if (layer === this.outputLayer) {
  4749. error = target[node] - output;
  4750. }
  4751. else {
  4752. for (let k = 0; k < nextDeltas.length; k++) {
  4753. error += nextDeltas[k] * nextWeights[k][node];
  4754. }
  4755. }
  4756. currentErrors[node] = error;
  4757. currentDeltas[node] = output > 0 ? error : 0;
  4758. }
  4759. }
  4760. }
  4761. _calculateDeltasLeakyRelu(target) {
  4762. const alpha = this.trainOpts.leakyReluAlpha;
  4763. for (let layer = this.outputLayer; layer >= 0; layer--) {
  4764. const currentSize = this.sizes[layer];
  4765. const currentOutputs = this.outputs[layer];
  4766. const nextDeltas = this.deltas[layer + 1];
  4767. const nextWeights = this.weights[layer + 1];
  4768. const currentErrors = this.errors[layer];
  4769. const currentDeltas = this.deltas[layer];
  4770. for (let node = 0; node < currentSize; node++) {
  4771. const output = currentOutputs[node];
  4772. let error = 0;
  4773. if (layer === this.outputLayer) {
  4774. error = target[node] - output;
  4775. }
  4776. else {
  4777. for (let k = 0; k < nextDeltas.length; k++) {
  4778. error += nextDeltas[k] * nextWeights[k][node];
  4779. }
  4780. }
  4781. currentErrors[node] = error;
  4782. currentDeltas[node] = output > 0 ? error : alpha * error;
  4783. }
  4784. }
  4785. }
  4786. _calculateDeltasTanh(target) {
  4787. for (let layer = this.outputLayer; layer >= 0; layer--) {
  4788. const currentSize = this.sizes[layer];
  4789. const currentOutputs = this.outputs[layer];
  4790. const nextDeltas = this.deltas[layer + 1];
  4791. const nextWeights = this.weights[layer + 1];
  4792. const currentErrors = this.errors[layer];
  4793. const currentDeltas = this.deltas[layer];
  4794. for (let node = 0; node < currentSize; node++) {
  4795. const output = currentOutputs[node];
  4796. let error = 0;
  4797. if (layer === this.outputLayer) {
  4798. error = target[node] - output;
  4799. }
  4800. else {
  4801. for (let k = 0; k < nextDeltas.length; k++) {
  4802. error += nextDeltas[k] * nextWeights[k][node];
  4803. }
  4804. }
  4805. currentErrors[node] = error;
  4806. currentDeltas[node] = (1 - output * output) * error;
  4807. }
  4808. }
  4809. }
  4810. /**
  4811. *
  4812. * Changes weights of networks
  4813. */
  4814. adjustWeights() {
  4815. const { learningRate, momentum } = this.trainOpts;
  4816. for (let layer = 1; layer <= this.outputLayer; layer++) {
  4817. const incoming = this.outputs[layer - 1];
  4818. const activeSize = this.sizes[layer];
  4819. const activeDelta = this.deltas[layer];
  4820. const activeChanges = this.changes[layer];
  4821. const activeWeights = this.weights[layer];
  4822. const activeBiases = this.biases[layer];
  4823. for (let node = 0; node < activeSize; node++) {
  4824. const delta = activeDelta[node];
  4825. for (let k = 0; k < incoming.length; k++) {
  4826. let change = activeChanges[node][k];
  4827. change = learningRate * delta * incoming[k] + momentum * change;
  4828. activeChanges[node][k] = change;
  4829. activeWeights[node][k] += change;
  4830. }
  4831. activeBiases[node] += learningRate * delta;
  4832. }
  4833. }
  4834. }
  4835. _setupAdam() {
  4836. this.biasChangesLow = [];
  4837. this.biasChangesHigh = [];
  4838. this.changesLow = [];
  4839. this.changesHigh = [];
  4840. this.iterations = 0;
  4841. for (let layer = 0; layer <= this.outputLayer; layer++) {
  4842. const size = this.sizes[layer];
  4843. if (layer > 0) {
  4844. this.biasChangesLow[layer] = zeros$1(size);
  4845. this.biasChangesHigh[layer] = zeros$1(size);
  4846. this.changesLow[layer] = new Array(size);
  4847. this.changesHigh[layer] = new Array(size);
  4848. for (let node = 0; node < size; node++) {
  4849. const prevSize = this.sizes[layer - 1];
  4850. this.changesLow[layer][node] = zeros$1(prevSize);
  4851. this.changesHigh[layer][node] = zeros$1(prevSize);
  4852. }
  4853. }
  4854. }
  4855. this.adjustWeights = this._adjustWeightsAdam;
  4856. }
  4857. _adjustWeightsAdam() {
  4858. this.iterations++;
  4859. const { iterations } = this;
  4860. const { beta1, beta2, epsilon, learningRate } = this.trainOpts;
  4861. for (let layer = 1; layer <= this.outputLayer; layer++) {
  4862. const incoming = this.outputs[layer - 1];
  4863. const currentSize = this.sizes[layer];
  4864. const currentDeltas = this.deltas[layer];
  4865. const currentChangesLow = this.changesLow[layer];
  4866. const currentChangesHigh = this.changesHigh[layer];
  4867. const currentWeights = this.weights[layer];
  4868. const currentBiases = this.biases[layer];
  4869. const currentBiasChangesLow = this.biasChangesLow[layer];
  4870. const currentBiasChangesHigh = this.biasChangesHigh[layer];
  4871. for (let node = 0; node < currentSize; node++) {
  4872. const delta = currentDeltas[node];
  4873. for (let k = 0; k < incoming.length; k++) {
  4874. const gradient = delta * incoming[k];
  4875. const changeLow = currentChangesLow[node][k] * beta1 + (1 - beta1) * gradient;
  4876. const changeHigh = currentChangesHigh[node][k] * beta2 +
  4877. (1 - beta2) * gradient * gradient;
  4878. const momentumCorrection = changeLow / (1 - Math.pow(beta1, iterations));
  4879. const gradientCorrection = changeHigh / (1 - Math.pow(beta2, iterations));
  4880. currentChangesLow[node][k] = changeLow;
  4881. currentChangesHigh[node][k] = changeHigh;
  4882. currentWeights[node][k] +=
  4883. (learningRate * momentumCorrection) /
  4884. (Math.sqrt(gradientCorrection) + epsilon);
  4885. }
  4886. const biasGradient = currentDeltas[node];
  4887. const biasChangeLow = currentBiasChangesLow[node] * beta1 + (1 - beta1) * biasGradient;
  4888. const biasChangeHigh = currentBiasChangesHigh[node] * beta2 +
  4889. (1 - beta2) * biasGradient * biasGradient;
  4890. const biasMomentumCorrection = currentBiasChangesLow[node] / (1 - Math.pow(beta1, iterations));
  4891. const biasGradientCorrection = currentBiasChangesHigh[node] / (1 - Math.pow(beta2, iterations));
  4892. currentBiasChangesLow[node] = biasChangeLow;
  4893. currentBiasChangesHigh[node] = biasChangeHigh;
  4894. currentBiases[node] +=
  4895. (learningRate * biasMomentumCorrection) /
  4896. (Math.sqrt(biasGradientCorrection) + epsilon);
  4897. }
  4898. }
  4899. }
  4900. formatData(data) {
  4901. if (!Array.isArray(data[0].input)) {
  4902. if (this.inputLookup) {
  4903. this.inputLookupLength = Object.keys(this.inputLookup).length;
  4904. }
  4905. else {
  4906. const inputLookup = new LookupTable(data, 'input');
  4907. this.inputLookup = inputLookup.table;
  4908. this.inputLookupLength = inputLookup.length;
  4909. }
  4910. }
  4911. if (!Array.isArray(data[0].output)) {
  4912. if (this.outputLookup) {
  4913. this.outputLookupLength = Object.keys(this.outputLookup).length;
  4914. }
  4915. else {
  4916. const lookup = new LookupTable(data, 'output');
  4917. this.outputLookup = lookup.table;
  4918. this.outputLookupLength = lookup.length;
  4919. }
  4920. }
  4921. if (!this._formatInput) {
  4922. this._formatInput = getTypedArrayFn(data[0].input, this.inputLookup);
  4923. }
  4924. if (!this._formatOutput) {
  4925. this._formatOutput = getTypedArrayFn(data[0].output, this.outputLookup);
  4926. }
  4927. // turn sparse hash input into arrays with 0s as filler
  4928. if (this._formatInput && this._formatOutput) {
  4929. const result = [];
  4930. for (let i = 0; i < data.length; i++) {
  4931. result.push({
  4932. input: this._formatInput(data[i].input),
  4933. output: this._formatOutput(data[i].output),
  4934. });
  4935. }
  4936. return result;
  4937. }
  4938. if (this._formatInput) {
  4939. const result = [];
  4940. for (let i = 0; i < data.length; i++) {
  4941. result.push({
  4942. input: this._formatInput(data[i].input),
  4943. output: data[i].output,
  4944. });
  4945. }
  4946. return result;
  4947. }
  4948. if (this._formatOutput) {
  4949. const result = [];
  4950. for (let i = 0; i < data.length; i++) {
  4951. result.push({
  4952. input: data[i].input,
  4953. output: this._formatOutput(data[i].output),
  4954. });
  4955. }
  4956. return result;
  4957. }
  4958. return data;
  4959. }
  4960. addFormat(data) {
  4961. var _a, _b;
  4962. if (!Array.isArray(data.input) || typeof data.input[0] !== 'number') {
  4963. this.inputLookup = lookup.addKeys(data.input, (_a = this.inputLookup) !== null && _a !== void 0 ? _a : {});
  4964. if (this.inputLookup) {
  4965. this.inputLookupLength = Object.keys(this.inputLookup).length;
  4966. }
  4967. }
  4968. if (!Array.isArray(data.output) || typeof data.output[0] !== 'number') {
  4969. this.outputLookup = lookup.addKeys(data.output, (_b = this.outputLookup) !== null && _b !== void 0 ? _b : {});
  4970. if (this.outputLookup) {
  4971. this.outputLookupLength = Object.keys(this.outputLookup).length;
  4972. }
  4973. }
  4974. }
  4975. test(data) {
  4976. const { preparedData } = this.prepTraining(data);
  4977. // for binary classification problems with one output node
  4978. const isBinary = preparedData[0].output.length === 1;
  4979. // for classification problems
  4980. const misclasses = [];
  4981. // run each pattern through the trained network and collect
  4982. // error and misclassification statistics
  4983. let errorSum = 0;
  4984. if (isBinary) {
  4985. let falsePos = 0;
  4986. let falseNeg = 0;
  4987. let truePos = 0;
  4988. let trueNeg = 0;
  4989. for (let i = 0; i < preparedData.length; i++) {
  4990. const output = this.runInput(preparedData[i].input);
  4991. const target = preparedData[i].output;
  4992. const actual = output[0] > this.options.binaryThresh ? 1 : 0;
  4993. const expected = target[0];
  4994. if (actual !== expected) {
  4995. const misclass = preparedData[i];
  4996. misclasses.push({
  4997. input: misclass.input,
  4998. output: misclass.output,
  4999. actual,
  5000. expected,
  5001. });
  5002. }
  5003. if (actual === 0 && expected === 0) {
  5004. trueNeg++;
  5005. }
  5006. else if (actual === 1 && expected === 1) {
  5007. truePos++;
  5008. }
  5009. else if (actual === 0 && expected === 1) {
  5010. falseNeg++;
  5011. }
  5012. else if (actual === 1 && expected === 0) {
  5013. falsePos++;
  5014. }
  5015. errorSum += mse$1(output.map((value, i) => {
  5016. return target[i] - value;
  5017. }));
  5018. }
  5019. return {
  5020. error: errorSum / preparedData.length,
  5021. misclasses,
  5022. total: preparedData.length,
  5023. trueNeg,
  5024. truePos,
  5025. falseNeg,
  5026. falsePos,
  5027. precision: truePos > 0 ? truePos / (truePos + falsePos) : 0,
  5028. recall: truePos > 0 ? truePos / (truePos + falseNeg) : 0,
  5029. accuracy: (trueNeg + truePos) / preparedData.length,
  5030. };
  5031. }
  5032. for (let i = 0; i < preparedData.length; i++) {
  5033. const output = this.runInput(preparedData[i].input);
  5034. const target = preparedData[i].output;
  5035. const actual = output.indexOf(max(output));
  5036. const expected = target.indexOf(max(target));
  5037. if (actual !== expected) {
  5038. const misclass = preparedData[i];
  5039. misclasses.push({
  5040. input: misclass.input,
  5041. output: misclass.output,
  5042. actual,
  5043. expected,
  5044. });
  5045. }
  5046. errorSum += mse$1(output.map((value, i) => {
  5047. return target[i] - value;
  5048. }));
  5049. }
  5050. return {
  5051. error: errorSum / preparedData.length,
  5052. misclasses,
  5053. total: preparedData.length,
  5054. };
  5055. }
  5056. toJSON() {
  5057. var _a, _b;
  5058. if (!this.isRunnable) {
  5059. this.initialize();
  5060. }
  5061. // use Array.from, keeping json small
  5062. const jsonLayerWeights = this.weights.map((layerWeights) => {
  5063. return layerWeights.map((layerWeights) => Array.from(layerWeights));
  5064. });
  5065. const jsonLayerBiases = this.biases.map((layerBiases) => Array.from(layerBiases));
  5066. const jsonLayers = [];
  5067. const outputLength = this.sizes.length - 1;
  5068. for (let i = 0; i <= outputLength; i++) {
  5069. jsonLayers.push({
  5070. weights: (_a = jsonLayerWeights[i]) !== null && _a !== void 0 ? _a : [],
  5071. biases: (_b = jsonLayerBiases[i]) !== null && _b !== void 0 ? _b : [],
  5072. });
  5073. }
  5074. return {
  5075. type: 'NeuralNetwork',
  5076. sizes: [...this.sizes],
  5077. layers: jsonLayers,
  5078. inputLookup: this.inputLookup ? { ...this.inputLookup } : null,
  5079. inputLookupLength: this.inputLookupLength,
  5080. outputLookup: this.outputLookup ? { ...this.outputLookup } : null,
  5081. outputLookupLength: this.outputLookupLength,
  5082. options: { ...this.options },
  5083. trainOpts: this.getTrainOptsJSON(),
  5084. };
  5085. }
  5086. fromJSON(json) {
  5087. this.options = { ...defaults$2(), ...json.options };
  5088. if (json.hasOwnProperty('trainOpts')) {
  5089. const trainOpts = {
  5090. ...json.trainOpts,
  5091. timeout: json.trainOpts.timeout === 'Infinity'
  5092. ? Infinity
  5093. : json.trainOpts.timeout,
  5094. };
  5095. this.updateTrainingOptions(trainOpts);
  5096. }
  5097. this.sizes = json.sizes;
  5098. this.initialize();
  5099. this.inputLookup = json.inputLookup ? { ...json.inputLookup } : null;
  5100. this.inputLookupLength = json.inputLookupLength;
  5101. this.outputLookup = json.outputLookup ? { ...json.outputLookup } : null;
  5102. this.outputLookupLength = json.outputLookupLength;
  5103. const jsonLayers = json.layers;
  5104. const layerWeights = this.weights.map((layerWeights, layerIndex) => {
  5105. return jsonLayers[layerIndex].weights.map((layerWeights) => Float32Array.from(layerWeights));
  5106. });
  5107. const layerBiases = this.biases.map((layerBiases, layerIndex) => Float32Array.from(jsonLayers[layerIndex].biases));
  5108. for (let i = 0; i <= this.outputLayer; i++) {
  5109. this.weights[i] = layerWeights[i] || [];
  5110. this.biases[i] = layerBiases[i] || [];
  5111. }
  5112. return this;
  5113. }
  5114. toFunction(cb) {
  5115. const { activation, leakyReluAlpha } = this.trainOpts;
  5116. let needsVar = false;
  5117. const nodeHandle = (layerIndex, nodeIndex) => {
  5118. if (layerIndex === 0) {
  5119. return `(input[${nodeIndex}]||0)`;
  5120. }
  5121. const weights = this.weights[layerIndex][nodeIndex];
  5122. const bias = this.biases[layerIndex][nodeIndex];
  5123. if (!weights) {
  5124. throw new Error(`weights at layerIndex ${layerIndex} & nodeIndex ${nodeIndex} not found`);
  5125. }
  5126. if (!bias) {
  5127. throw new Error(`bias as layerIndex ${layerIndex} & nodeIndex ${nodeIndex} not found`);
  5128. }
  5129. const weightsArray = [];
  5130. weights.forEach((weight, subNodeIndex) => {
  5131. if (weight < 0) {
  5132. weightsArray.push(`${weight}*${nodeHandle(layerIndex - 1, subNodeIndex)}`);
  5133. }
  5134. else {
  5135. weightsArray.push(`+${weight}*${nodeHandle(layerIndex - 1, subNodeIndex)}`);
  5136. }
  5137. });
  5138. const result = `(${bias.toString()}${weightsArray.join('')})`;
  5139. switch (activation) {
  5140. case 'sigmoid':
  5141. return `1/(1+1/Math.exp(${result}))`;
  5142. case 'relu': {
  5143. needsVar = true;
  5144. return `((v=${result})<0?0:v)`;
  5145. }
  5146. case 'leaky-relu': {
  5147. needsVar = true;
  5148. return `Math.max((v=${result}),${leakyReluAlpha}*v)`;
  5149. }
  5150. case 'tanh':
  5151. return `Math.tanh(${result})`;
  5152. default:
  5153. throw new Error(`Unknown activation ${activation}. Available activations are: 'sigmoid', 'relu', 'leaky-relu', 'tanh'`);
  5154. }
  5155. };
  5156. function checkKeys(keys) {
  5157. if (keys.find((v) => v.includes('"'))) {
  5158. throw new Error(`key contains '"', which is not compatible`);
  5159. }
  5160. }
  5161. const layersAsMath = [];
  5162. let result;
  5163. let inputLookup = '';
  5164. if (this.inputLookup) {
  5165. const keys = Object.keys(this.inputLookup);
  5166. checkKeys(keys);
  5167. inputLookup = `input = new Float32Array([${Object.keys(this.inputLookup)
  5168. .map((key) => `input["${key}"]`)
  5169. .join(',')}]);`;
  5170. }
  5171. if (this.sizes.length < 1)
  5172. throw new Error('No layers');
  5173. for (let nodeIndex = 0; nodeIndex < this.sizes[this.outputLayer]; nodeIndex++) {
  5174. layersAsMath.push(nodeHandle(this.outputLayer, nodeIndex));
  5175. }
  5176. if (this.outputLookup) {
  5177. const keys = Object.keys(this.outputLookup);
  5178. checkKeys(keys);
  5179. const values = keys
  5180. .map((key, i) => `"${key}":${layersAsMath[i]}`)
  5181. .join(',');
  5182. result = `{${values}}`;
  5183. }
  5184. else {
  5185. result = `[${layersAsMath.join(',')}]`;
  5186. }
  5187. const source = `${inputLookup}${needsVar ? 'var v;' : ''}return ${result};`;
  5188. // eslint-disable-next-line @typescript-eslint/no-implied-eval,no-new-func
  5189. return new Function('input', cb ? cb(source) : source);
  5190. }
  5191. }
  5192. function weightedSumSigmoid(weights, biases, inputs) {
  5193. let sum = biases[this.thread.x];
  5194. for (let k = 0; k < this.constants.size; k++) {
  5195. sum += weights[this.thread.x][k] * inputs[k];
  5196. }
  5197. // sigmoid
  5198. return 1 / (1 + Math.exp(-sum));
  5199. }
  5200. function weightedSumRelu(weights, biases, inputs) {
  5201. let sum = biases[this.thread.x];
  5202. for (let k = 0; k < this.constants.size; k++) {
  5203. sum += weights[this.thread.x][k] * inputs[k];
  5204. }
  5205. // relu
  5206. return sum < 0 ? 0 : sum;
  5207. }
  5208. function weightedSumLeakyRelu(weights, biases, inputs) {
  5209. let sum = biases[this.thread.x];
  5210. for (let k = 0; k < this.constants.size; k++) {
  5211. sum += weights[this.thread.x][k] * inputs[k];
  5212. }
  5213. // leaky relu
  5214. return sum < 0 ? 0 : 0.01 * sum;
  5215. }
  5216. function weightedSumTanh(weights, biases, inputs) {
  5217. let sum = biases[this.thread.x];
  5218. for (let k = 0; k < this.constants.size; k++) {
  5219. sum += weights[this.thread.x][k] * inputs[k];
  5220. }
  5221. // tanh
  5222. return Math.tanh(sum);
  5223. }
  5224. function calcErrorOutput(output, target) {
  5225. return target - output;
  5226. }
  5227. function calcDeltasSigmoid(error, output) {
  5228. // sigmoid derivative
  5229. return error * output * (1 - output);
  5230. }
  5231. function calcDeltasRelu(error, output) {
  5232. // relu derivative
  5233. return output > 0 ? error : 0;
  5234. }
  5235. function calcDeltasLeakyRelu(error, output) {
  5236. // leaky relu derivative
  5237. return output > 0 ? error : 0.01 * error;
  5238. }
  5239. function calcDeltasTanh(error, output) {
  5240. // tanh derivative
  5241. return (1 - output * output) * error;
  5242. }
  5243. function calcError(x, size, nextWeights, nextDeltas) {
  5244. let error = 0;
  5245. for (let k = 0; k < size; k++) {
  5246. error += nextDeltas[k] * nextWeights[k][x];
  5247. }
  5248. return error;
  5249. }
  5250. function calcChanges(learningRate, momentum, previousChange, delta, previousOutput) {
  5251. return learningRate * delta * previousOutput + momentum * previousChange;
  5252. }
  5253. function addWeights(change, weight) {
  5254. return change + weight;
  5255. }
  5256. function addBiases(biases, deltas) {
  5257. return (biases[this.thread.x] + deltas[this.thread.x] * this.constants.learningRate);
  5258. }
  5259. // mean squared error, reimplemented for GPU
  5260. function mse(errors) {
  5261. let sum = 0;
  5262. for (let i = 0; i < this.constants.size; i++) {
  5263. sum += errors[i] ** 2;
  5264. }
  5265. return sum / this.constants.size;
  5266. }
  5267. class NeuralNetworkGPU extends NeuralNetwork {
  5268. constructor(options = {}) {
  5269. super(options);
  5270. this.texturizeInputData = () => {
  5271. throw new Error('not yet setup');
  5272. };
  5273. this.forwardPropagate = [];
  5274. this.backwardPropagate = [];
  5275. this.changesPropagate = [];
  5276. this.biasesPropagate = [];
  5277. this.getMSE = () => {
  5278. throw new Error('not yet setup');
  5279. };
  5280. this._addMSE = () => {
  5281. throw new Error('not yet setup');
  5282. };
  5283. this._divideMSESum = () => {
  5284. throw new Error('not yet setup');
  5285. };
  5286. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5287. // @ts-expect-error
  5288. this.outputs = [];
  5289. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5290. // @ts-expect-error
  5291. this.deltas = [];
  5292. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5293. // @ts-expect-error
  5294. this.errors = [];
  5295. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5296. // @ts-expect-error
  5297. this.weights = [];
  5298. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5299. // @ts-expect-error
  5300. this.changes = [];
  5301. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5302. // @ts-expect-error
  5303. this.biases = [];
  5304. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5305. // @ts-expect-error
  5306. this.runInput = (input) => {
  5307. let output;
  5308. this.outputs[0] = input;
  5309. for (let layer = 1; layer <= this.outputLayer; layer++) {
  5310. release(this.outputs[layer]);
  5311. this.outputs[layer] = this.forwardPropagate[layer](this.weights[layer], this.biases[layer], input);
  5312. output = input = this.outputs[layer];
  5313. }
  5314. return output;
  5315. };
  5316. this.calculateDeltas = (target) => {
  5317. for (let layer = this.outputLayer; layer > 0; layer--) {
  5318. release(this.deltas[layer]);
  5319. release(this.errors[layer]);
  5320. let output;
  5321. if (layer === this.outputLayer) {
  5322. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5323. // @ts-expect-error
  5324. output = this.backwardPropagate[layer](this.outputs[layer], target);
  5325. }
  5326. else {
  5327. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5328. // @ts-expect-error
  5329. output = this.backwardPropagate[layer](this.weights[layer + 1], this.outputs[layer], this.deltas[layer + 1]);
  5330. }
  5331. this.deltas[layer] = output.result;
  5332. this.errors[layer] = output.error;
  5333. }
  5334. };
  5335. this.errorCheckInterval = 100;
  5336. this.gpu = new gpu_js.GPU({ mode: options.mode });
  5337. }
  5338. initialize() {
  5339. super.initialize();
  5340. this.buildRunInput();
  5341. this.buildCalculateDeltas();
  5342. this.buildGetChanges();
  5343. this.buildChangeBiases();
  5344. this.buildGetMSE();
  5345. }
  5346. setActivation() { }
  5347. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5348. // @ts-expect-error
  5349. trainPattern(value, logErrorRate) {
  5350. // forward propagate
  5351. this.runInput(value.input);
  5352. // back propagate
  5353. this.calculateDeltas(value.output);
  5354. this.adjustWeights();
  5355. if (logErrorRate) {
  5356. return this.getMSE(this.errors[this.outputLayer]);
  5357. }
  5358. return null;
  5359. }
  5360. calculateTrainingError(data) {
  5361. let sum = new Float32Array([0]);
  5362. for (let i = 0; i < data.length; ++i) {
  5363. const prevSum = sum;
  5364. const error = this.trainPattern(data[i], true);
  5365. sum = this._addMSE(sum, error);
  5366. release(error);
  5367. release(prevSum);
  5368. }
  5369. const result = this._divideMSESum(data.length, sum);
  5370. release(sum);
  5371. return (result instanceof gpu_js.Texture
  5372. ? result.toArray()
  5373. : result)[0];
  5374. }
  5375. adjustWeights() {
  5376. this.getChanges();
  5377. this.changeBiases();
  5378. }
  5379. buildRunInput() {
  5380. let weightedSum = null;
  5381. switch (this.trainOpts.activation) {
  5382. case 'sigmoid':
  5383. weightedSum = weightedSumSigmoid;
  5384. break;
  5385. case 'relu':
  5386. weightedSum = weightedSumRelu;
  5387. break;
  5388. case 'leaky-relu':
  5389. weightedSum = weightedSumLeakyRelu;
  5390. break;
  5391. case 'tanh':
  5392. weightedSum = weightedSumTanh;
  5393. break;
  5394. default:
  5395. throw new Error(`Unknown activation ${this.trainOpts.activation}. Available activations are: 'sigmoid', 'relu', 'leaky-relu', 'tanh'`);
  5396. }
  5397. for (let layer = 1; layer <= this.outputLayer; layer++) {
  5398. this.forwardPropagate[layer] = this.gpu.createKernel(weightedSum, {
  5399. output: [this.sizes[layer]],
  5400. pipeline: true,
  5401. constants: {
  5402. size: this.sizes[layer - 1],
  5403. },
  5404. immutable: true,
  5405. });
  5406. }
  5407. this.texturizeInputData = this.gpu.createKernel(function (value) {
  5408. return value[this.thread.x];
  5409. }, {
  5410. output: [this.sizes[1]],
  5411. pipeline: true,
  5412. immutable: true,
  5413. });
  5414. }
  5415. buildCalculateDeltas() {
  5416. let calcDeltas;
  5417. switch (this.trainOpts.activation) {
  5418. case 'sigmoid':
  5419. calcDeltas = calcDeltasSigmoid;
  5420. break;
  5421. case 'relu':
  5422. calcDeltas = calcDeltasRelu;
  5423. break;
  5424. case 'leaky-relu':
  5425. calcDeltas = calcDeltasLeakyRelu;
  5426. break;
  5427. case 'tanh':
  5428. calcDeltas = calcDeltasTanh;
  5429. break;
  5430. default:
  5431. throw new Error(`Unknown activation ${this.trainOpts.activation}. Available activations are: 'sigmoid', 'relu', 'leaky-relu', 'tanh'`);
  5432. }
  5433. calcDeltas = gpu_js.alias(gpu_js.utils.getMinifySafeName(() => calcDeltas), calcDeltas);
  5434. this.gpu.addFunction(calcDeltas);
  5435. for (let layer = this.outputLayer; layer > 0; layer--) {
  5436. if (layer === this.outputLayer) {
  5437. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5438. // @ts-expect-error
  5439. this.backwardPropagate[this.outputLayer] = this.gpu.createKernelMap({
  5440. error: calcErrorOutput,
  5441. }, function (outputs, targets) {
  5442. const output = outputs[this.thread.x];
  5443. const target = targets[this.thread.x];
  5444. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5445. // @ts-expect-error
  5446. return calcDeltas(calcErrorOutput(output, target), output);
  5447. }, {
  5448. output: [this.sizes[this.outputLayer]],
  5449. pipeline: true,
  5450. immutable: true,
  5451. });
  5452. }
  5453. else {
  5454. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5455. // @ts-expect-error
  5456. this.backwardPropagate[layer] = this.gpu.createKernelMap({
  5457. error: calcError,
  5458. }, function (nextWeights, outputs, nextDeltas) {
  5459. const output = outputs[this.thread.x];
  5460. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5461. // @ts-expect-error
  5462. return calcDeltas(calcError(this.thread.x, this.constants.size, nextWeights, nextDeltas), output);
  5463. }, {
  5464. output: [this.sizes[layer]],
  5465. pipeline: true,
  5466. constants: {
  5467. size: this.sizes[layer + 1],
  5468. },
  5469. immutable: true,
  5470. });
  5471. }
  5472. }
  5473. }
  5474. buildGetChanges() {
  5475. for (let layer = 1; layer <= this.outputLayer; layer++) {
  5476. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5477. // @ts-expect-error
  5478. this.changesPropagate[layer] = this.gpu.createKernelMap({
  5479. weights: addWeights,
  5480. changes: calcChanges,
  5481. }, function (previousOutputs, deltas, weights, previousChanges) {
  5482. const change = calcChanges(this.constants.learningRate, this.constants.momentum, previousChanges[this.thread.y][this.thread.x], deltas[this.thread.y], previousOutputs[this.thread.x]);
  5483. return addWeights(change, weights[this.thread.y][this.thread.x]);
  5484. }, {
  5485. output: [this.sizes[layer - 1], this.sizes[layer]],
  5486. pipeline: true,
  5487. constants: {
  5488. size: this.sizes[layer - 1],
  5489. learningRate: this.trainOpts.learningRate,
  5490. momentum: this.trainOpts.momentum,
  5491. },
  5492. immutable: true,
  5493. });
  5494. }
  5495. }
  5496. getChanges() {
  5497. for (let layer = 1; layer <= this.outputLayer; layer++) {
  5498. const weights = this.weights[layer];
  5499. const changes = this.changes[layer];
  5500. const output = this.changesPropagate[layer](this.outputs[layer - 1], this.deltas[layer], weights, changes);
  5501. release(weights);
  5502. release(changes);
  5503. this.weights[layer] = output.weights;
  5504. this.changes[layer] = output.changes;
  5505. release(output.result);
  5506. }
  5507. }
  5508. buildChangeBiases() {
  5509. for (let layer = 1; layer <= this.outputLayer; layer++) {
  5510. this.biasesPropagate[layer] = this.gpu.createKernel(addBiases, {
  5511. output: [this.sizes[layer]],
  5512. pipeline: true,
  5513. constants: {
  5514. learningRate: this.trainOpts.learningRate,
  5515. },
  5516. immutable: true,
  5517. });
  5518. }
  5519. }
  5520. changeBiases() {
  5521. for (let layer = 1; layer <= this.outputLayer; layer++) {
  5522. const biases = this.biases[layer];
  5523. this.biases[layer] = this.biasesPropagate[layer](biases, this.deltas[layer]);
  5524. release(biases);
  5525. }
  5526. }
  5527. buildGetMSE() {
  5528. this.getMSE = this.gpu.createKernel(mse, {
  5529. output: [1],
  5530. constants: {
  5531. size: this.sizes[this.outputLayer],
  5532. },
  5533. pipeline: true,
  5534. immutable: true,
  5535. });
  5536. this._addMSE = this.gpu.createKernel(function (value1, value2) {
  5537. return value1[0] + value2[0];
  5538. }, {
  5539. output: [1],
  5540. pipeline: true,
  5541. immutable: true,
  5542. });
  5543. this._divideMSESum = this.gpu.createKernel(function (length, mseSum) {
  5544. const value = mseSum[0];
  5545. if (value > 0) {
  5546. return value / length;
  5547. }
  5548. return 0;
  5549. }, {
  5550. output: [1],
  5551. });
  5552. }
  5553. run(input) {
  5554. if (!this.isRunnable) {
  5555. throw new Error('network not runnable');
  5556. }
  5557. let formattedInput;
  5558. if (this.inputLookup) {
  5559. formattedInput = lookup.toArray(this.inputLookup, input, this.inputLookupLength);
  5560. }
  5561. else {
  5562. formattedInput = input;
  5563. }
  5564. const outputTextures = this.runInput(formattedInput);
  5565. const output = outputTextures instanceof gpu_js.Texture
  5566. ? outputTextures.toArray()
  5567. : outputTextures;
  5568. if (this.outputLookup) {
  5569. return lookup.toObject(this.outputLookup, output);
  5570. }
  5571. return output;
  5572. }
  5573. // @ts-expect-error the underlying network works as normal, but we are working on the GPU
  5574. prepTraining(data, options = {}) {
  5575. this.updateTrainingOptions(options);
  5576. const preparedData = this.formatData(data);
  5577. const endTime = Date.now() + this.trainOpts.timeout;
  5578. const status = {
  5579. error: 1,
  5580. iterations: 0,
  5581. };
  5582. this.verifyIsInitialized(preparedData);
  5583. const texturizeOutputData = this.gpu.createKernel(function (value) {
  5584. return value[this.thread.x];
  5585. }, {
  5586. output: [preparedData[0].output.length],
  5587. pipeline: true,
  5588. immutable: true,
  5589. });
  5590. return {
  5591. preparedData: preparedData.map((set) => ({
  5592. input: this.texturizeInputData(set.input),
  5593. output: texturizeOutputData(set.output),
  5594. })),
  5595. status,
  5596. endTime,
  5597. };
  5598. }
  5599. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5600. // @ts-expect-error
  5601. toFunction() {
  5602. throw new Error(`${this.constructor.name}-toFunction is not yet implemented`);
  5603. }
  5604. toJSON() {
  5605. var _a, _b;
  5606. if (this.sizes === null) {
  5607. this.initialize();
  5608. }
  5609. // use Array.from, keeping json small
  5610. const jsonLayerWeights = this.weights.map((layerWeights) => {
  5611. return (layerWeights instanceof gpu_js.Texture
  5612. ? layerWeights.toArray()
  5613. : layerWeights).map((layerWeights) => Array.from(layerWeights));
  5614. });
  5615. const jsonLayerBiases = this.biases.map((layerBiases) => Array.from(layerBiases instanceof gpu_js.Texture
  5616. ? layerBiases.toArray()
  5617. : layerBiases));
  5618. const jsonLayers = [];
  5619. for (let i = 0; i <= this.outputLayer; i++) {
  5620. jsonLayers.push({
  5621. weights: (_a = jsonLayerWeights[i]) !== null && _a !== void 0 ? _a : [],
  5622. biases: (_b = jsonLayerBiases[i]) !== null && _b !== void 0 ? _b : [],
  5623. });
  5624. }
  5625. return {
  5626. type: 'NeuralNetworkGPU',
  5627. sizes: [...this.sizes],
  5628. layers: jsonLayers,
  5629. inputLookup: this.inputLookup ? { ...this.inputLookup } : null,
  5630. inputLookupLength: this.inputLookupLength,
  5631. outputLookup: this.outputLookup ? { ...this.outputLookup } : null,
  5632. outputLookupLength: this.outputLookupLength,
  5633. options: { ...this.options },
  5634. trainOpts: this.getTrainOptsJSON(),
  5635. };
  5636. }
  5637. }
  5638. class RecurrentConnection extends Internal {
  5639. constructor() {
  5640. super(...arguments);
  5641. this.settings = {};
  5642. this.layer = null;
  5643. }
  5644. setLayer(layer) {
  5645. this.layer = layer;
  5646. }
  5647. get width() {
  5648. if (!this.layer)
  5649. throw new Error('layer not set');
  5650. return this.layer.width;
  5651. }
  5652. set width(value) {
  5653. throw new Error(`${this.constructor.name}-width is not yet implemented`);
  5654. }
  5655. get height() {
  5656. if (!this.layer)
  5657. throw new Error('layer not set');
  5658. return this.layer.height;
  5659. }
  5660. set height(value) {
  5661. throw new Error(`${this.constructor.name}-height is not yet implemented`);
  5662. }
  5663. get deltas() {
  5664. if (!this.layer)
  5665. throw new Error('layer not set');
  5666. return this.layer.deltas;
  5667. }
  5668. set deltas(deltas) {
  5669. if (!this.layer)
  5670. throw new Error('layer not set');
  5671. release(this.layer.deltas);
  5672. this.layer.deltas = deltas;
  5673. }
  5674. get weights() {
  5675. if (!this.layer)
  5676. throw new Error('layer not set');
  5677. return this.layer.weights;
  5678. }
  5679. set weights(weights) {
  5680. if (!this.layer)
  5681. throw new Error('layer not set');
  5682. release(this.layer.weights);
  5683. this.layer.weights = weights;
  5684. }
  5685. predict() {
  5686. // throw new Error(`${this.constructor.name}-predict is not yet implemented`)
  5687. }
  5688. compare() {
  5689. // throw new Error(`${this.constructor.name}-compare is not yet implemented`)
  5690. }
  5691. learn() {
  5692. throw new Error('no longer using');
  5693. }
  5694. setupKernels() {
  5695. // throw new Error(
  5696. // `${this.constructor.name}-setupKernels is not yet implemented`
  5697. // )
  5698. }
  5699. reuseKernels() {
  5700. // throw new Error(
  5701. // `${this.constructor.name}-reuseKernels is not yet implemented`
  5702. // )
  5703. }
  5704. }
  5705. class Recurrent extends FeedForward {
  5706. // TODO: use generics in extend
  5707. constructor(options = {}) {
  5708. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5709. // @ts-expect-error
  5710. super(options);
  5711. this.trainOpts = {};
  5712. this._outputConnection = null;
  5713. this._layerSets = [];
  5714. this._hiddenLayerOutputIndices = [];
  5715. this._model = null;
  5716. }
  5717. _connectLayers() {
  5718. if (!this.options.inputLayer) {
  5719. throw new Error('inputLayer not found');
  5720. }
  5721. if (!this.options.outputLayer) {
  5722. throw new Error('outputLayer not found');
  5723. }
  5724. const inputLayer = this.options.inputLayer();
  5725. const hiddenLayers = this._connectHiddenLayers(inputLayer);
  5726. const outputLayer = this.options.outputLayer(hiddenLayers[hiddenLayers.length - 1], -1);
  5727. return {
  5728. inputLayer,
  5729. hiddenLayers,
  5730. outputLayer,
  5731. };
  5732. }
  5733. _connectLayersDeep() {
  5734. const layers = [];
  5735. const previousLayers = this._layerSets[this._layerSets.length - 1];
  5736. let usedHiddenLayerOutputIndex = 0;
  5737. function findInputLayer(inputLayer) {
  5738. const index = previousLayers.indexOf(inputLayer);
  5739. if (index < 0)
  5740. throw new Error('unable to find layer');
  5741. return layers[index];
  5742. }
  5743. function layerSettings(layer) {
  5744. return {
  5745. ...layer.settings,
  5746. weights: null,
  5747. deltas: null,
  5748. praxis: null,
  5749. };
  5750. }
  5751. for (let i = 0; i < previousLayers.length; i++) {
  5752. const previousLayer = previousLayers[i];
  5753. let layer;
  5754. if (previousLayer instanceof Activation) {
  5755. layer = new previousLayer.constructor(findInputLayer(previousLayer.inputLayer), layerSettings(previousLayer));
  5756. }
  5757. else if (previousLayer instanceof EntryPoint) {
  5758. layer = new previousLayer.constructor(layerSettings(previousLayer));
  5759. }
  5760. else if (previousLayer instanceof Filter) {
  5761. layer = new previousLayer.constructor(layerSettings(previousLayer.inputLayer), findInputLayer(previousLayer.inputLayer));
  5762. }
  5763. else if (previousLayer instanceof Internal) {
  5764. const previousHiddenLayerOutput = previousLayers[this._hiddenLayerOutputIndices[usedHiddenLayerOutputIndex++]];
  5765. if (previousLayer instanceof RecurrentConnection) {
  5766. throw new Error('unfinished');
  5767. }
  5768. else if (previousLayer instanceof RecurrentInput) {
  5769. layer = new RecurrentInput(previousHiddenLayerOutput);
  5770. }
  5771. else if (previousLayer instanceof RecurrentZeros) {
  5772. layer = new RecurrentInput(previousHiddenLayerOutput);
  5773. }
  5774. else {
  5775. throw new Error(`hidden layer ${previousLayer.constructor.name} extends unknown hidden layer`);
  5776. }
  5777. }
  5778. else if (previousLayer instanceof InternalModel ||
  5779. previousLayer instanceof Model) {
  5780. layer = previousLayer;
  5781. }
  5782. else if (previousLayer instanceof Modifier) {
  5783. layer = new previousLayer.constructor(findInputLayer(previousLayer.inputLayer), layerSettings(previousLayer.inputLayer));
  5784. }
  5785. else if (previousLayer instanceof Operator) {
  5786. layer = new previousLayer.constructor(findInputLayer(previousLayer.inputLayer1), findInputLayer(previousLayer.inputLayer2), layerSettings(previousLayer));
  5787. }
  5788. else if (previousLayer instanceof Target) {
  5789. layer = new previousLayer.constructor(layerSettings(previousLayer), findInputLayer(previousLayer.inputLayer));
  5790. }
  5791. else {
  5792. throw new Error(`hidden layer ${previousLayer.constructor.name} extends unknown hidden layer`);
  5793. }
  5794. layers.push(layer);
  5795. }
  5796. return layers;
  5797. }
  5798. _connectHiddenLayers(previousLayer) {
  5799. const hiddenLayers = [];
  5800. if (!this.options.hiddenLayers)
  5801. throw new Error('hiddenLayers not defined');
  5802. for (let i = 0; i < this.options.hiddenLayers.length; i++) {
  5803. const recurrentInput = new RecurrentZeros();
  5804. const hiddenLayer = this.options.hiddenLayers[i](previousLayer, recurrentInput, i);
  5805. previousLayer = hiddenLayer;
  5806. hiddenLayers.push(hiddenLayer);
  5807. }
  5808. return hiddenLayers;
  5809. }
  5810. initialize() {
  5811. this._outputConnection = new RecurrentConnection();
  5812. let layerSet;
  5813. if (this.options.layers) {
  5814. layerSet = this._connectOptionsLayers();
  5815. }
  5816. else {
  5817. const { inputLayer, hiddenLayers, outputLayer } = this._connectLayers();
  5818. layerSet = flattenLayers([inputLayer, ...hiddenLayers, outputLayer]);
  5819. this._hiddenLayerOutputIndices = hiddenLayers.map((l) => layerSet.indexOf(l));
  5820. this._inputLayer = inputLayer;
  5821. this._hiddenLayers = hiddenLayers;
  5822. this._outputLayer = outputLayer;
  5823. }
  5824. this.layers = layerSet;
  5825. this._layerSets = [layerSet];
  5826. this._model = layerSet.filter((l) => l instanceof Model || l instanceof InternalModel);
  5827. this.initializeLayers(layerSet);
  5828. }
  5829. initializeDeep() {
  5830. const layers = this._connectLayersDeep();
  5831. for (let i = 0; i < layers.length; i++) {
  5832. const layer = layers[i];
  5833. layer.setupKernels(true);
  5834. layer.reuseKernels(this._layerSets[0][i]);
  5835. }
  5836. this._layerSets.push(layers);
  5837. }
  5838. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5839. // @ts-expect-error
  5840. run(inputs) {
  5841. while (this._layerSets.length <= inputs.length) {
  5842. this.initializeDeep();
  5843. }
  5844. const result = this.runInputs(inputs);
  5845. if (result instanceof gpu_js.Texture) {
  5846. return result.toArray();
  5847. }
  5848. return result;
  5849. }
  5850. runInput(input) {
  5851. throw new Error('use .runInputs()');
  5852. }
  5853. runInputs(inputs) {
  5854. while (this._layerSets.length < inputs.length) {
  5855. this.initializeDeep();
  5856. }
  5857. const max = inputs.length - 1; // last output will be compared with last index
  5858. for (let x = 0; x <= max; x++) {
  5859. const layerSet = this._layerSets[x];
  5860. layerSet[0].predict(inputs[x]);
  5861. for (let i = 1; i < layerSet.length; i++) {
  5862. layerSet[i].predict();
  5863. }
  5864. }
  5865. const lastLayerUsed = this._layerSets[max];
  5866. const result = lastLayerUsed[lastLayerUsed.length - 1].weights;
  5867. this.end();
  5868. return result;
  5869. }
  5870. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5871. // @ts-expect-error
  5872. train(data, options = {}) {
  5873. const { preparedData, status, endTime } = this._prepTraining(data, options);
  5874. let continueTicking = true;
  5875. const calculateError = () => this._calculateTrainingError(preparedData);
  5876. const trainPatters = () => this._trainPatterns(preparedData);
  5877. while (continueTicking) {
  5878. continueTicking = this._trainingTick(status, endTime, calculateError, trainPatters);
  5879. }
  5880. return status;
  5881. }
  5882. end() {
  5883. const x = this._layerSets.length - 1;
  5884. const lastLayerSet = this._layerSets[x];
  5885. lastLayerSet[0].predict([new Float32Array([0])]);
  5886. for (let i = 1; i < lastLayerSet.length; i++) {
  5887. lastLayerSet[i].predict();
  5888. }
  5889. }
  5890. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5891. // @ts-expect-error
  5892. transferData(formattedData) {
  5893. return formattedData;
  5894. }
  5895. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5896. // @ts-expect-error
  5897. _prepTraining(data, options) {
  5898. this._updateTrainingOptions(options);
  5899. const endTime = this.trainOpts.timeout
  5900. ? Date.now() + this.trainOpts.timeout
  5901. : 0;
  5902. const status = {
  5903. error: 1,
  5904. iterations: 0,
  5905. };
  5906. this.verifyIsInitialized();
  5907. return {
  5908. preparedData: this.transferData(data),
  5909. status,
  5910. endTime,
  5911. };
  5912. }
  5913. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5914. // @ts-expect-error
  5915. _calculateTrainingError(data) {
  5916. if (!this.meanSquaredError) {
  5917. throw new Error('this.meanSquaredError not setup');
  5918. }
  5919. let sum = new Float32Array(1);
  5920. for (let i = 0; i < data.length; ++i) {
  5921. const prevSum = sum;
  5922. const error = this._trainPattern(data[i], true);
  5923. sum = this.meanSquaredError.add(sum, error);
  5924. release(error);
  5925. release(prevSum);
  5926. }
  5927. const result = this.meanSquaredError.divide(data.length, sum);
  5928. release(sum);
  5929. if (result instanceof gpu_js.Texture) {
  5930. const resultArray = result.toArray();
  5931. return resultArray[0];
  5932. }
  5933. return result[0];
  5934. }
  5935. // TODO: more types
  5936. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5937. // @ts-expect-error
  5938. formatData(data) {
  5939. return data;
  5940. }
  5941. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5942. // @ts-expect-error
  5943. _calculateDeltas(target) {
  5944. const lastLayerSet = this._layerSets[this._layerSets.length - 1];
  5945. // Iterate from the second to last layer backwards, propagating 0's
  5946. for (let i = lastLayerSet.length - 2; i >= 0; i--) {
  5947. lastLayerSet[i].compare();
  5948. }
  5949. for (let x = target.length - 2; x >= 0; x--) {
  5950. const layerSet = this._layerSets[x];
  5951. layerSet[layerSet.length - 1].compare(target[x + 1]);
  5952. for (let i = layerSet.length - 2; i >= 0; i--) {
  5953. layerSet[i].compare();
  5954. }
  5955. }
  5956. }
  5957. adjustWeights() {
  5958. var _a;
  5959. const _model = this._model;
  5960. for (let i = 0; i < _model.length; i++) {
  5961. _model[i].learn((_a = this.options.learningRate) !== null && _a !== void 0 ? _a : 0);
  5962. }
  5963. }
  5964. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5965. // @ts-expect-error
  5966. _trainPatterns(data) {
  5967. for (let i = 0; i < data.length; ++i) {
  5968. this._trainPattern(data[i], false);
  5969. }
  5970. }
  5971. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  5972. // @ts-expect-error
  5973. _trainPattern(inputs, logErrorRate) {
  5974. // forward propagate
  5975. this.runInputs(inputs);
  5976. // back propagate
  5977. this._calculateDeltas(inputs);
  5978. this.adjustWeights();
  5979. if (logErrorRate) {
  5980. if (!this.meanSquaredError) {
  5981. throw new Error('this.meanSquaredError not setup');
  5982. }
  5983. let error = new Float32Array(1);
  5984. for (let i = 0, max = inputs.length - 2; i <= max; i++) {
  5985. const layerSet = this._layerSets[i];
  5986. const lastLayer = layerSet[layerSet.length - 1];
  5987. const prevError = error;
  5988. error = this.meanSquaredError.addAbsolute(prevError, lastLayer.errors);
  5989. release(prevError);
  5990. }
  5991. return clone(this.meanSquaredError.divide(inputs.length, error));
  5992. }
  5993. return null;
  5994. }
  5995. }
  5996. /**
  5997. * A matrix
  5998. */
  5999. class Matrix {
  6000. constructor(rows, columns) {
  6001. this.rows = 0;
  6002. this.columns = 0;
  6003. if (rows)
  6004. this.rows = rows;
  6005. if (columns)
  6006. this.columns = columns;
  6007. this.weights = zeros$1(this.rows * this.columns);
  6008. this.deltas = zeros$1(this.rows * this.columns);
  6009. }
  6010. getWeight(row, col) {
  6011. // slow but careful accessor function
  6012. // we want row-major order
  6013. const ix = this.columns * row + col;
  6014. if (ix < 0 || ix >= this.weights.length) {
  6015. throw new Error('get accessor is skewed');
  6016. }
  6017. return this.weights[ix];
  6018. }
  6019. setWeight(row, col, v) {
  6020. // slow but careful accessor function
  6021. const ix = this.columns * row + col;
  6022. if (ix < 0 || ix >= this.weights.length) {
  6023. throw new Error('set accessor is skewed');
  6024. }
  6025. this.weights[ix] = v;
  6026. return this;
  6027. }
  6028. getDelta(row, col) {
  6029. // slow but careful accessor function
  6030. // we want row-major order
  6031. const ix = this.columns * row + col;
  6032. if (ix < 0 || ix >= this.deltas.length) {
  6033. throw new Error('get accessor is skewed');
  6034. }
  6035. return this.deltas[ix];
  6036. }
  6037. setDelta(row, col, v) {
  6038. // slow but careful accessor function
  6039. const ix = this.columns * row + col;
  6040. if (ix < 0 || ix >= this.weights.length) {
  6041. throw new Error('set accessor is skewed');
  6042. }
  6043. this.deltas[ix] = v;
  6044. return this;
  6045. }
  6046. toJSON() {
  6047. return {
  6048. rows: this.rows,
  6049. columns: this.columns,
  6050. weights: Array.from(this.weights.slice(0)),
  6051. };
  6052. }
  6053. static fromJSON(json) {
  6054. const matrix = new Matrix(json.rows, json.columns);
  6055. for (let i = 0, max = json.rows * json.columns; i < max; i++) {
  6056. matrix.weights[i] = json.weights[i]; // copy over weights
  6057. }
  6058. return matrix;
  6059. }
  6060. static fromArray(weights) {
  6061. const matrix = new Matrix(weights.length, weights[0].length);
  6062. matrix.fromArray(weights);
  6063. return matrix;
  6064. }
  6065. deltasToArray() {
  6066. return this.toArray('deltas');
  6067. }
  6068. weightsToArray() {
  6069. return this.toArray('weights');
  6070. }
  6071. toArray(prop = 'weights') {
  6072. const result = new Array(this.rows);
  6073. this.iterate({
  6074. row: (rowIndex) => {
  6075. result[rowIndex] = new Array(this.columns);
  6076. },
  6077. column: (rowIndex, columnIndex) => {
  6078. if (prop === 'weights') {
  6079. result[rowIndex][columnIndex] = this.getWeight(rowIndex, columnIndex);
  6080. }
  6081. else if (prop === 'deltas') {
  6082. result[rowIndex][columnIndex] = this.getDelta(rowIndex, columnIndex);
  6083. }
  6084. },
  6085. });
  6086. return result;
  6087. }
  6088. fromArray(array, prop = 'weights') {
  6089. if (array.length !== this.rows) {
  6090. throw new Error('rows do not match');
  6091. }
  6092. if (array[0].length !== this.columns) {
  6093. throw new Error('columns do not match');
  6094. }
  6095. this.iterate({
  6096. column: (rowIndex, columnIndex) => {
  6097. const value = array[rowIndex][columnIndex];
  6098. if (typeof value !== 'number') {
  6099. throw new Error('value not number');
  6100. }
  6101. if (prop === 'weights') {
  6102. this.setWeight(rowIndex, columnIndex, value);
  6103. }
  6104. else if (prop === 'deltas') {
  6105. this.setDelta(rowIndex, columnIndex, value);
  6106. }
  6107. },
  6108. });
  6109. return this;
  6110. }
  6111. iterate(callbacks) {
  6112. const rows = this.rows;
  6113. const columns = this.columns;
  6114. for (let rowIndex = 0; rowIndex < rows; rowIndex++) {
  6115. if (callbacks.row) {
  6116. callbacks.row(rowIndex);
  6117. }
  6118. for (let columnIndex = 0; columnIndex < columns; columnIndex++) {
  6119. if (callbacks.column) {
  6120. callbacks.column(rowIndex, columnIndex);
  6121. }
  6122. }
  6123. }
  6124. return this;
  6125. }
  6126. }
  6127. /** return Matrix but filled with random numbers from gaussian
  6128. */
  6129. class RandomMatrix extends Matrix {
  6130. constructor(rows, columns, std) {
  6131. super(rows, columns);
  6132. this.std = std;
  6133. for (let i = 0, max = this.weights.length; i < max; i++) {
  6134. this.weights[i] = randomFloat(-std, std);
  6135. }
  6136. }
  6137. }
  6138. class DataFormatter {
  6139. constructor(values, maxThreshold = 0) {
  6140. this.values = values;
  6141. this.indexTable = {};
  6142. this.characterTable = {};
  6143. this.characters = [];
  6144. this.specialIndexes = [];
  6145. this.isSetup = false;
  6146. if (values === undefined)
  6147. return;
  6148. this.setup(values, maxThreshold);
  6149. }
  6150. setup(values, maxThreshold = 0) {
  6151. if (this.isSetup)
  6152. throw new Error('DataFormatter is already setup');
  6153. this.values = values;
  6154. // go over all characters and keep track of all unique ones seen
  6155. // count up all characters
  6156. this.buildCharactersFromIterable(values);
  6157. this.buildTables(maxThreshold);
  6158. if (values[0].input) {
  6159. this.addInputOutput();
  6160. }
  6161. this.addUnrecognized();
  6162. this.isSetup = true;
  6163. }
  6164. buildCharactersFromIterable(values) {
  6165. const tempCharactersTable = {};
  6166. for (let dataFormatterIndex = 0, dataFormatterLength = values.length; dataFormatterIndex < dataFormatterLength; dataFormatterIndex++) {
  6167. const characters = values[dataFormatterIndex];
  6168. // if (typeof characters === 'string') {
  6169. // const character = characters;
  6170. // if (tempCharactersTable.hasOwnProperty(character)) continue;
  6171. // tempCharactersTable[character] = true;
  6172. // this.characters.push(character);
  6173. if (characters.hasOwnProperty('length')) {
  6174. const iteratable = characters;
  6175. for (let characterIndex = 0, charactersLength = iteratable.length; characterIndex < charactersLength; characterIndex++) {
  6176. const character = iteratable[characterIndex];
  6177. if (tempCharactersTable.hasOwnProperty(character))
  6178. continue;
  6179. tempCharactersTable[character] = true;
  6180. this.characters.push(character);
  6181. }
  6182. }
  6183. else if (typeof characters === 'number') {
  6184. if (tempCharactersTable.hasOwnProperty(characters))
  6185. continue;
  6186. tempCharactersTable[characters] = true;
  6187. this.characters.push(characters);
  6188. }
  6189. else if (typeof characters === 'boolean') {
  6190. const character = characters.toString();
  6191. if (tempCharactersTable.hasOwnProperty(character))
  6192. continue;
  6193. tempCharactersTable[character] = true;
  6194. this.characters.push(character);
  6195. }
  6196. else if (Array.isArray(characters) &&
  6197. typeof characters[0] === 'string') {
  6198. for (let i = 0; i < characters.length; i++) {
  6199. const character = characters[i];
  6200. if (tempCharactersTable.hasOwnProperty(character))
  6201. continue;
  6202. tempCharactersTable[character] = true;
  6203. this.characters.push(character);
  6204. }
  6205. }
  6206. else if (Array.isArray(characters) &&
  6207. (typeof characters[0] === 'number' ||
  6208. typeof characters[0] === 'boolean')) {
  6209. for (let i = 0; i < characters.length; i++) {
  6210. const character = characters[i].toString();
  6211. if (tempCharactersTable.hasOwnProperty(dataFormatterIndex))
  6212. continue;
  6213. tempCharactersTable[character] = true;
  6214. this.characters.push(character);
  6215. }
  6216. }
  6217. else if (characters.hasOwnProperty('input') &&
  6218. characters.hasOwnProperty('output')) {
  6219. const { input, output } = characters;
  6220. if (Array.isArray(input)) {
  6221. this.addCharacters(input, tempCharactersTable);
  6222. }
  6223. else {
  6224. this.addCharacters(input.toString(), tempCharactersTable);
  6225. }
  6226. if (Array.isArray(output)) {
  6227. this.addCharacters(output, tempCharactersTable);
  6228. }
  6229. else {
  6230. this.addCharacters(output.toString(), tempCharactersTable);
  6231. }
  6232. }
  6233. else {
  6234. throw new Error('Unhandled value');
  6235. }
  6236. }
  6237. }
  6238. addCharacters(characters, charactersTable) {
  6239. for (let i = 0; i < characters.length; i++) {
  6240. const character = characters[i].toString();
  6241. if (charactersTable.hasOwnProperty(character))
  6242. continue;
  6243. charactersTable[character] = true;
  6244. this.characters.push(character);
  6245. }
  6246. }
  6247. buildTables(maxThreshold) {
  6248. // filter by count threshold and create pointers
  6249. const charactersLength = this.characters.length;
  6250. for (let characterIndex = 0; characterIndex < charactersLength; characterIndex++) {
  6251. const character = this.characters[characterIndex];
  6252. if (characterIndex >= maxThreshold) {
  6253. // add character to dataFormatter
  6254. this.indexTable[character] = characterIndex;
  6255. this.characterTable[characterIndex] = character;
  6256. }
  6257. }
  6258. }
  6259. toIndexes(value, maxThreshold = 0) {
  6260. const result = [];
  6261. const { indexTable } = this;
  6262. switch (typeof value) {
  6263. case 'number':
  6264. case 'boolean':
  6265. value = value.toString();
  6266. }
  6267. for (let i = 0, max = value.length; i < max; i++) {
  6268. const character = value[i].toString();
  6269. let index = indexTable[character];
  6270. if (index === undefined) {
  6271. if (indexTable.unrecognized) {
  6272. index = indexTable.unrecognized;
  6273. }
  6274. else {
  6275. throw new Error(`unrecognized character "${character}"`);
  6276. }
  6277. }
  6278. if (index < maxThreshold)
  6279. continue;
  6280. result.push(index);
  6281. }
  6282. return result;
  6283. }
  6284. toIndexesInputOutput(input, output, maxThreshold = 0) {
  6285. const result = this.toIndexesValue(input, maxThreshold, true);
  6286. if (typeof output === 'undefined')
  6287. return result;
  6288. return result.concat(this.toIndexesValue(output, maxThreshold, false));
  6289. }
  6290. toIndexesValue(value, maxThreshold, isInput) {
  6291. if (typeof value === 'string') {
  6292. value = value.split('');
  6293. }
  6294. else if (typeof value === 'number' || typeof value === 'boolean') {
  6295. value = value.toString().split('');
  6296. }
  6297. else if (Array.isArray(value) &&
  6298. (typeof value[0] === 'number' ||
  6299. typeof value[0] === 'boolean' ||
  6300. typeof value[0] === 'string')) {
  6301. value = value.map((v) => v.toString());
  6302. }
  6303. else {
  6304. throw new Error('unrecognized value');
  6305. }
  6306. if (isInput) {
  6307. value = value.concat(['stop-input', 'start-output']);
  6308. }
  6309. return this.toIndexes(value, maxThreshold);
  6310. }
  6311. toCharacters(indices, maxThreshold = 0) {
  6312. const result = [];
  6313. const { indexTable, characterTable } = this;
  6314. for (let i = 0, max = indices.length; i < max; i++) {
  6315. const index = indices[i];
  6316. if (index < maxThreshold)
  6317. continue;
  6318. let character = characterTable[index];
  6319. if (character === undefined) {
  6320. if (indexTable.unrecognized) {
  6321. character = characterTable[indexTable.unrecognized];
  6322. }
  6323. else {
  6324. throw new Error(`unrecognized index "${index}"`);
  6325. }
  6326. }
  6327. else if (character !== null) {
  6328. result.push(character.toString());
  6329. }
  6330. }
  6331. return result;
  6332. }
  6333. toString(indices, maxThreshold) {
  6334. return this.toCharacters(indices, maxThreshold).join('');
  6335. }
  6336. addInputOutput() {
  6337. this.addSpecial('stop-input');
  6338. this.addSpecial('start-output');
  6339. }
  6340. addUnrecognized() {
  6341. this.addSpecial('unrecognized');
  6342. }
  6343. static fromAllPrintable(maxThreshold, values = ['\n']) {
  6344. for (let i = 32; i <= 126; i++) {
  6345. values.push(String.fromCharCode(i));
  6346. }
  6347. return new DataFormatter(values, maxThreshold);
  6348. }
  6349. static fromAllPrintableInputOutput(maxThreshold, values = ['\n']) {
  6350. const dataFormatter = DataFormatter.fromAllPrintable(maxThreshold, values);
  6351. dataFormatter.addInputOutput();
  6352. dataFormatter.addUnrecognized();
  6353. return dataFormatter;
  6354. }
  6355. static fromStringInputOutput(string, maxThreshold) {
  6356. const values = Array.from(new Set(string)).join('');
  6357. const dataFormatter = new DataFormatter(values.split(''), maxThreshold);
  6358. dataFormatter.addInputOutput();
  6359. dataFormatter.addUnrecognized();
  6360. dataFormatter.isSetup = true;
  6361. return dataFormatter;
  6362. }
  6363. static fromArrayInputOutput(data, maxThreshold) {
  6364. const values = [];
  6365. for (let i = 0; i < data.length; i++) {
  6366. const datum = data[i];
  6367. values.push(validateAndCast(datum.input), validateAndCast(datum.output));
  6368. }
  6369. const flatArray = Array.isArray(values)
  6370. ? values.flat()
  6371. : values;
  6372. const dataFormatter = new DataFormatter(Array.from(new Set(flatArray)), maxThreshold);
  6373. dataFormatter.addInputOutput();
  6374. dataFormatter.addUnrecognized();
  6375. dataFormatter.isSetup = true;
  6376. return dataFormatter;
  6377. }
  6378. static fromString(string, maxThreshold = 0) {
  6379. const values = Array.from(new Set(string)).join('');
  6380. return new DataFormatter(values.split(''), maxThreshold);
  6381. }
  6382. toJSON() {
  6383. return {
  6384. indexTable: this.indexTable,
  6385. characterTable: this.characterTable,
  6386. values: this.values,
  6387. characters: this.characters,
  6388. specialIndexes: this.specialIndexes,
  6389. };
  6390. }
  6391. /** TODO: Type better, The type of json is not "string that is a valid JSON", it is a POJO in the shape of DataFormatter.
  6392. * this method re-hydrates the the data as an instance of DataFormatter.
  6393. */
  6394. static fromJSON(json) {
  6395. const dataFormatter = new DataFormatter();
  6396. dataFormatter.indexTable = json.indexTable;
  6397. dataFormatter.characterTable = json.characterTable;
  6398. dataFormatter.values = json.values;
  6399. dataFormatter.characters = json.characters;
  6400. dataFormatter.specialIndexes = json.specialIndexes;
  6401. return dataFormatter;
  6402. }
  6403. addSpecial(special, character = null) {
  6404. const specialIndex = (this.indexTable[special] = this.characters.length);
  6405. this.characterTable[specialIndex] = character;
  6406. this.specialIndexes.push(this.characters.length);
  6407. this.characters.push(special);
  6408. }
  6409. toFunctionString() {
  6410. return `
  6411. var characterTable = ${JSON.stringify(this.characterTable)};
  6412. var indexTable = ${JSON.stringify(this.indexTable)};
  6413. var characters = ${JSON.stringify(this.characters)};
  6414. var dataFormatter = {
  6415. toIndexes: function ${this.toIndexes.toString()},
  6416. toIndexesInputOutput: function ${this.toIndexesInputOutput.toString()},
  6417. toCharacters: function ${this.toCharacters.toString()},
  6418. toIndexesValue: function ${this.toIndexesValue.toString()},
  6419. };`;
  6420. }
  6421. formatDataIn(input, output) {
  6422. var _a;
  6423. if (input === undefined)
  6424. return [];
  6425. if (Array.isArray(input) && typeof input[0] === 'number') {
  6426. return input;
  6427. }
  6428. if ((_a = this.indexTable) === null || _a === void 0 ? void 0 : _a.hasOwnProperty('stop-input')) {
  6429. return this.toIndexesInputOutput(input, output);
  6430. }
  6431. return this.toIndexes(input);
  6432. }
  6433. formatDataOut(input, output) {
  6434. return this.toCharacters(output).join('');
  6435. }
  6436. format(data) {
  6437. if (typeof data[0] === 'number' &&
  6438. !Array.isArray(data[0]) &&
  6439. (!data[0].hasOwnProperty('input') || !data[0].hasOwnProperty('output'))) {
  6440. return data;
  6441. }
  6442. const result = [];
  6443. if (typeof data[0] === 'string' ||
  6444. typeof data[0] === 'number' ||
  6445. Array.isArray(data[0])) {
  6446. if (!this.isSetup) {
  6447. this.setup(data);
  6448. for (let i = 0; i < data.length; i++) {
  6449. result.push(this.formatDataIn(validateAndCast(data[i])));
  6450. }
  6451. }
  6452. else {
  6453. for (let i = 0, max = data.length; i < max; i++) {
  6454. result.push(this.formatDataIn(data[i]));
  6455. }
  6456. }
  6457. }
  6458. else if (data[0].input && data[0].output) {
  6459. if (!this.isSetup) {
  6460. this.setup(data);
  6461. }
  6462. for (let i = 0, max = data.length; i < max; i++) {
  6463. result.push(this.formatDataIn(validateAndCast(data[i].input), validateAndCast(data[i].output)));
  6464. }
  6465. }
  6466. else {
  6467. throw new Error('unrecognized data');
  6468. }
  6469. return result;
  6470. }
  6471. }
  6472. function validateAndCast(value) {
  6473. if (typeof value === 'string')
  6474. return value;
  6475. if (typeof value === 'number')
  6476. return value.toString();
  6477. if (typeof value === 'boolean')
  6478. return value.toString();
  6479. if (Array.isArray(value) && typeof value[0] === 'string')
  6480. return value;
  6481. if (typeof value[0] === 'boolean') {
  6482. return value.map((v) => v.toString());
  6483. }
  6484. if (typeof value[0] === 'number') {
  6485. return value.map((v) => v.toString());
  6486. }
  6487. throw new Error('unrecognized value, expected string[], string, number[], number, boolean[], or boolean');
  6488. }
  6489. function copy(product, left) {
  6490. product.rows = left.rows;
  6491. product.columns = left.columns;
  6492. product.weights = left.weights.slice(0);
  6493. product.deltas = left.deltas.slice(0);
  6494. }
  6495. /**
  6496. * add {left} and {right} matrix weights into {into}
  6497. */
  6498. function add(product, left, right) {
  6499. for (let i = 0; i < left.weights.length; i++) {
  6500. product.weights[i] = left.weights[i] + right.weights[i];
  6501. product.deltas[i] = 0;
  6502. }
  6503. }
  6504. /**
  6505. * adds {from} deltas to {left} and {right} deltas
  6506. */
  6507. function addB(product, left, right) {
  6508. for (let i = 0; i < product.deltas.length; i++) {
  6509. left.deltas[i] = product.deltas[i];
  6510. right.deltas[i] = product.deltas[i];
  6511. }
  6512. }
  6513. /**
  6514. * makes matrix weights and deltas all ones
  6515. */
  6516. function allOnes(product) {
  6517. for (let i = 0; i < product.weights.length; i++) {
  6518. product.weights[i] = 1;
  6519. product.deltas[i] = 0;
  6520. }
  6521. }
  6522. function cloneNegative(product, left) {
  6523. product.rows = left.rows;
  6524. product.columns = left.columns;
  6525. product.weights = left.weights.slice(0);
  6526. product.deltas = left.deltas.slice(0);
  6527. for (let i = 0; i < left.weights.length; i++) {
  6528. product.weights[i] = -left.weights[i];
  6529. product.deltas[i] = 0;
  6530. }
  6531. }
  6532. /**
  6533. * multiply {left} and {right} matrix weights to {into}
  6534. */
  6535. function multiply(product, left, right) {
  6536. const leftRows = left.rows;
  6537. const leftColumns = left.columns;
  6538. const rightColumns = right.columns;
  6539. // loop over rows of left
  6540. for (let leftRow = 0; leftRow < leftRows; leftRow++) {
  6541. const leftRowBase = leftColumns * leftRow;
  6542. const rightRowBase = rightColumns * leftRow;
  6543. // loop over cols of right
  6544. for (let rightColumn = 0; rightColumn < rightColumns; rightColumn++) {
  6545. // dot product loop
  6546. let dot = 0;
  6547. // loop over columns of left
  6548. for (let leftColumn = 0; leftColumn < leftColumns; leftColumn++) {
  6549. const rightColumnBase = rightColumns * leftColumn;
  6550. const leftIndex = leftRowBase + leftColumn;
  6551. const rightIndex = rightColumnBase + rightColumn;
  6552. dot += left.weights[leftIndex] * right.weights[rightIndex];
  6553. left.deltas[leftIndex] = 0;
  6554. right.deltas[rightIndex] = 0;
  6555. }
  6556. product.weights[rightRowBase + rightColumn] = dot;
  6557. }
  6558. }
  6559. }
  6560. /**
  6561. * multiplies {from} deltas to {left} and {right}
  6562. */
  6563. function multiplyB(product, left, right) {
  6564. const leftRows = left.rows;
  6565. const leftColumns = left.columns;
  6566. const rightColumns = right.columns;
  6567. // loop over rows of left
  6568. for (let leftRowRoot = 0; leftRowRoot < leftRows; leftRowRoot++) {
  6569. const leftRowBase = leftColumns * leftRowRoot;
  6570. const rightRowBase = rightColumns * leftRowRoot;
  6571. // loop over cols of right
  6572. for (let rightColumn = 0; rightColumn < rightColumns; rightColumn++) {
  6573. // loop over columns of left
  6574. for (let leftColumn = 0; leftColumn < leftColumns; leftColumn++) {
  6575. const rightColumnBase = rightColumns * leftColumn;
  6576. const leftRow = leftRowBase + leftColumn;
  6577. const rightRow = rightColumnBase + rightColumn;
  6578. const backPropagateValue = product.deltas[rightRowBase + rightColumn];
  6579. left.deltas[leftRow] += right.weights[rightRow] * backPropagateValue;
  6580. right.deltas[rightRow] += left.weights[leftRow] * backPropagateValue;
  6581. }
  6582. }
  6583. }
  6584. }
  6585. function multiplyElement(product, left, right) {
  6586. const { weights } = left;
  6587. for (let i = 0; i < weights.length; i++) {
  6588. product.weights[i] = left.weights[i] * right.weights[i];
  6589. product.deltas[i] = 0;
  6590. }
  6591. }
  6592. /**
  6593. * multiplies {left} and {right} weight by {from} deltas into {left} and {right} deltas
  6594. */
  6595. function multiplyElementB(product, left, right) {
  6596. for (let i = 0; i < left.weights.length; i++) {
  6597. left.deltas[i] = right.weights[i] * product.deltas[i];
  6598. right.deltas[i] = left.weights[i] * product.deltas[i];
  6599. }
  6600. }
  6601. /**
  6602. *
  6603. * relu {m} weights to {into} weights
  6604. */
  6605. function relu(product, left) {
  6606. for (let i = 0; i < left.weights.length; i++) {
  6607. product.weights[i] = Math.max(0, left.weights[i]); // relu
  6608. product.deltas[i] = 0;
  6609. }
  6610. }
  6611. /**
  6612. * adds {from} deltas to {m} deltas when {m} weights are above other a threshold of 0
  6613. */
  6614. function reluB(product, left) {
  6615. for (let i = 0; i < product.deltas.length; i++) {
  6616. left.deltas[i] = left.weights[i] > 0 ? product.deltas[i] : 0;
  6617. }
  6618. }
  6619. function rowPluck(product, left, rowPluckIndex) {
  6620. const { columns } = left;
  6621. const rowBase = columns * rowPluckIndex;
  6622. for (let column = 0; column < columns; column++) {
  6623. product.weights[column] = left.weights[rowBase + column];
  6624. product.deltas[column] = 0;
  6625. }
  6626. }
  6627. /**
  6628. * adds {from} deltas into {m} deltas
  6629. */
  6630. function rowPluckB(product, left, rowIndex) {
  6631. const { columns } = left;
  6632. const rowBase = columns * rowIndex;
  6633. for (let column = 0; column < columns; column++) {
  6634. left.deltas[rowBase + column] = product.deltas[column];
  6635. }
  6636. }
  6637. function sigmoid(product, left) {
  6638. // sigmoid nonlinearity
  6639. for (let i = 0; i < left.weights.length; i++) {
  6640. product.weights[i] = 1 / (1 + Math.exp(-left.weights[i]));
  6641. product.deltas[i] = 0;
  6642. }
  6643. }
  6644. // function sig(x) {
  6645. // // helper function for computing sigmoid
  6646. // return 1 / (1 + Math.exp(-x));
  6647. // }
  6648. function sigmoidB(product, left) {
  6649. for (let i = 0; i < product.deltas.length; i++) {
  6650. const mwi = product.weights[i];
  6651. left.deltas[i] = mwi * (1 - mwi) * product.deltas[i];
  6652. }
  6653. }
  6654. function softmax(matrix) {
  6655. // probability volume
  6656. const result = new Matrix(matrix.rows, matrix.columns);
  6657. let maxVal = -999999;
  6658. for (let i = 0; i < matrix.weights.length; i++) {
  6659. if (matrix.weights[i] > maxVal) {
  6660. maxVal = matrix.weights[i];
  6661. }
  6662. }
  6663. let s = 0;
  6664. for (let i = 0; i < matrix.weights.length; i++) {
  6665. result.weights[i] = Math.exp(matrix.weights[i] - maxVal);
  6666. s += result.weights[i];
  6667. }
  6668. for (let i = 0; i < matrix.weights.length; i++) {
  6669. result.weights[i] /= s;
  6670. }
  6671. // no backward pass here needed
  6672. // since we will use the computed probabilities outside
  6673. // to set gradients directly on m
  6674. return result;
  6675. }
  6676. function tanh(product, left) {
  6677. // tanh nonlinearity
  6678. for (let i = 0; i < left.weights.length; i++) {
  6679. product.weights[i] = Math.tanh(left.weights[i]);
  6680. product.deltas[i] = 0;
  6681. }
  6682. }
  6683. function tanhB(product, left) {
  6684. for (let i = 0; i < product.deltas.length; i++) {
  6685. // grad for z = tanh(x) is (1 - z^2)
  6686. const mwi = product.weights[i];
  6687. left.deltas[i] = (1 - mwi * mwi) * product.deltas[i];
  6688. }
  6689. }
  6690. class Equation {
  6691. constructor() {
  6692. this.states = [];
  6693. this.inputRow = 0;
  6694. }
  6695. add(left, right) {
  6696. if (left.weights.length !== right.weights.length) {
  6697. throw new Error('misaligned matrices');
  6698. }
  6699. const product = new Matrix(left.rows, left.columns);
  6700. this.states.push({
  6701. name: 'add',
  6702. product,
  6703. left,
  6704. right,
  6705. forwardFn: add,
  6706. backpropagationFn: addB,
  6707. });
  6708. return product;
  6709. }
  6710. allOnes(rows, columns) {
  6711. const product = new Matrix(rows, columns);
  6712. this.states.push({
  6713. name: 'allOnes',
  6714. product,
  6715. left: product,
  6716. forwardFn: allOnes,
  6717. backpropagationFn: () => { },
  6718. });
  6719. return product;
  6720. }
  6721. cloneNegative(matrix) {
  6722. const product = new Matrix(matrix.rows, matrix.columns);
  6723. this.states.push({
  6724. name: 'cloneNegative',
  6725. product,
  6726. left: matrix,
  6727. forwardFn: cloneNegative,
  6728. backpropagationFn: () => { },
  6729. });
  6730. return product;
  6731. }
  6732. /**
  6733. * connects two matrices together by subtract
  6734. */
  6735. subtract(left, right) {
  6736. if (left.weights.length !== right.weights.length) {
  6737. throw new Error('misaligned matrices');
  6738. }
  6739. return this.add(this.add(this.allOnes(left.rows, left.columns), this.cloneNegative(left)), right);
  6740. }
  6741. /**
  6742. * connects two matrices together by multiply
  6743. */
  6744. multiply(left, right) {
  6745. if (left.columns !== right.rows) {
  6746. throw new Error('misaligned matrices');
  6747. }
  6748. const product = new Matrix(left.rows, right.columns);
  6749. this.states.push({
  6750. name: 'multiply',
  6751. product,
  6752. left,
  6753. right,
  6754. forwardFn: multiply,
  6755. backpropagationFn: multiplyB,
  6756. });
  6757. return product;
  6758. }
  6759. /**
  6760. * connects two matrices together by multiplyElement
  6761. */
  6762. multiplyElement(left, right) {
  6763. if (left.weights.length !== right.weights.length) {
  6764. throw new Error('misaligned matrices');
  6765. }
  6766. const product = new Matrix(left.rows, left.columns);
  6767. this.states.push({
  6768. name: 'multiplyElement',
  6769. product,
  6770. left,
  6771. right,
  6772. forwardFn: multiplyElement,
  6773. backpropagationFn: multiplyElementB,
  6774. });
  6775. return product;
  6776. }
  6777. /**
  6778. * connects a matrix to relu
  6779. */
  6780. relu(matrix) {
  6781. const product = new Matrix(matrix.rows, matrix.columns);
  6782. this.states.push({
  6783. name: 'relu',
  6784. product,
  6785. left: matrix,
  6786. forwardFn: relu,
  6787. backpropagationFn: reluB,
  6788. });
  6789. return product;
  6790. }
  6791. /**
  6792. * input a matrix
  6793. */
  6794. input(input) {
  6795. this.states.push({
  6796. name: 'input',
  6797. product: input,
  6798. forwardFn: (product) => {
  6799. if (!this.inputValue)
  6800. return;
  6801. if (this.inputValue.length !== product.weights.length) {
  6802. throw new Error('this.inputValue is of wrong dimensions');
  6803. }
  6804. product.weights = input.weights = this.inputValue;
  6805. },
  6806. backpropagationFn: () => { },
  6807. });
  6808. return input;
  6809. }
  6810. /**
  6811. * connects a matrix via a row
  6812. */
  6813. inputMatrixToRow(matrix) {
  6814. // eslint-disable-next-line @typescript-eslint/no-this-alias
  6815. const self = this;
  6816. const product = new Matrix(matrix.columns, 1);
  6817. this.states.push({
  6818. name: 'inputMatrixToRow',
  6819. product,
  6820. left: matrix,
  6821. get right() {
  6822. return self.inputRow;
  6823. },
  6824. forwardFn: rowPluck,
  6825. backpropagationFn: rowPluckB,
  6826. });
  6827. return product;
  6828. }
  6829. /**
  6830. * connects a matrix to sigmoid
  6831. */
  6832. sigmoid(matrix) {
  6833. const product = new Matrix(matrix.rows, matrix.columns);
  6834. this.states.push({
  6835. name: 'sigmoid',
  6836. product,
  6837. left: matrix,
  6838. forwardFn: sigmoid,
  6839. backpropagationFn: sigmoidB,
  6840. });
  6841. return product;
  6842. }
  6843. /**
  6844. * connects a matrix to tanh
  6845. */
  6846. tanh(matrix) {
  6847. const product = new Matrix(matrix.rows, matrix.columns);
  6848. this.states.push({
  6849. name: 'tanh',
  6850. product,
  6851. left: matrix,
  6852. forwardFn: tanh,
  6853. backpropagationFn: tanhB,
  6854. });
  6855. return product;
  6856. }
  6857. /**
  6858. *
  6859. * Observe a matrix for debugging
  6860. */
  6861. observe(matrix) {
  6862. this.states.push({
  6863. name: 'observe',
  6864. product: new Matrix(),
  6865. forwardFn: () => { },
  6866. backpropagationFn: () => { },
  6867. });
  6868. return matrix;
  6869. }
  6870. /**
  6871. * Run index through equations via forward propagation
  6872. */
  6873. runIndex(rowIndex = 0) {
  6874. this.inputRow = rowIndex;
  6875. let state = this.states[0];
  6876. for (let i = 0, max = this.states.length; i < max; i++) {
  6877. state = this.states[i];
  6878. if (!state.hasOwnProperty('forwardFn'))
  6879. continue;
  6880. state.forwardFn(state.product, state.left, state.right);
  6881. }
  6882. return state.product;
  6883. }
  6884. /**
  6885. * Run value through equations via forward propagation
  6886. */
  6887. runInput(inputValue) {
  6888. this.inputValue = inputValue;
  6889. let state = this.states[0];
  6890. for (let i = 0, max = this.states.length; i < max; i++) {
  6891. state = this.states[i];
  6892. if (!state.hasOwnProperty('forwardFn'))
  6893. continue;
  6894. state.forwardFn(state.product, state.left, state.right);
  6895. }
  6896. return state.product;
  6897. }
  6898. /**
  6899. * Run value through equations via back propagation
  6900. */
  6901. backpropagate() {
  6902. let i = this.states.length;
  6903. let state = this.states[0];
  6904. while (i-- > 0) {
  6905. state = this.states[i];
  6906. if (!state.hasOwnProperty('backpropagationFn'))
  6907. continue;
  6908. state.backpropagationFn(state.product, state.left, state.right);
  6909. }
  6910. return state.product;
  6911. }
  6912. /**
  6913. * Run index through equations via back propagation
  6914. */
  6915. backpropagateIndex(rowIndex = 0) {
  6916. this.inputRow = rowIndex;
  6917. let i = this.states.length;
  6918. let state = this.states[0];
  6919. while (i-- > 0) {
  6920. state = this.states[i];
  6921. if (!state.hasOwnProperty('backpropagationFn'))
  6922. continue;
  6923. state.backpropagationFn(state.product, state.left, state.right);
  6924. }
  6925. return state.product;
  6926. }
  6927. /**
  6928. * Predict a target value from equation
  6929. */
  6930. predictTarget(input, target) {
  6931. let errorSum = 0;
  6932. const output = this.runInput(input);
  6933. for (let i = 0; i < output.weights.length; i++) {
  6934. const error = output.weights[i] - target[i];
  6935. // set gradients into log probabilities
  6936. errorSum += Math.abs(error);
  6937. // write gradients into log probabilities
  6938. output.deltas[i] = error;
  6939. }
  6940. return errorSum;
  6941. }
  6942. /**
  6943. * Predict a target index from equation
  6944. */
  6945. predictTargetIndex(input, target) {
  6946. const output = this.runIndex(input);
  6947. // set gradients into log probabilities
  6948. const logProbabilities = output; // interpret output as log probabilities
  6949. const probabilities = softmax(output); // compute the softmax probabilities
  6950. // write gradients into log probabilities
  6951. logProbabilities.deltas = probabilities.weights.slice(0);
  6952. logProbabilities.deltas[target] -= 1;
  6953. // accumulate base 2 log prob and do smoothing
  6954. return -Math.log2(probabilities.weights[target]);
  6955. }
  6956. }
  6957. function maxI(matrix) {
  6958. // argmax of array w
  6959. const { weights } = matrix;
  6960. let maxv = weights[0];
  6961. let maxix = 0;
  6962. for (let i = 1; i < weights.length; i++) {
  6963. const v = weights[i];
  6964. if (v < maxv)
  6965. continue;
  6966. maxix = i;
  6967. maxv = v;
  6968. }
  6969. return maxix;
  6970. }
  6971. function sampleI(matrix) {
  6972. // sample argmax from w, assuming w are
  6973. // probabilities that sum to one
  6974. const r = randomFloat(0, 1);
  6975. const w = matrix.weights;
  6976. let x = 0;
  6977. let i = 0;
  6978. while (true) {
  6979. x += w[i];
  6980. if (x > r) {
  6981. return i;
  6982. }
  6983. i++;
  6984. }
  6985. }
  6986. const trainDefaults$1 = {
  6987. iterations: 20000,
  6988. errorThresh: 0.005,
  6989. log: false,
  6990. logPeriod: 10,
  6991. learningRate: 0.01,
  6992. callbackPeriod: 10,
  6993. timeout: Infinity,
  6994. };
  6995. const defaults$1 = () => {
  6996. return {
  6997. inputSize: 20,
  6998. inputRange: 20,
  6999. hiddenLayers: [20, 20],
  7000. outputSize: 20,
  7001. decayRate: 0.999,
  7002. smoothEps: 1e-8,
  7003. regc: 0.000001,
  7004. clipval: 5,
  7005. maxPredictionLength: 100,
  7006. dataFormatter: new DataFormatter(),
  7007. };
  7008. };
  7009. class RNN {
  7010. constructor(options = {}) {
  7011. this.options = { ...defaults$1() };
  7012. this.trainOpts = { ...trainDefaults$1 };
  7013. this.stepCache = {};
  7014. this.runs = 0;
  7015. this.ratioClipped = 0;
  7016. this.model = Object.seal({
  7017. isInitialized: false,
  7018. input: new Matrix(0, 0),
  7019. hiddenLayers: [],
  7020. output: new Matrix(0, 0),
  7021. equations: [],
  7022. allMatrices: [],
  7023. equationConnections: [],
  7024. outputConnector: new RandomMatrix(0, 0, 0.08),
  7025. });
  7026. this.initialLayerInputs = [];
  7027. this.options = { ...this.options, ...options };
  7028. this.updateTrainingOptions({
  7029. ...trainDefaults$1,
  7030. });
  7031. if (options.json) {
  7032. this.fromJSON(options.json);
  7033. }
  7034. }
  7035. initialize() {
  7036. const { dataFormatter } = this.options;
  7037. if (dataFormatter === null || dataFormatter === void 0 ? void 0 : dataFormatter.characters.length) {
  7038. this.options.inputSize = this.options.inputRange = this.options.outputSize =
  7039. dataFormatter.characters.length;
  7040. }
  7041. this.model = this.mapModel();
  7042. }
  7043. createHiddenLayers() {
  7044. const { hiddenLayers, inputSize } = this.options;
  7045. const hiddenLayersModel = [];
  7046. // 0 is end, so add 1 to offset
  7047. hiddenLayersModel.push(this.getHiddenLayer(hiddenLayers[0], inputSize));
  7048. let prevSize = hiddenLayers[0];
  7049. for (let d = 1; d < hiddenLayers.length; d++) {
  7050. // loop over depths
  7051. const hiddenSize = hiddenLayers[d];
  7052. hiddenLayersModel.push(this.getHiddenLayer(hiddenSize, prevSize));
  7053. prevSize = hiddenSize;
  7054. }
  7055. return hiddenLayersModel;
  7056. }
  7057. getHiddenLayer(hiddenSize, prevSize) {
  7058. return {
  7059. // wxh
  7060. weight: new RandomMatrix(hiddenSize, prevSize, 0.08),
  7061. // whh
  7062. transition: new RandomMatrix(hiddenSize, hiddenSize, 0.08),
  7063. // bhh
  7064. bias: new Matrix(hiddenSize, 1),
  7065. };
  7066. }
  7067. getEquation(equation, inputMatrix, previousResult, hiddenLayer) {
  7068. if (!hiddenLayer.weight || !hiddenLayer.transition || !hiddenLayer.bias) {
  7069. throw new Error('hiddenLayer does not have expected properties');
  7070. }
  7071. const relu = equation.relu.bind(equation);
  7072. const add = equation.add.bind(equation);
  7073. const multiply = equation.multiply.bind(equation);
  7074. return relu(add(add(multiply(hiddenLayer.weight, inputMatrix), multiply(hiddenLayer.transition, previousResult)), hiddenLayer.bias));
  7075. }
  7076. createInputMatrix() {
  7077. const { inputRange, inputSize } = this.options;
  7078. if (inputRange < 1)
  7079. throw new Error('this.options.inputRange not an expected number');
  7080. if (inputSize < 1)
  7081. throw new Error('this.options.inputSize not an expected number');
  7082. // 0 is end, so add 1 to offset
  7083. return new RandomMatrix(inputRange + 1, inputSize, 0.08);
  7084. }
  7085. createOutputMatrices() {
  7086. const { outputSize, hiddenLayers } = this.options;
  7087. const lastHiddenSize = last(hiddenLayers);
  7088. // 0 is end, so add 1 to offset
  7089. return {
  7090. // whd
  7091. outputConnector: new RandomMatrix(outputSize + 1, lastHiddenSize, 0.08),
  7092. // 0 is end, so add 1 to offset
  7093. // bd
  7094. output: new Matrix(outputSize + 1, 1),
  7095. };
  7096. }
  7097. bindEquation() {
  7098. const { model } = this;
  7099. const { hiddenLayers } = this.options;
  7100. const equation = new Equation();
  7101. const outputs = [];
  7102. const equationConnection = model.equationConnections.length > 0
  7103. ? last(model.equationConnections)
  7104. : this.initialLayerInputs;
  7105. // 0 index
  7106. let output = this.getEquation(equation, equation.inputMatrixToRow(model.input), equationConnection[0], model.hiddenLayers[0]);
  7107. outputs.push(output);
  7108. // 1+ indices
  7109. for (let i = 1, max = hiddenLayers.length; i < max; i++) {
  7110. if (!equationConnection[i]) {
  7111. throw new Error(`Cannot find equation at index ${i}`);
  7112. }
  7113. output = this.getEquation(equation, output, equationConnection[i], model.hiddenLayers[i]);
  7114. outputs.push(output);
  7115. }
  7116. model.equationConnections.push(outputs);
  7117. equation.add(equation.multiply(model.outputConnector, output), model.output);
  7118. model.equations.push(equation);
  7119. }
  7120. mapModel() {
  7121. const allMatrices = [];
  7122. this.initialLayerInputs = this.options.hiddenLayers.map((size) => new Matrix(size, 1));
  7123. const input = this.createInputMatrix();
  7124. allMatrices.push(input);
  7125. const hiddenLayers = this.createHiddenLayers();
  7126. if (!hiddenLayers.length)
  7127. throw new Error('net.hiddenLayers not set');
  7128. for (let i = 0, max = hiddenLayers.length; i < max; i++) {
  7129. const hiddenMatrix = hiddenLayers[i];
  7130. for (const property in hiddenMatrix) {
  7131. if (!hiddenMatrix.hasOwnProperty(property))
  7132. continue;
  7133. allMatrices.push(hiddenMatrix[property]);
  7134. }
  7135. }
  7136. const { output, outputConnector } = this.createOutputMatrices();
  7137. allMatrices.push(outputConnector);
  7138. allMatrices.push(output);
  7139. return Object.seal({
  7140. isInitialized: true,
  7141. input,
  7142. hiddenLayers,
  7143. output,
  7144. equations: [],
  7145. allMatrices,
  7146. equationConnections: [],
  7147. outputConnector,
  7148. });
  7149. }
  7150. trainInput(input) {
  7151. this.runs++;
  7152. const { model } = this;
  7153. const max = input.length;
  7154. let log2ppl = 0;
  7155. let equation;
  7156. while (model.equations.length <= input.length + 1) {
  7157. // last is zero
  7158. this.bindEquation();
  7159. }
  7160. for (let inputIndex = -1, inputMax = input.length; inputIndex < inputMax; inputIndex++) {
  7161. // start and end tokens are zeros
  7162. const equationIndex = inputIndex + 1;
  7163. equation = model.equations[equationIndex];
  7164. const source = inputIndex === -1 ? 0 : input[inputIndex] + 1; // first step: start with START token
  7165. const target = inputIndex === max - 1 ? 0 : input[inputIndex + 1] + 1; // last step: end with END token
  7166. log2ppl += equation.predictTargetIndex(source, target);
  7167. }
  7168. return Math.pow(2, log2ppl / (max - 1)) / 100;
  7169. }
  7170. backpropagate(input) {
  7171. let i = input.length;
  7172. const { model } = this;
  7173. const { equations } = model;
  7174. while (i > 0) {
  7175. equations[i].backpropagateIndex(input[i - 1] + 1);
  7176. i--;
  7177. }
  7178. equations[0].backpropagateIndex(0);
  7179. }
  7180. adjustWeights() {
  7181. const { regc, clipval, decayRate, smoothEps } = this.options;
  7182. const { trainOpts, model, stepCache } = this;
  7183. const { learningRate } = trainOpts;
  7184. const { allMatrices } = model;
  7185. let numClipped = 0;
  7186. let numTot = 0;
  7187. for (let matrixIndex = 0; matrixIndex < allMatrices.length; matrixIndex++) {
  7188. const matrix = allMatrices[matrixIndex];
  7189. const { weights, deltas } = matrix;
  7190. if (!(matrixIndex in stepCache)) {
  7191. stepCache[matrixIndex] = zeros$1(matrix.rows * matrix.columns);
  7192. }
  7193. const cache = stepCache[matrixIndex];
  7194. for (let i = 0; i < weights.length; i++) {
  7195. let r = deltas[i];
  7196. const w = weights[i];
  7197. // rmsprop adaptive learning rate
  7198. cache[i] = cache[i] * decayRate + (1 - decayRate) * r * r;
  7199. // gradient clip
  7200. if (r > clipval) {
  7201. r = clipval;
  7202. numClipped++;
  7203. }
  7204. else if (r < -clipval) {
  7205. r = -clipval;
  7206. numClipped++;
  7207. }
  7208. numTot++;
  7209. // update (and regularize)
  7210. weights[i] =
  7211. w + (-learningRate * r) / Math.sqrt(cache[i] + smoothEps) - regc * w;
  7212. }
  7213. }
  7214. this.ratioClipped = numClipped / numTot;
  7215. }
  7216. get isRunnable() {
  7217. if (this.model && this.model.equations.length === 0) {
  7218. console.error(`No equations bound, did you run train()?`);
  7219. return false;
  7220. }
  7221. return true;
  7222. }
  7223. checkRunnable() {
  7224. if (!this.isRunnable) {
  7225. throw new Error('Network not runnable');
  7226. }
  7227. }
  7228. run(rawInput = [], isSampleI = false, temperature = 1) {
  7229. const maxPredictionLength = this.options.maxPredictionLength +
  7230. (rawInput !== null ? rawInput.length : 0) +
  7231. (this.options.dataFormatter
  7232. ? this.options.dataFormatter.specialIndexes.length
  7233. : 0);
  7234. this.checkRunnable();
  7235. const input = this.options.dataFormatter && rawInput.length > 0
  7236. ? this.options.dataFormatter.formatDataIn(rawInput)
  7237. : rawInput;
  7238. const { model } = this;
  7239. const output = [];
  7240. let i = 0;
  7241. while (true) {
  7242. const previousIndex = i === 0 ? 0 : i < input.length ? input[i - 1] + 1 : output[i - 1];
  7243. while (model.equations.length <= i) {
  7244. this.bindEquation();
  7245. }
  7246. const equation = model.equations[i];
  7247. // sample predicted letter
  7248. const outputMatrix = equation.runIndex(previousIndex);
  7249. const logProbabilities = new Matrix(model.output.rows, model.output.columns);
  7250. copy(logProbabilities, outputMatrix);
  7251. if (temperature !== 1 && isSampleI) {
  7252. /**
  7253. * scale log probabilities by temperature and re-normalize
  7254. * if temperature is high, logProbabilities will go towards zero
  7255. * and the softmax outputs will be more diffuse. if temperature is
  7256. * very low, the softmax outputs will be more peaky
  7257. */
  7258. for (let j = 0, max = logProbabilities.weights.length; j < max; j++) {
  7259. logProbabilities.weights[j] /= temperature;
  7260. }
  7261. }
  7262. const probs = softmax(logProbabilities);
  7263. const nextIndex = isSampleI ? sampleI(probs) : maxI(probs);
  7264. i++;
  7265. if (nextIndex === 0) {
  7266. // END token predicted, break out
  7267. break;
  7268. }
  7269. if (i >= maxPredictionLength) {
  7270. // something is wrong
  7271. break;
  7272. }
  7273. output.push(nextIndex);
  7274. }
  7275. /**
  7276. * we slice the input length here, not because output contains it, but it will be erroneous as we are sending the
  7277. * network what is contained in input, so the data is essentially guessed by the network what could be next, till it
  7278. * locks in on a value.
  7279. * Kind of like this, values are from input:
  7280. * 0 -> 4 (or in English: "beginning on input" -> "I have no idea? I'll guess what they want next!")
  7281. * 2 -> 2 (oh how interesting, I've narrowed down values...)
  7282. * 1 -> 9 (oh how interesting, I've now know what the values are...)
  7283. * then the output looks like: [4, 2, 9,...]
  7284. * so we then remove the erroneous data to get our true output
  7285. */
  7286. return this.options.dataFormatter.formatDataOut(input, output.slice(input.length).map((value) => value - 1));
  7287. }
  7288. /**
  7289. *
  7290. * Verifies network sizes are initialized
  7291. * If they are not it will initialize them
  7292. */
  7293. verifyIsInitialized() {
  7294. if (!this.model.isInitialized) {
  7295. this.initialize();
  7296. }
  7297. }
  7298. /**
  7299. *
  7300. * @param options
  7301. * Supports all `trainDefaults` properties
  7302. * also supports:
  7303. * learningRate: (number),
  7304. * momentum: (number),
  7305. * activation: 'sigmoid', 'relu', 'leaky-relu', 'tanh'
  7306. */
  7307. updateTrainingOptions(options) {
  7308. var _a;
  7309. this.trainOpts = { ...trainDefaults$1, ...options };
  7310. this.validateTrainingOptions(this.trainOpts);
  7311. this.setLogMethod((_a = options.log) !== null && _a !== void 0 ? _a : this.trainOpts.log);
  7312. // TODO: Remove this?
  7313. // this.activation = options.activation || this.activation;
  7314. }
  7315. validateTrainingOptions(options) {
  7316. const validations = {
  7317. iterations: () => {
  7318. const val = options.iterations;
  7319. return typeof val === 'number' && val > 0;
  7320. },
  7321. errorThresh: () => {
  7322. const val = options.errorThresh;
  7323. return typeof val === 'number' && val > 0 && val < 1;
  7324. },
  7325. log: () => {
  7326. const val = options.log;
  7327. return typeof val === 'function' || typeof val === 'boolean';
  7328. },
  7329. logPeriod: () => {
  7330. const val = options.logPeriod;
  7331. return typeof val === 'number' && val > 0;
  7332. },
  7333. learningRate: () => {
  7334. const val = options.learningRate;
  7335. return typeof val === 'number' && val > 0 && val < 1;
  7336. },
  7337. callback: () => {
  7338. const val = options.callback;
  7339. return typeof val === 'function' || val === undefined;
  7340. },
  7341. callbackPeriod: () => {
  7342. const val = options.callbackPeriod;
  7343. return typeof val === 'number' && val > 0;
  7344. },
  7345. timeout: () => {
  7346. const val = options.timeout;
  7347. return typeof val === 'number' && val > 0;
  7348. },
  7349. };
  7350. for (const p in validations) {
  7351. const v = options;
  7352. if (!validations[p]()) {
  7353. throw new Error(`[${p}, ${v[p]}] is out of normal training range, your network will probably not train.`);
  7354. }
  7355. }
  7356. }
  7357. setLogMethod(log) {
  7358. if (typeof log === 'function') {
  7359. this.trainOpts.log = log;
  7360. }
  7361. else if (log) {
  7362. this.trainOpts.log = console.log;
  7363. }
  7364. else {
  7365. this.trainOpts.log = false;
  7366. }
  7367. }
  7368. prepTraining(data, options) {
  7369. var _a;
  7370. this.updateTrainingOptions(options);
  7371. const preparedData = this.options.dataFormatter.format(data);
  7372. const endTime = Date.now() + ((_a = this.trainOpts.timeout) !== null && _a !== void 0 ? _a : 0);
  7373. const status = {
  7374. error: 1,
  7375. iterations: 0,
  7376. };
  7377. this.verifyIsInitialized();
  7378. return {
  7379. preparedData,
  7380. status,
  7381. endTime,
  7382. };
  7383. }
  7384. train(data, trainOpts = {}) {
  7385. var _a;
  7386. this.trainOpts = trainOpts = {
  7387. ...trainDefaults$1,
  7388. ...trainOpts,
  7389. };
  7390. const { iterations, errorThresh, logPeriod, callback, callbackPeriod, } = this.trainOpts;
  7391. const log = trainOpts.log === true ? console.log : trainOpts.log;
  7392. let error = Infinity;
  7393. let i;
  7394. let inputs;
  7395. if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.dataFormatter) {
  7396. inputs = this.options.dataFormatter.format(data);
  7397. }
  7398. else if (Array.isArray(data) &&
  7399. Array.isArray(data[0]) &&
  7400. typeof data[0][0] === 'number') {
  7401. inputs = data;
  7402. }
  7403. else {
  7404. throw new Error('training not in expected format of number[][]');
  7405. }
  7406. this.verifyIsInitialized();
  7407. for (i = 0; i < iterations && error > errorThresh; i++) {
  7408. let sum = 0;
  7409. for (let j = 0; j < inputs.length; j++) {
  7410. const err = this.trainPattern(inputs[j], true);
  7411. sum += err;
  7412. }
  7413. error = sum / data.length;
  7414. if (isNaN(error)) {
  7415. throw new Error('Network error rate is unexpected NaN, check network configurations and try again. Most probably input format is not correct or training data is not enough. ');
  7416. }
  7417. if (log && i % logPeriod === 0) {
  7418. log(`iterations: ${i}, training error: ${error}`);
  7419. }
  7420. if (callback && i % callbackPeriod === 0) {
  7421. callback({ error, iterations: i });
  7422. }
  7423. }
  7424. return {
  7425. error,
  7426. iterations: i,
  7427. };
  7428. }
  7429. addFormat() {
  7430. throw new Error('not yet implemented');
  7431. }
  7432. toJSON() {
  7433. if (!this.model.isInitialized) {
  7434. this.initialize();
  7435. }
  7436. const { model, options } = this;
  7437. return {
  7438. type: this.constructor.name,
  7439. options: { ...options, dataFormatter: options.dataFormatter.toJSON() },
  7440. trainOpts: {
  7441. ...this.trainOpts,
  7442. timeout: this.trainOpts.timeout === Infinity
  7443. ? 'Infinity'
  7444. : this.trainOpts.timeout,
  7445. },
  7446. input: model.input.toJSON(),
  7447. hiddenLayers: model.hiddenLayers.map((hiddenLayer) => {
  7448. const layers = {};
  7449. for (const p in hiddenLayer) {
  7450. if (!hiddenLayer.hasOwnProperty(p))
  7451. continue;
  7452. layers[p] = hiddenLayer[p].toJSON();
  7453. }
  7454. return layers;
  7455. }),
  7456. outputConnector: this.model.outputConnector.toJSON(),
  7457. output: this.model.output.toJSON(),
  7458. };
  7459. }
  7460. fromJSON(json) {
  7461. const { options } = json;
  7462. const allMatrices = [];
  7463. const input = Matrix.fromJSON(json.input);
  7464. allMatrices.push(input);
  7465. const hiddenLayers = [];
  7466. json.hiddenLayers.forEach((hiddenLayer) => {
  7467. const layers = {};
  7468. for (const p in hiddenLayer) {
  7469. layers[p] = Matrix.fromJSON(hiddenLayer[p]);
  7470. allMatrices.push(layers[p]);
  7471. }
  7472. hiddenLayers.push(layers);
  7473. });
  7474. const outputConnector = Matrix.fromJSON(json.outputConnector);
  7475. allMatrices.push(outputConnector);
  7476. const output = Matrix.fromJSON(json.output);
  7477. allMatrices.push(output);
  7478. if (options.dataFormatter) {
  7479. this.options = {
  7480. ...defaults$1(),
  7481. ...options,
  7482. dataFormatter: DataFormatter.fromJSON(options.dataFormatter),
  7483. };
  7484. }
  7485. else {
  7486. this.options = {
  7487. ...defaults$1(),
  7488. ...options,
  7489. dataFormatter: new DataFormatter(),
  7490. };
  7491. }
  7492. this.model = Object.seal({
  7493. isInitialized: true,
  7494. input,
  7495. hiddenLayers,
  7496. output,
  7497. allMatrices,
  7498. outputConnector,
  7499. equations: [],
  7500. equationConnections: [],
  7501. });
  7502. this.initialLayerInputs = this.options.hiddenLayers.map((size) => new Matrix(size, 1));
  7503. this.bindEquation();
  7504. return this;
  7505. }
  7506. toFunction(cb) {
  7507. const { model } = this;
  7508. const { equations } = this.model;
  7509. const equation = equations[1];
  7510. const { states } = equation;
  7511. const jsonString = JSON.stringify(this.toJSON());
  7512. function previousConnectionIndex(m) {
  7513. const connection = model.equationConnections[0];
  7514. const { states } = equations[0];
  7515. for (let i = 0, max = states.length; i < max; i++) {
  7516. if (states[i].product === m) {
  7517. return i;
  7518. }
  7519. }
  7520. return connection.indexOf(m);
  7521. }
  7522. function matrixOrigin(m, stateIndex) {
  7523. for (let i = 0, max = states.length; i < max; i++) {
  7524. const state = states[i];
  7525. if (i === stateIndex) {
  7526. const j = previousConnectionIndex(m);
  7527. if (j > -1 && (m === state.left || m === state.right)) {
  7528. return `typeof prevStates[${j}] === 'object' ? prevStates[${j}].product : new Matrix(${m.rows}, ${m.columns})`;
  7529. }
  7530. return `new Matrix(${m.rows}, ${m.columns})`;
  7531. }
  7532. if (m === state.product)
  7533. return `states[${i}].product`;
  7534. if (m === state.right)
  7535. return `states[${i}].right`;
  7536. if (m === state.left)
  7537. return `states[${i}].left`;
  7538. }
  7539. return '';
  7540. }
  7541. function matrixToString(m, stateIndex) {
  7542. if (!m || !m.rows || !m.columns)
  7543. return 'null';
  7544. if (m === model.input)
  7545. return `json.input`;
  7546. if (m === model.outputConnector)
  7547. return `json.outputConnector`;
  7548. if (m === model.output)
  7549. return `json.output`;
  7550. for (let i = 0, max = model.hiddenLayers.length; i < max; i++) {
  7551. const hiddenLayer = model.hiddenLayers[i];
  7552. for (const p in hiddenLayer) {
  7553. if (!hiddenLayer.hasOwnProperty(p))
  7554. continue;
  7555. if (hiddenLayer[p] !== m)
  7556. continue;
  7557. return `json.hiddenLayers[${i}].${p}`;
  7558. }
  7559. }
  7560. return matrixOrigin(m, stateIndex);
  7561. }
  7562. function toInner(fnString) {
  7563. // crude, but should be sufficient for now
  7564. // function() { body }
  7565. const fnParts = fnString.toString().split('{');
  7566. fnParts.shift();
  7567. // body }
  7568. const fnBodyString = fnParts.join('{');
  7569. const fnBodyParts = fnBodyString.split('}');
  7570. fnBodyParts.pop();
  7571. // body
  7572. return fnBodyParts
  7573. .join('}')
  7574. .split('\n')
  7575. .join('\n ')
  7576. .replace('product.deltas[i] = 0;', '')
  7577. .replace('product.deltas[column] = 0;', '')
  7578. .replace('left.deltas[leftIndex] = 0;', '')
  7579. .replace('right.deltas[rightIndex] = 0;', '')
  7580. .replace('product.deltas = left.deltas.slice(0);', '');
  7581. }
  7582. function fileName(fnName) {
  7583. return `src/recurrent/matrix/${fnName.replace(/[A-Z]/g, function (value) {
  7584. return `-${value.toLowerCase()}`;
  7585. })}.js`;
  7586. }
  7587. const statesRaw = [];
  7588. const usedFunctionNames = {};
  7589. const innerFunctionsSwitch = [];
  7590. for (let i = 0, max = states.length; i < max; i++) {
  7591. const state = states[i];
  7592. statesRaw.push(`states[${i}] = {
  7593. name: '${state.forwardFn.name}',
  7594. left: ${state.left ? matrixToString(state.left, i) : 'undefined'},
  7595. right: ${state.right ? matrixToString(state.right, i) : 'undefined'},
  7596. product: ${matrixToString(state.product, i)}
  7597. }`);
  7598. const fnName = state.forwardFn.name;
  7599. if (!usedFunctionNames[fnName]) {
  7600. usedFunctionNames[fnName] = true;
  7601. innerFunctionsSwitch.push(` case '${fnName}': //compiled from ${fileName(fnName)}
  7602. ${toInner(state.forwardFn.toString())}
  7603. break;`);
  7604. }
  7605. }
  7606. const src = `
  7607. if (typeof rawInput === 'undefined') rawInput = [];
  7608. if (typeof isSampleI === 'undefined') isSampleI = false;
  7609. if (typeof temperature === 'undefined') temperature = 1;
  7610. var json = ${jsonString};
  7611. ${this.options.dataFormatter
  7612. ? `${this.options.dataFormatter.toFunctionString()};
  7613. Object.assign(dataFormatter, json.options.dataFormatter);`
  7614. : ''}
  7615. ${this.options.dataFormatter &&
  7616. typeof this.options.dataFormatter.formatDataIn === 'function'
  7617. ? `const formatDataIn = function (input, output) { ${toInner(this.options.dataFormatter.formatDataIn.toString())} }.bind(dataFormatter);`
  7618. : ''}
  7619. ${this.options.dataFormatter !== null &&
  7620. typeof this.options.dataFormatter.formatDataOut === 'function'
  7621. ? `const formatDataOut = function formatDataOut(input, output) { ${toInner(this.options.dataFormatter.formatDataOut.toString())} }.bind(dataFormatter);`
  7622. : ''}
  7623. var maxPredictionLength =
  7624. ${this.options.maxPredictionLength} +
  7625. rawInput.length +
  7626. ${this.options.dataFormatter
  7627. ? this.options.dataFormatter.specialIndexes.length
  7628. : 0};
  7629. var input = ${this.options.dataFormatter &&
  7630. typeof this.options.dataFormatter.formatDataIn === 'function'
  7631. ? 'formatDataIn(rawInput)'
  7632. : 'rawInput'};
  7633. var _i = 0;
  7634. var output = [];
  7635. var states = [];
  7636. var prevStates;
  7637. while (true) {
  7638. var previousIndex = (_i === 0
  7639. ? 0
  7640. : _i < input.length
  7641. ? input[_i - 1] + 1
  7642. : output[_i - 1])
  7643. ;
  7644. var rowPluckIndex = previousIndex;
  7645. prevStates = states;
  7646. states = [];
  7647. ${statesRaw.join(';\n ')};
  7648. for (var stateIndex = 0, stateMax = ${statesRaw.length}; stateIndex < stateMax; stateIndex++) {
  7649. var state = states[stateIndex];
  7650. var product = state.product;
  7651. var left = state.left;
  7652. var right = state.right;
  7653. switch (state.name) {
  7654. ${innerFunctionsSwitch.join('\n')}
  7655. }
  7656. }
  7657. var logProbabilities = state.product;
  7658. if (temperature !== 1 && isSampleI) {
  7659. for (var q = 0, nq = logProbabilities.weights.length; q < nq; q++) {
  7660. logProbabilities.weights[q] /= temperature;
  7661. }
  7662. }
  7663. var probs = softmax(logProbabilities);
  7664. var nextIndex = isSampleI ? sampleI(probs) : maxI(probs);
  7665. _i++;
  7666. if (nextIndex === 0) {
  7667. break;
  7668. }
  7669. if (_i >= maxPredictionLength) {
  7670. break;
  7671. }
  7672. output.push(nextIndex);
  7673. }
  7674. ${this.options.dataFormatter &&
  7675. typeof this.options.dataFormatter.formatDataOut === 'function'
  7676. ? 'return formatDataOut(input, output.slice(input.length).map(function(value) { return value - 1; }))'
  7677. : 'return output.slice(input.length).map(function(value) { return value - 1; })'};
  7678. function Matrix(rows, columns) {
  7679. this.rows = rows;
  7680. this.columns = columns;
  7681. this.weights = zeros(rows * columns);
  7682. }
  7683. ${zeros$1.toString()}
  7684. ${softmax.toString().replace('_1.Matrix', 'Matrix')}
  7685. ${randomFloat.toString()}
  7686. ${sampleI.toString()}
  7687. ${maxI.toString()}`;
  7688. // eslint-disable-next-line
  7689. return new Function('rawInput', 'isSampleI', 'temperature', cb ? cb(src) : src);
  7690. }
  7691. trainPattern(input, logErrorRate) {
  7692. const error = this.trainInput(input);
  7693. this.backpropagate(input);
  7694. this.adjustWeights();
  7695. if (logErrorRate) {
  7696. return error;
  7697. }
  7698. return 0;
  7699. }
  7700. }
  7701. function last(values) {
  7702. return values[values.length - 1];
  7703. }
  7704. class GRU extends RNN {
  7705. getHiddenLayer(hiddenSize, prevSize) {
  7706. return getGRUHiddenLayer(hiddenSize, prevSize);
  7707. }
  7708. getEquation(equation, inputMatrix, previousResult, hiddenLayer) {
  7709. return getGRUEquation(equation, inputMatrix, previousResult, hiddenLayer);
  7710. }
  7711. }
  7712. function getGRUHiddenLayer(hiddenSize, prevSize) {
  7713. return {
  7714. // update Gate
  7715. // wzxh
  7716. updateGateInputMatrix: new RandomMatrix(hiddenSize, prevSize, 0.08),
  7717. updateGateHiddenMatrix: new RandomMatrix(hiddenSize, hiddenSize, 0.08),
  7718. updateGateBias: new Matrix(hiddenSize, 1),
  7719. // reset Gate
  7720. // wrxh
  7721. resetGateInputMatrix: new RandomMatrix(hiddenSize, prevSize, 0.08),
  7722. resetGateHiddenMatrix: new RandomMatrix(hiddenSize, hiddenSize, 0.08),
  7723. resetGateBias: new Matrix(hiddenSize, 1),
  7724. // cell write parameters
  7725. // wcxh
  7726. cellWriteInputMatrix: new RandomMatrix(hiddenSize, prevSize, 0.08),
  7727. cellWriteHiddenMatrix: new RandomMatrix(hiddenSize, hiddenSize, 0.08),
  7728. cellWriteBias: new Matrix(hiddenSize, 1),
  7729. };
  7730. }
  7731. function getGRUEquation(equation, inputMatrix, previousResult, hiddenLayer) {
  7732. if (!hiddenLayer.updateGateInputMatrix ||
  7733. !hiddenLayer.updateGateHiddenMatrix ||
  7734. !hiddenLayer.updateGateBias ||
  7735. !hiddenLayer.resetGateInputMatrix ||
  7736. !hiddenLayer.resetGateHiddenMatrix ||
  7737. !hiddenLayer.resetGateBias ||
  7738. !hiddenLayer.cellWriteInputMatrix ||
  7739. !hiddenLayer.cellWriteHiddenMatrix ||
  7740. !hiddenLayer.cellWriteBias) {
  7741. throw new Error('hiddenLayer does not have expected properties');
  7742. }
  7743. const sigmoid = equation.sigmoid.bind(equation);
  7744. const add = equation.add.bind(equation);
  7745. const multiply = equation.multiply.bind(equation);
  7746. const multiplyElement = equation.multiplyElement.bind(equation);
  7747. const tanh = equation.tanh.bind(equation);
  7748. const allOnes = equation.allOnes.bind(equation);
  7749. const cloneNegative = equation.cloneNegative.bind(equation);
  7750. // update gate
  7751. const updateGate = sigmoid(add(add(multiply(hiddenLayer.updateGateInputMatrix, inputMatrix), multiply(hiddenLayer.updateGateHiddenMatrix, previousResult)), hiddenLayer.updateGateBias));
  7752. // reset gate
  7753. const resetGate = sigmoid(add(add(multiply(hiddenLayer.resetGateInputMatrix, inputMatrix), multiply(hiddenLayer.resetGateHiddenMatrix, previousResult)), hiddenLayer.resetGateBias));
  7754. // cell
  7755. const cell = tanh(add(add(multiply(hiddenLayer.cellWriteInputMatrix, inputMatrix), multiply(hiddenLayer.cellWriteHiddenMatrix, multiplyElement(resetGate, previousResult))), hiddenLayer.cellWriteBias));
  7756. // compute hidden state as gated, saturated cell activations
  7757. // negate updateGate
  7758. return add(multiplyElement(add(allOnes(updateGate.rows, updateGate.columns), cloneNegative(updateGate)), cell), multiplyElement(previousResult, updateGate));
  7759. }
  7760. class ArrayLookupTable {
  7761. constructor(data, prop) {
  7762. this.prop = prop;
  7763. this.length = 0;
  7764. this.table = {};
  7765. for (let i = 0; i < data.length; i++) {
  7766. const datum = data[i];
  7767. const ioValue = datum[prop];
  7768. for (let j = 0; j < ioValue.length; j++) {
  7769. const value = ioValue[j];
  7770. for (const p in value) {
  7771. if (!value.hasOwnProperty(p))
  7772. continue;
  7773. if (this.table.hasOwnProperty(p))
  7774. continue;
  7775. this.table[p] = this.length++;
  7776. }
  7777. }
  7778. }
  7779. }
  7780. }
  7781. const defaults = () => {
  7782. return {
  7783. ...defaults$1(),
  7784. inputSize: 1,
  7785. hiddenLayers: [20],
  7786. outputSize: 1,
  7787. inputRange: 0,
  7788. };
  7789. };
  7790. class RNNTimeStep extends RNN {
  7791. constructor(options = {}) {
  7792. super();
  7793. this.inputLookupLength = 0;
  7794. this.inputLookup = null;
  7795. this.outputLookup = null;
  7796. this.outputLookupLength = 0;
  7797. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  7798. // @ts-expect-error
  7799. this.model = Object.seal({
  7800. isInitialized: false,
  7801. hiddenLayers: [],
  7802. output: new Matrix(0, 0),
  7803. equations: [],
  7804. allMatrices: [],
  7805. equationConnections: [],
  7806. outputConnector: new RandomMatrix(0, 0, 0.08),
  7807. });
  7808. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  7809. // @ts-expect-error
  7810. this.options = defaults();
  7811. this.options = { ...this.options, ...options };
  7812. this.updateTrainingOptions({
  7813. ...trainDefaults,
  7814. ...options,
  7815. });
  7816. if (options.json) {
  7817. this.fromJSON(options.json);
  7818. }
  7819. }
  7820. createInputMatrix() {
  7821. throw new Error('Input Matrices do not exist on RNNTimeStep');
  7822. }
  7823. createOutputMatrices() {
  7824. const { outputSize } = this.options;
  7825. const lastHiddenSize = last(this.options.hiddenLayers);
  7826. // whd
  7827. const outputConnector = new RandomMatrix(outputSize, lastHiddenSize, 0.08);
  7828. // bd
  7829. const output = new RandomMatrix(outputSize, 1, 0.08);
  7830. return { output, outputConnector };
  7831. }
  7832. bindEquation() {
  7833. const { model, options } = this;
  7834. const { hiddenLayers, inputSize } = options;
  7835. const layers = model.hiddenLayers;
  7836. const equation = new Equation();
  7837. const outputs = [];
  7838. const equationConnection = model.equationConnections.length > 0
  7839. ? model.equationConnections[model.equationConnections.length - 1]
  7840. : this.initialLayerInputs;
  7841. // 0 index
  7842. let output = this.getEquation(equation, equation.input(new Matrix(inputSize, 1)), equationConnection[0], layers[0]);
  7843. outputs.push(output);
  7844. // 1+ indices
  7845. for (let i = 1, max = hiddenLayers.length; i < max; i++) {
  7846. output = this.getEquation(equation, output, equationConnection[i], layers[i]);
  7847. outputs.push(output);
  7848. }
  7849. model.equationConnections.push(outputs);
  7850. equation.add(equation.multiply(model.outputConnector, output), model.output);
  7851. model.equations.push(equation);
  7852. }
  7853. initialize() {
  7854. this.model = this.mapModel();
  7855. }
  7856. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  7857. // @ts-expect-error
  7858. mapModel() {
  7859. const allMatrices = [];
  7860. this.initialLayerInputs = this.options.hiddenLayers.map((size) => new Matrix(size, 1));
  7861. const hiddenLayers = this.createHiddenLayers();
  7862. for (let i = 0, max = hiddenLayers.length; i < max; i++) {
  7863. const hiddenMatrix = hiddenLayers[i];
  7864. for (const property in hiddenMatrix) {
  7865. if (!hiddenMatrix.hasOwnProperty(property))
  7866. continue;
  7867. allMatrices.push(hiddenMatrix[property]);
  7868. }
  7869. }
  7870. const { outputConnector, output } = this.createOutputMatrices();
  7871. allMatrices.push(outputConnector);
  7872. allMatrices.push(output);
  7873. return Object.seal({
  7874. isInitialized: true,
  7875. hiddenLayers,
  7876. output,
  7877. equations: [],
  7878. allMatrices,
  7879. equationConnections: [],
  7880. outputConnector,
  7881. });
  7882. }
  7883. backpropagate() {
  7884. for (let i = this.model.equations.length - 1; i > -1; i--) {
  7885. this.model.equations[i].backpropagate();
  7886. }
  7887. }
  7888. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  7889. // @ts-expect-error
  7890. run(rawInput) {
  7891. const shape = lookup.dataShape(rawInput).join(',');
  7892. switch (shape) {
  7893. case 'array,number':
  7894. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  7895. // @ts-expect-error
  7896. return this.runArray(rawInput);
  7897. case 'array,array,number':
  7898. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  7899. // @ts-expect-error
  7900. return this.runArrayOfArray(rawInput);
  7901. case 'object,number':
  7902. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  7903. // @ts-expect-error
  7904. return this.runObject(rawInput); // Backward compatibility, will be result of `unknown` and need casting. Better to just use net.runObject() directly
  7905. case 'array,object,number':
  7906. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  7907. // @ts-expect-error
  7908. return this.runArrayOfObject(rawInput);
  7909. default:
  7910. throw new Error(`Unrecognized data shape ${shape}`);
  7911. }
  7912. }
  7913. forecast(rawInput, count = 1) {
  7914. const shape = lookup.dataShape(rawInput).join(',');
  7915. switch (shape) {
  7916. case 'array,number':
  7917. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  7918. // @ts-expect-error
  7919. return this.forecastArray(rawInput, count);
  7920. case 'array,array,number':
  7921. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  7922. // @ts-expect-error
  7923. return this.forecastArrayOfArray(rawInput, count);
  7924. case 'object,number':
  7925. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  7926. // @ts-expect-error
  7927. return this.runObject(rawInput);
  7928. case 'array,object,number':
  7929. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  7930. // @ts-expect-error
  7931. return this.forecastArrayOfObject(rawInput, count);
  7932. default:
  7933. throw new Error(`Unrecognized data shape ${shape}`);
  7934. }
  7935. }
  7936. forecastArray(input, count = 1) {
  7937. this.checkRunnable();
  7938. const { model } = this;
  7939. const { equations } = model;
  7940. const length = input.length + count;
  7941. while (equations.length <= length) {
  7942. this.bindEquation();
  7943. }
  7944. let lastOutput;
  7945. let equationIndex = 0;
  7946. if (this.options.inputSize === 1) {
  7947. for (let i = 0; i < input.length; i++) {
  7948. lastOutput = equations[equationIndex++].runInput(Float32Array.from([input[i]]));
  7949. }
  7950. }
  7951. else {
  7952. for (let i = 0; i < input.length; i++) {
  7953. lastOutput = equations[equationIndex++].runInput(Float32Array.from([]));
  7954. }
  7955. }
  7956. if (!lastOutput) {
  7957. throw new Error('lastOutput not set');
  7958. }
  7959. const result = [lastOutput.weights[0]];
  7960. for (let i = 0, max = count - 1; i < max; i++) {
  7961. lastOutput = equations[equationIndex++].runInput(lastOutput.weights);
  7962. result.push(lastOutput.weights[0]);
  7963. }
  7964. this.end();
  7965. return Float32Array.from(result);
  7966. }
  7967. forecastArrayOfArray(input, count = 1) {
  7968. this.checkRunnable();
  7969. const { model } = this;
  7970. const { equations } = model;
  7971. const length = input.length + count;
  7972. while (equations.length <= length) {
  7973. this.bindEquation();
  7974. }
  7975. let lastOutput;
  7976. let equationIndex = 0;
  7977. for (let i = 0; i < input.length; i++) {
  7978. lastOutput = equations[equationIndex++].runInput(input[i]);
  7979. }
  7980. if (!lastOutput) {
  7981. throw new Error('lastOutput not set');
  7982. }
  7983. const result = [Float32Array.from(lastOutput.weights)];
  7984. for (let i = 0, max = count - 1; i < max; i++) {
  7985. lastOutput = equations[equationIndex++].runInput(lastOutput.weights);
  7986. result.push(Float32Array.from(lastOutput.weights.slice(0)));
  7987. }
  7988. this.end();
  7989. return result;
  7990. }
  7991. forecastArrayOfObject(input, count = 1) {
  7992. if (!this.inputLookup) {
  7993. throw new Error('this.inputLookup not set');
  7994. }
  7995. if (!this.outputLookup) {
  7996. throw new Error('this.outputLookup not set');
  7997. }
  7998. const formattedData = input.map((value) => lookup.toArray(this.inputLookup, value, this.inputLookupLength));
  7999. return this.forecastArrayOfArray(formattedData, count).map((value) => lookup.toObject(this.outputLookup, value));
  8000. }
  8001. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  8002. // @ts-expect-error
  8003. train(data, trainOpts = {}) {
  8004. this.trainOpts = trainOpts = {
  8005. ...trainDefaults$1,
  8006. ...trainOpts,
  8007. };
  8008. // Don't destructure here because this.setSize() can reset this.options.
  8009. if (this.options.inputSize === 1 && this.options.outputSize === 1) {
  8010. this.setSize(data);
  8011. }
  8012. this.verifySize();
  8013. const formattedData = this.formatData(data);
  8014. let error = Infinity;
  8015. let i;
  8016. this.verifyIsInitialized();
  8017. const { iterations, errorThresh, logPeriod, callback, callbackPeriod, } = this.trainOpts;
  8018. const log = trainOpts.log === true ? console.log : trainOpts.log;
  8019. for (i = 0; i < iterations && error > errorThresh; i++) {
  8020. let sum = 0;
  8021. for (let j = 0; j < formattedData.length; j++) {
  8022. const err = this.trainPattern(formattedData[j], true);
  8023. sum += err;
  8024. }
  8025. error = sum / formattedData.length;
  8026. if (isNaN(error))
  8027. throw new Error('Network error rate is unexpected NaN, check network configurations and try again. Most probably input format is not correct or training data is not enough. ');
  8028. if (log && i % logPeriod === 0) {
  8029. log(`iterations: ${i}, training error: ${error}`);
  8030. }
  8031. if (callback && i % callbackPeriod === 0) {
  8032. callback({ error, iterations: i });
  8033. }
  8034. }
  8035. return {
  8036. error,
  8037. iterations: i,
  8038. };
  8039. }
  8040. trainArrayOfArray(input) {
  8041. if (input.length < 2) {
  8042. throw new Error('input must be an array of 2 or more');
  8043. }
  8044. const { equations } = this.model;
  8045. while (equations.length < input.length) {
  8046. this.bindEquation();
  8047. }
  8048. let errorSum = 0;
  8049. for (let i = 0, max = input.length - 1; i < max; i++) {
  8050. errorSum += equations[i].predictTarget(input[i], input[i + 1]);
  8051. }
  8052. this.end();
  8053. return errorSum / input.length;
  8054. }
  8055. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  8056. // @ts-expect-error
  8057. trainPattern(input, logErrorRate) {
  8058. const error = this.trainArrayOfArray(input);
  8059. this.backpropagate();
  8060. this.adjustWeights();
  8061. if (logErrorRate) {
  8062. return error;
  8063. }
  8064. return 0;
  8065. }
  8066. setSize(data) {
  8067. let size = 0;
  8068. const dataShape = lookup.dataShape(data).join(',');
  8069. switch (dataShape) {
  8070. case 'array,array,number':
  8071. case 'array,object,number':
  8072. case 'array,datum,array,number':
  8073. case 'array,datum,object,number':
  8074. size = 1;
  8075. // probably 1
  8076. break;
  8077. case 'array,array,array,number':
  8078. size = data[0][0].length;
  8079. break;
  8080. case 'array,array,object,number':
  8081. // inputs and outputs should match
  8082. size = Object.keys(lookup.toTable2D(data)).length;
  8083. break;
  8084. case 'array,datum,array,array,number':
  8085. size = data[0].input[0].length;
  8086. break;
  8087. case 'array,datum,array,object,number':
  8088. size = Object.keys(lookup.toInputTable2D(data)).length;
  8089. break;
  8090. default:
  8091. throw new Error('unknown data shape or configuration');
  8092. }
  8093. this.options = Object.seal({
  8094. ...this.options,
  8095. inputSize: size,
  8096. outputSize: size,
  8097. });
  8098. }
  8099. verifySize() {
  8100. if (this.options.inputSize || this.options.outputSize) {
  8101. if (this.options.inputSize !== this.options.outputSize) {
  8102. throw new Error('manually set inputSize and outputSize mismatch');
  8103. }
  8104. }
  8105. }
  8106. runArray(input) {
  8107. this.checkRunnable();
  8108. const { equations } = this.model;
  8109. while (equations.length <= input.length) {
  8110. this.bindEquation();
  8111. }
  8112. let lastOutput;
  8113. for (let i = 0; i < input.length; i++) {
  8114. lastOutput = equations[i].runInput(new Float32Array([input[i]]));
  8115. }
  8116. this.end();
  8117. return lastOutput.weights[0];
  8118. }
  8119. runArrayOfArray(input) {
  8120. this.checkRunnable();
  8121. const { model } = this;
  8122. const { equations } = model;
  8123. while (equations.length <= input.length) {
  8124. this.bindEquation();
  8125. }
  8126. let lastOutput;
  8127. for (let i = 0; i < input.length; i++) {
  8128. const outputMatrix = equations[i].runInput(input[i]);
  8129. lastOutput = outputMatrix.weights;
  8130. }
  8131. this.end();
  8132. return lastOutput !== null && lastOutput !== void 0 ? lastOutput : Float32Array.from([]);
  8133. }
  8134. runObject(input) {
  8135. if (!this.inputLookup) {
  8136. throw new Error('this.inputLookup not set');
  8137. }
  8138. if (!this.outputLookup) {
  8139. throw new Error('this.outputLookup not set');
  8140. }
  8141. if (!this.outputLookupLength) {
  8142. throw new Error('this.outputLookupLength not set');
  8143. }
  8144. if (this.inputLookup === this.outputLookup) {
  8145. const inputArray = lookup.toArrayShort(this.inputLookup, input);
  8146. return lookup.toObjectPartial(this.outputLookup, this.forecastArray(inputArray, this.outputLookupLength - inputArray.length), inputArray.length);
  8147. }
  8148. return lookup.toObject(this.outputLookup, this.forecastArray(lookup.toArray(this.inputLookup, input, this.inputLookupLength), this.outputLookupLength));
  8149. }
  8150. runArrayOfObject(input) {
  8151. if (this.inputLookup === null) {
  8152. throw new Error('this.inputLookup not set');
  8153. }
  8154. if (this.outputLookup === null) {
  8155. throw new Error('this.outputLookup not set');
  8156. }
  8157. const formattedInput = input.map((value) => lookup.toArray(this.inputLookup, value, this.inputLookupLength));
  8158. return this.forecastArrayOfArray(formattedInput, 1).map((value) => lookup.toObject(this.outputLookup, value))[0];
  8159. }
  8160. runArrayOfObjectOfArray(input) {
  8161. if (!this.inputLookup) {
  8162. throw new Error('this.inputLookup not set');
  8163. }
  8164. if (!this.outputLookup) {
  8165. throw new Error('this.outputLookup not set');
  8166. }
  8167. return lookup.toObject(this.outputLookup, this.runArrayOfArray(lookup.toArrays(this.inputLookup, input, this.inputLookupLength)));
  8168. }
  8169. end() {
  8170. this.model.equations[this.model.equations.length - 1].runInput(new Float32Array(this.options.outputSize));
  8171. }
  8172. requireInputOutputOfOne() {
  8173. if (this.options.inputSize !== 1) {
  8174. throw new Error('inputSize must be 1 for this data size');
  8175. }
  8176. if (this.options.outputSize !== 1) {
  8177. throw new Error('outputSize must be 1 for this data size');
  8178. }
  8179. }
  8180. // Handles data shape of 'array,number'
  8181. formatArray(data) {
  8182. const result = [];
  8183. this.requireInputOutputOfOne();
  8184. for (let i = 0; i < data.length; i++) {
  8185. result.push(Float32Array.from([data[i]]));
  8186. }
  8187. return [result];
  8188. }
  8189. // Handles data shape of 'array,array,number'
  8190. formatArrayOfArray(data) {
  8191. const result = [];
  8192. const { inputSize, outputSize } = this.options;
  8193. if (inputSize === 1 && outputSize === 1) {
  8194. for (let i = 0; i < data.length; i++) {
  8195. result.push(arrayToFloat32Arrays(data[i]));
  8196. }
  8197. return result;
  8198. }
  8199. if (inputSize !== data[0].length) {
  8200. throw new Error('inputSize must match data input size');
  8201. }
  8202. if (outputSize !== data[0].length) {
  8203. throw new Error('outputSize must match data output size');
  8204. }
  8205. for (let i = 0; i < data.length; i++) {
  8206. result.push(Float32Array.from(data[i]));
  8207. }
  8208. return [result];
  8209. }
  8210. // Handles data shape of 'array,object,number'
  8211. formatArrayOfObject(data) {
  8212. this.requireInputOutputOfOne();
  8213. if (!this.inputLookup) {
  8214. const lookupTable = new LookupTable(data);
  8215. this.inputLookup = this.outputLookup = lookupTable.table;
  8216. this.inputLookupLength = this.outputLookupLength = lookupTable.length;
  8217. }
  8218. const result = [];
  8219. for (let i = 0; i < data.length; i++) {
  8220. result.push(objectToFloat32Arrays(data[i]));
  8221. }
  8222. return result;
  8223. }
  8224. // Handles data shape of 'array,object,number' when this.options.inputSize > 1
  8225. formatArrayOfObjectMulti(data) {
  8226. if (!this.inputLookup) {
  8227. const lookupTable = new LookupTable(data);
  8228. this.inputLookup = this.outputLookup = lookupTable.table;
  8229. this.inputLookupLength = this.outputLookupLength = lookupTable.length;
  8230. }
  8231. const result = [];
  8232. for (let i = 0; i < data.length; i++) {
  8233. result.push([
  8234. objectToFloat32Array(data[i], this.inputLookup, this.inputLookupLength),
  8235. ]);
  8236. }
  8237. return result;
  8238. }
  8239. // Handles data shape of 'array,datum,array,number'
  8240. formatArrayOfDatumOfArray(data) {
  8241. const result = [];
  8242. this.requireInputOutputOfOne();
  8243. for (let i = 0; i < data.length; i++) {
  8244. const datum = data[i];
  8245. result.push(inputOutputArrayToFloat32Arrays(datum.input, datum.output));
  8246. }
  8247. return result;
  8248. }
  8249. // Handles data shape of 'array,datum,object,number'
  8250. formatArrayOfDatumOfObject(data) {
  8251. this.requireInputOutputOfOne();
  8252. if (!this.inputLookup) {
  8253. const inputLookup = new LookupTable(data, 'input');
  8254. this.inputLookup = inputLookup.table;
  8255. this.inputLookupLength = inputLookup.length;
  8256. }
  8257. if (!this.outputLookup) {
  8258. const outputLookup = new LookupTable(data, 'output');
  8259. this.outputLookup = outputLookup.table;
  8260. this.outputLookupLength = outputLookup.length;
  8261. }
  8262. const result = [];
  8263. for (let i = 0; i < data.length; i++) {
  8264. const datum = data[i];
  8265. result.push(inputOutputObjectToFloat32Arrays(datum.input, datum.output));
  8266. }
  8267. return result;
  8268. }
  8269. // Handles data shape of 'array,array,array,number'
  8270. formatArrayOfArrayOfArray(data) {
  8271. const result = [];
  8272. for (let i = 0; i < data.length; i++) {
  8273. result.push(arraysToFloat32Arrays(data[i]));
  8274. }
  8275. return result;
  8276. }
  8277. // Handles data shape of 'array,array,object,number'
  8278. formatArrayOfArrayOfObject(data) {
  8279. if (!this.inputLookup) {
  8280. const lookupTable = new LookupTable(data);
  8281. this.inputLookup = this.outputLookup = lookupTable.table;
  8282. this.inputLookupLength = this.outputLookupLength = lookupTable.length;
  8283. }
  8284. const result = [];
  8285. for (let i = 0; i < data.length; i++) {
  8286. const array = [];
  8287. for (let j = 0; j < data[i].length; j++) {
  8288. array.push(objectToFloat32Array(data[i][j], this.inputLookup, this.inputLookupLength));
  8289. }
  8290. result.push(array);
  8291. }
  8292. return result;
  8293. }
  8294. // Handles data shape of 'array,datum,array,array,number'
  8295. formatArrayOfDatumOfArrayOfArray(data) {
  8296. const result = [];
  8297. const { inputSize, outputSize } = this.options;
  8298. if (inputSize !== data[0].input[0].length) {
  8299. throw new Error('inputSize must match data input size');
  8300. }
  8301. if (outputSize !== data[0].output[0].length) {
  8302. throw new Error('outputSize must match data output size');
  8303. }
  8304. for (let i = 0; i < data.length; i++) {
  8305. const datum = data[i];
  8306. result.push(inputOutputArraysToFloat32Arrays(datum.input, datum.output));
  8307. }
  8308. return result;
  8309. }
  8310. // 'Handles data shape of array,datum,array,object,number'
  8311. formatArrayOfDatumOfArrayOfObject(data) {
  8312. if (!this.inputLookup) {
  8313. const inputLookup = new ArrayLookupTable(data, 'input');
  8314. this.inputLookup = inputLookup.table;
  8315. this.inputLookupLength = inputLookup.length;
  8316. }
  8317. if (!this.outputLookup) {
  8318. const outputLookup = new ArrayLookupTable(data, 'output');
  8319. this.outputLookup = outputLookup.table;
  8320. this.outputLookupLength = outputLookup.length;
  8321. }
  8322. if (!this.outputLookupLength) {
  8323. throw new Error('this.outputLookupLength not set to usable number');
  8324. }
  8325. const result = [];
  8326. for (let i = 0; i < data.length; i++) {
  8327. const datum = data[i];
  8328. result.push(inputOutputObjectsToFloat32Arrays(datum.input, datum.output, this.inputLookup, this.outputLookup, this.inputLookupLength, this.outputLookupLength));
  8329. }
  8330. return result;
  8331. }
  8332. formatData(data) {
  8333. const dataShape = lookup.dataShape(data).join(',');
  8334. switch (dataShape) {
  8335. case 'array,number':
  8336. return this.formatArray(data);
  8337. case 'array,array,number':
  8338. return this.formatArrayOfArray(data);
  8339. case 'array,object,number':
  8340. if (this.options.inputSize === 1) {
  8341. return this.formatArrayOfObject(data);
  8342. }
  8343. else {
  8344. return this.formatArrayOfObjectMulti(data);
  8345. }
  8346. case 'array,datum,array,number':
  8347. return this.formatArrayOfDatumOfArray(data);
  8348. case 'array,datum,object,number':
  8349. return this.formatArrayOfDatumOfObject(data);
  8350. case 'array,array,array,number':
  8351. return this.formatArrayOfArrayOfArray(data);
  8352. case 'array,array,object,number':
  8353. return this.formatArrayOfArrayOfObject(data);
  8354. case 'array,datum,array,array,number':
  8355. return this.formatArrayOfDatumOfArrayOfArray(data);
  8356. case 'array,datum,array,object,number':
  8357. return this.formatArrayOfDatumOfArrayOfObject(data);
  8358. default:
  8359. throw new Error('unknown data shape or configuration');
  8360. }
  8361. }
  8362. test(data) {
  8363. // for classification problems
  8364. const misclasses = [];
  8365. // run each pattern through the trained network and collect
  8366. // error and misclassification statistics
  8367. let errorSum = 0;
  8368. const formattedData = this.formatData(data);
  8369. for (let i = 0; i < formattedData.length; i++) {
  8370. const input = formattedData[i];
  8371. const output = this.run(input.splice(0, input.length - 1));
  8372. const target = input[input.length - 1];
  8373. let errors = 0;
  8374. let errorCount = 0;
  8375. for (let j = 0; j < output.length; j++) {
  8376. errorCount++;
  8377. const error = target[j] - output[j];
  8378. // mse
  8379. errors += error * error;
  8380. }
  8381. errorSum += errors / errorCount;
  8382. const errorsAbs = Math.abs(errors);
  8383. if (errorsAbs > this.trainOpts.errorThresh) {
  8384. const misclass = data[i];
  8385. misclasses.push({
  8386. value: misclass,
  8387. actual: output,
  8388. });
  8389. }
  8390. }
  8391. return {
  8392. error: errorSum / formattedData.length,
  8393. misclasses,
  8394. total: formattedData.length,
  8395. };
  8396. }
  8397. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  8398. // @ts-expect-error
  8399. addFormat(value) {
  8400. var _a, _b, _c, _d, _e, _f;
  8401. const dataShape = lookup.dataShape(value).join(',');
  8402. switch (dataShape) {
  8403. case 'array,array,number':
  8404. case 'datum,array,array,number':
  8405. case 'array,number':
  8406. case 'datum,array,number':
  8407. return;
  8408. case 'datum,object,number': {
  8409. this.inputLookup = lookup.addKeys(value.input, (_a = this.inputLookup) !== null && _a !== void 0 ? _a : {});
  8410. if (this.inputLookup) {
  8411. this.inputLookupLength = Object.keys(this.inputLookup).length;
  8412. }
  8413. this.outputLookup = lookup.addKeys(value.output, (_b = this.outputLookup) !== null && _b !== void 0 ? _b : {});
  8414. if (this.outputLookup) {
  8415. this.outputLookupLength = Object.keys(this.outputLookup).length;
  8416. }
  8417. break;
  8418. }
  8419. case 'object,number': {
  8420. this.inputLookup = this.outputLookup = lookup.addKeys(value, (_c = this.inputLookup) !== null && _c !== void 0 ? _c : {});
  8421. if (this.inputLookup) {
  8422. this.inputLookupLength = this.outputLookupLength = Object.keys(this.inputLookup).length;
  8423. }
  8424. break;
  8425. }
  8426. case 'array,object,number': {
  8427. const typedValue = value;
  8428. for (let i = 0; i < typedValue.length; i++) {
  8429. this.inputLookup = this.outputLookup = lookup.addKeys(typedValue[i], (_d = this.inputLookup) !== null && _d !== void 0 ? _d : {});
  8430. if (this.inputLookup) {
  8431. this.inputLookupLength = this.outputLookupLength = Object.keys(this.inputLookup).length;
  8432. }
  8433. }
  8434. break;
  8435. }
  8436. case 'datum,array,object,number': {
  8437. const typedValue = value;
  8438. const typedInput = typedValue.input;
  8439. for (let i = 0; i < typedInput.length; i++) {
  8440. this.inputLookup = lookup.addKeys(typedInput[i], (_e = this.inputLookup) !== null && _e !== void 0 ? _e : {});
  8441. if (this.inputLookup) {
  8442. this.inputLookupLength = Object.keys(this.inputLookup).length;
  8443. }
  8444. }
  8445. const typedOutput = typedValue.output;
  8446. for (let i = 0; i < typedOutput.length; i++) {
  8447. this.outputLookup = lookup.addKeys(typedOutput[i], (_f = this.outputLookup) !== null && _f !== void 0 ? _f : {});
  8448. if (this.outputLookup) {
  8449. this.outputLookupLength = Object.keys(this.outputLookup).length;
  8450. }
  8451. }
  8452. break;
  8453. }
  8454. default:
  8455. throw new Error('unknown data shape or configuration');
  8456. }
  8457. }
  8458. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  8459. // @ts-expect-error
  8460. toJSON() {
  8461. if (!this.model) {
  8462. this.initialize();
  8463. }
  8464. const { model } = this;
  8465. const options = { ...this.options, ...defaults$1 };
  8466. return {
  8467. type: this.constructor.name,
  8468. options,
  8469. hiddenLayers: model.hiddenLayers.map((hiddenLayer) => {
  8470. const layers = {};
  8471. for (const p in hiddenLayer) {
  8472. if (!hiddenLayer.hasOwnProperty(p))
  8473. continue;
  8474. layers[p] = hiddenLayer[p].toJSON();
  8475. }
  8476. return layers;
  8477. }),
  8478. outputConnector: model.outputConnector.toJSON(),
  8479. output: model.output.toJSON(),
  8480. inputLookup: this.inputLookup,
  8481. inputLookupLength: this.inputLookupLength,
  8482. outputLookup: this.outputLookup,
  8483. outputLookupLength: this.outputLookupLength,
  8484. };
  8485. }
  8486. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  8487. // @ts-expect-error
  8488. fromJSON(json) {
  8489. const { options } = json;
  8490. const allMatrices = [];
  8491. const hiddenLayers = [];
  8492. // backward compatibility for hiddenSizes
  8493. json.hiddenLayers.forEach((hiddenLayer) => {
  8494. const layers = {};
  8495. for (const p in hiddenLayer) {
  8496. layers[p] = Matrix.fromJSON(hiddenLayer[p]);
  8497. allMatrices.push(layers[p]);
  8498. }
  8499. hiddenLayers.push(layers);
  8500. });
  8501. const outputConnector = Matrix.fromJSON(json.outputConnector);
  8502. allMatrices.push(outputConnector);
  8503. const output = Matrix.fromJSON(json.output);
  8504. allMatrices.push(output);
  8505. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  8506. // @ts-expect-error
  8507. this.options = { ...defaults(), ...options };
  8508. this.inputLookup = json.inputLookup;
  8509. this.inputLookupLength = json.inputLookupLength;
  8510. this.outputLookup = json.outputLookup;
  8511. this.outputLookupLength = json.outputLookupLength;
  8512. this.model = Object.seal({
  8513. isInitialized: true,
  8514. hiddenLayers,
  8515. output,
  8516. allMatrices,
  8517. outputConnector,
  8518. equations: [],
  8519. equationConnections: [],
  8520. });
  8521. this.initialLayerInputs = options.hiddenLayers.map((size) => new Matrix(size, 1));
  8522. this.bindEquation();
  8523. return this;
  8524. }
  8525. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  8526. // @ts-expect-error
  8527. toFunction(cb) {
  8528. const { model, inputLookup, inputLookupLength, outputLookup, outputLookupLength, } = this;
  8529. const { inputSize } = this.options;
  8530. const { equations } = model;
  8531. const equation = equations[1];
  8532. const { states } = equation;
  8533. const jsonString = JSON.stringify(this.toJSON());
  8534. function previousConnectionIndex(m) {
  8535. const connection = model.equationConnections[0];
  8536. const { states } = equations[0];
  8537. for (let i = 0, max = states.length; i < max; i++) {
  8538. if (states[i].product === m) {
  8539. return i;
  8540. }
  8541. }
  8542. return connection.indexOf(m);
  8543. }
  8544. function matrixOrigin(m, stateIndex) {
  8545. for (let i = 0, max = states.length; i < max; i++) {
  8546. const state = states[i];
  8547. if (i === stateIndex) {
  8548. const j = previousConnectionIndex(m);
  8549. switch (m) {
  8550. case state.left:
  8551. if (j > -1) {
  8552. return `typeof prevStates[${j}] === 'object' ? prevStates[${j}].product : new Matrix(${m.rows}, ${m.columns})`;
  8553. }
  8554. // eslint-disable-next-line no-fallthrough
  8555. case state.right:
  8556. if (j > -1) {
  8557. return `typeof prevStates[${j}] === 'object' ? prevStates[${j}].product : new Matrix(${m.rows}, ${m.columns})`;
  8558. }
  8559. // eslint-disable-next-line no-fallthrough
  8560. case state.product:
  8561. return `new Matrix(${m.rows}, ${m.columns})`;
  8562. default:
  8563. throw Error('unknown state');
  8564. }
  8565. }
  8566. if (m === state.product)
  8567. return `states[${i}].product`;
  8568. if (m === state.right)
  8569. return `states[${i}].right`;
  8570. if (m === state.left)
  8571. return `states[${i}].left`;
  8572. }
  8573. return '';
  8574. }
  8575. function matrixToString(m, stateIndex) {
  8576. if (!m || !m.rows || !m.columns)
  8577. return 'null';
  8578. if (m === model.outputConnector)
  8579. return `json.outputConnector`;
  8580. if (m === model.output)
  8581. return `json.output`;
  8582. for (let i = 0, max = model.hiddenLayers.length; i < max; i++) {
  8583. const hiddenLayer = model.hiddenLayers[i];
  8584. for (const p in hiddenLayer) {
  8585. if (!hiddenLayer.hasOwnProperty(p))
  8586. continue;
  8587. if (hiddenLayer[p] !== m)
  8588. continue;
  8589. return `json.hiddenLayers[${i}].${p}`;
  8590. }
  8591. }
  8592. return matrixOrigin(m, stateIndex);
  8593. }
  8594. function formatInputData() {
  8595. if (!inputLookup)
  8596. return '';
  8597. if (inputSize === 1) {
  8598. if (inputLookup === outputLookup) {
  8599. return `function lookupInput(input) {
  8600. var table = ${JSON.stringify(inputLookup)};
  8601. var result = [];
  8602. for (var p in table) {
  8603. if (!input.hasOwnProperty(p)) break;
  8604. result.push(Float32Array.from([input[p]]));
  8605. }
  8606. return result;
  8607. }`;
  8608. }
  8609. return `function lookupInput(input) {
  8610. var table = ${JSON.stringify(inputLookup)};
  8611. var result = [];
  8612. for (var p in table) {
  8613. result.push(Float32Array.from([input[p]]));
  8614. }
  8615. return result;
  8616. }`;
  8617. }
  8618. return `function lookupInput(rawInputs) {
  8619. var table = ${JSON.stringify(inputLookup)};
  8620. var result = [];
  8621. for (var i = 0; i < rawInputs.length; i++) {
  8622. var rawInput = rawInputs[i];
  8623. var input = new Float32Array(${inputLookupLength});
  8624. for (var p in table) {
  8625. input[table[p]] = rawInput.hasOwnProperty(p) ? rawInput[p] : 0;
  8626. }
  8627. result.push(input);
  8628. }
  8629. return result;
  8630. }`;
  8631. }
  8632. function formatOutputData() {
  8633. if (!outputLookup)
  8634. return '';
  8635. if (inputSize === 1) {
  8636. if (inputLookup === outputLookup) {
  8637. return `function lookupOutputPartial(output, input) {
  8638. var table = ${JSON.stringify(outputLookup)};
  8639. var offset = input.length;
  8640. var result = {};
  8641. var i = 0;
  8642. for (var p in table) {
  8643. if (i++ < offset) continue;
  8644. result[p] = output[table[p] - offset][0];
  8645. }
  8646. return result;
  8647. }`;
  8648. }
  8649. return `function lookupOutput(output) {
  8650. var table = ${JSON.stringify(outputLookup)};
  8651. var result = {};
  8652. for (var p in table) {
  8653. result[p] = output[table[p]][0];
  8654. }
  8655. return result;
  8656. }`;
  8657. }
  8658. return `function lookupOutput(output) {
  8659. var table = ${JSON.stringify(outputLookup)};
  8660. var result = {};
  8661. for (var p in table) {
  8662. result[p] = output[table[p]];
  8663. }
  8664. return result;
  8665. }`;
  8666. }
  8667. function toInner(fnString) {
  8668. // crude, but should be sufficient for now
  8669. // function() { body }
  8670. // crude, but should be sufficient for now
  8671. // function() { body }
  8672. const fnParts = fnString.toString().split('{');
  8673. fnParts.shift();
  8674. // body }
  8675. const fnBodyString = fnParts.join('{');
  8676. const fnBodyParts = fnBodyString.split('}');
  8677. fnBodyParts.pop();
  8678. // body
  8679. return fnBodyParts
  8680. .join('}')
  8681. .split('\n')
  8682. .join('\n ')
  8683. .replace('product.deltas[i] = 0;', '')
  8684. .replace('product.deltas[column] = 0;', '')
  8685. .replace('left.deltas[leftIndex] = 0;', '')
  8686. .replace('right.deltas[rightIndex] = 0;', '')
  8687. .replace('product.deltas = left.deltas.slice(0);', '');
  8688. }
  8689. function fileName(fnName) {
  8690. return `src/recurrent/matrix/${fnName.replace(/[A-Z]/g, function (value) {
  8691. return `-${value.toLowerCase()}`;
  8692. })}.js`;
  8693. }
  8694. const statesRaw = [];
  8695. const usedFunctionNames = {};
  8696. const innerFunctionsSwitch = [];
  8697. for (let i = 0, max = states.length; i < max; i++) {
  8698. const state = states[i];
  8699. statesRaw.push(`states[${i}] = {
  8700. name: '${state.forwardFn.name}',
  8701. left: ${state.left ? matrixToString(state.left, i) : 'undefined'},
  8702. right: ${state.right ? matrixToString(state.right, i) : 'undefined'},
  8703. product: ${matrixToString(state.product, i)}
  8704. }`);
  8705. const fnName = state.forwardFn.name;
  8706. if (!usedFunctionNames[fnName]) {
  8707. usedFunctionNames[fnName] = true;
  8708. if (state.name === 'input') {
  8709. innerFunctionsSwitch.push(`case '${fnName}':`);
  8710. innerFunctionsSwitch.push(inputLookup && inputSize === 1
  8711. ? 'product.weights = _i < input.length ? input[_i]: prevStates[prevStates.length - 1].product.weights;'
  8712. : inputSize === 1
  8713. ? 'product.weights = [input[_i]];'
  8714. : 'product.weights = input[_i];');
  8715. innerFunctionsSwitch.push('break;');
  8716. }
  8717. else {
  8718. innerFunctionsSwitch.push(` case '${fnName}':${fnName !== 'forwardFn'
  8719. ? ` //compiled from ${fileName(fnName)}`
  8720. : ''}
  8721. ${toInner(state.forwardFn.toString())}
  8722. break;`);
  8723. }
  8724. }
  8725. }
  8726. const forceForecast = inputSize === 1 && this.outputLookup;
  8727. const src = `
  8728. var input = ${this.inputLookup ? 'lookupInput(rawInput)' : 'rawInput'};
  8729. var json = ${jsonString};
  8730. var output = [];
  8731. var states = [];
  8732. var prevStates;
  8733. var state;
  8734. var max = ${forceForecast
  8735. ? inputLookup === outputLookup
  8736. ? inputLookupLength
  8737. : `input.length + ${outputLookupLength - 1}`
  8738. : 'input.length'};
  8739. for (var _i = 0; _i < max; _i++) {
  8740. prevStates = states;
  8741. states = [];
  8742. ${statesRaw.join(';\n ')};
  8743. for (var stateIndex = 0, stateMax = ${statesRaw.length}; stateIndex < stateMax; stateIndex++) {
  8744. state = states[stateIndex];
  8745. var product = state.product;
  8746. var left = state.left;
  8747. var right = state.right;
  8748. switch (state.name) {
  8749. ${innerFunctionsSwitch.join('\n')}
  8750. }
  8751. }
  8752. ${inputSize === 1 && inputLookup
  8753. ? 'if (_i >= input.length - 1) { output.push(state.product.weights); }'
  8754. : 'output = state.product.weights;'}
  8755. }
  8756. ${outputLookup
  8757. ? outputLookup === inputLookup
  8758. ? 'return lookupOutputPartial(output, input)'
  8759. : 'return lookupOutput(output)'
  8760. : inputSize === 1
  8761. ? 'return output[0]'
  8762. : 'return output'};
  8763. ${formatInputData()}
  8764. ${formatOutputData()}
  8765. function Matrix(rows, columns) {
  8766. this.rows = rows;
  8767. this.columns = columns;
  8768. this.weights = zeros(rows * columns);
  8769. }
  8770. ${zeros$1.toString()}
  8771. ${softmax.toString().replace('_2.default', 'Matrix')}
  8772. ${randomFloat.toString()}
  8773. ${sampleI.toString()}
  8774. ${maxI.toString()}`;
  8775. // eslint-disable-next-line
  8776. return new Function('rawInput', cb ? cb(src) : src);
  8777. }
  8778. }
  8779. const trainDefaults = { ...trainDefaults$1 };
  8780. class GRUTimeStep extends RNNTimeStep {
  8781. getHiddenLayer(hiddenSize, prevSize) {
  8782. return getGRUHiddenLayer(hiddenSize, prevSize);
  8783. }
  8784. getEquation(equation, inputMatrix, previousResult, hiddenLayer) {
  8785. return getGRUEquation(equation, inputMatrix, previousResult, hiddenLayer);
  8786. }
  8787. }
  8788. class LSTM extends RNN {
  8789. getHiddenLayer(hiddenSize, prevSize) {
  8790. return getHiddenLSTMLayer(hiddenSize, prevSize);
  8791. }
  8792. getEquation(equation, inputMatrix, previousResult, hiddenLayer) {
  8793. return getLSTMEquation(equation, inputMatrix, previousResult, hiddenLayer);
  8794. }
  8795. }
  8796. function getHiddenLSTMLayer(hiddenSize, prevSize) {
  8797. return {
  8798. // gates parameters
  8799. // wix
  8800. inputMatrix: new RandomMatrix(hiddenSize, prevSize, 0.08),
  8801. inputHidden: new RandomMatrix(hiddenSize, hiddenSize, 0.08),
  8802. inputBias: new Matrix(hiddenSize, 1),
  8803. // wfx
  8804. forgetMatrix: new RandomMatrix(hiddenSize, prevSize, 0.08),
  8805. forgetHidden: new RandomMatrix(hiddenSize, hiddenSize, 0.08),
  8806. forgetBias: new Matrix(hiddenSize, 1),
  8807. // wox
  8808. outputMatrix: new RandomMatrix(hiddenSize, prevSize, 0.08),
  8809. outputHidden: new RandomMatrix(hiddenSize, hiddenSize, 0.08),
  8810. outputBias: new Matrix(hiddenSize, 1),
  8811. // cell write params
  8812. // wcx
  8813. cellActivationMatrix: new RandomMatrix(hiddenSize, prevSize, 0.08),
  8814. cellActivationHidden: new RandomMatrix(hiddenSize, hiddenSize, 0.08),
  8815. cellActivationBias: new Matrix(hiddenSize, 1),
  8816. };
  8817. }
  8818. function getLSTMEquation(equation, inputMatrix, previousResult, hiddenLayer) {
  8819. if (!hiddenLayer.inputMatrix ||
  8820. !hiddenLayer.inputHidden ||
  8821. !hiddenLayer.inputBias ||
  8822. !hiddenLayer.forgetMatrix ||
  8823. !hiddenLayer.forgetHidden ||
  8824. !hiddenLayer.forgetBias ||
  8825. !hiddenLayer.outputMatrix ||
  8826. !hiddenLayer.outputHidden ||
  8827. !hiddenLayer.outputBias ||
  8828. !hiddenLayer.cellActivationMatrix ||
  8829. !hiddenLayer.cellActivationHidden ||
  8830. !hiddenLayer.cellActivationBias) {
  8831. throw new Error('hiddenLayer does not have expected properties');
  8832. }
  8833. const sigmoid = equation.sigmoid.bind(equation);
  8834. const add = equation.add.bind(equation);
  8835. const multiply = equation.multiply.bind(equation);
  8836. const multiplyElement = equation.multiplyElement.bind(equation);
  8837. const tanh = equation.tanh.bind(equation);
  8838. const inputGate = sigmoid(add(add(multiply(hiddenLayer.inputMatrix, inputMatrix), multiply(hiddenLayer.inputHidden, previousResult)), hiddenLayer.inputBias));
  8839. const forgetGate = sigmoid(add(add(multiply(hiddenLayer.forgetMatrix, inputMatrix), multiply(hiddenLayer.forgetHidden, previousResult)), hiddenLayer.forgetBias));
  8840. // output gate
  8841. const outputGate = sigmoid(add(add(multiply(hiddenLayer.outputMatrix, inputMatrix), multiply(hiddenLayer.outputHidden, previousResult)), hiddenLayer.outputBias));
  8842. // write operation on cells
  8843. const cellWrite = tanh(add(add(multiply(hiddenLayer.cellActivationMatrix, inputMatrix), multiply(hiddenLayer.cellActivationHidden, previousResult)), hiddenLayer.cellActivationBias));
  8844. // compute new cell activation
  8845. const retainCell = multiplyElement(forgetGate, previousResult); // what do we keep from cell
  8846. const writeCell = multiplyElement(inputGate, cellWrite); // what do we write to cell
  8847. const cell = add(retainCell, writeCell); // new cell contents
  8848. // compute hidden state as gated, saturated cell activations
  8849. return multiplyElement(outputGate, tanh(cell));
  8850. }
  8851. class LSTMTimeStep extends RNNTimeStep {
  8852. getHiddenLayer(hiddenSize, prevSize) {
  8853. return getHiddenLSTMLayer(hiddenSize, prevSize);
  8854. }
  8855. getEquation(equation, inputMatrix, previousResult, hiddenLayer) {
  8856. return getLSTMEquation(equation, inputMatrix, previousResult, hiddenLayer);
  8857. }
  8858. }
  8859. /**
  8860. *
  8861. * @param start
  8862. * @param end
  8863. * @returns {Array}
  8864. */
  8865. function range(start, end) {
  8866. const result = [];
  8867. for (; start < end; start++) {
  8868. result.push(start);
  8869. }
  8870. return result;
  8871. }
  8872. function toArray(values) {
  8873. if (Array.isArray(values)) {
  8874. return Float32Array.from(values);
  8875. }
  8876. return Float32Array.from(Object.values(values));
  8877. }
  8878. function drawInput({ pixelX, pixelY, radius, inputs, row, line, fontSize, fontClassName, }) {
  8879. let svg = `<rect
  8880. x="${pixelX / 2 - radius}"
  8881. y="${pixelY / 2 + row * pixelY - radius}"
  8882. width="${2 * radius}"
  8883. height="${2 * radius}"
  8884. stroke="black"
  8885. stroke-width="1"
  8886. fill="${inputs.color}"
  8887. class="${inputs.className}" />
  8888. <line
  8889. x1="${pixelX / 4}"
  8890. y1="${pixelY / 2 + row * pixelY}"
  8891. x2="${pixelX / 2 - radius}"
  8892. y2="${pixelY / 2 + row * pixelY}"
  8893. style="stroke:${line.color};stroke-width:${line.width}"
  8894. class="${line.className}" />`;
  8895. if (inputs.labels) {
  8896. svg += `<text
  8897. x="${pixelX / 8}"
  8898. y="${pixelY / 2 + row * pixelY - 5}"
  8899. fill="black"
  8900. font-size="${fontSize}"
  8901. class="${fontClassName}">${inputs.labels[row]}</text>`;
  8902. }
  8903. return svg;
  8904. }
  8905. function drawNeuron({ pixelX, pixelY, row, column, radius, hidden, }) {
  8906. return `<circle
  8907. cx="${pixelX / 2 + column * pixelX}"
  8908. cy="${pixelY / 2 + row * pixelY}"
  8909. r="${radius}"
  8910. stroke="black"
  8911. stroke-width="1"
  8912. fill="${hidden.color}"
  8913. class="${hidden.className}" />`;
  8914. }
  8915. function drawOutput({ pixelX, pixelY, row, column, line, outputs, radius, }) {
  8916. return `<circle
  8917. cx="${pixelX / 2 + column * pixelX}"
  8918. cy="${pixelY / 2 + row * pixelY}"
  8919. r="${radius}"
  8920. stroke="black"
  8921. stroke-width="1"
  8922. fill="${outputs.color}"
  8923. class="${outputs.className}" />
  8924. <line
  8925. x1="${pixelX / 2 + column * pixelX + radius}"
  8926. y1="${pixelY / 2 + row * pixelY}"
  8927. x2="${pixelX / 2 + column * pixelX + pixelX / 4}"
  8928. y2="${pixelY / 2 + row * pixelY}"
  8929. style="stroke:${line.color};stroke-width:${line.width}"
  8930. class="${line.className}" />`;
  8931. }
  8932. function drawBackwardConnections({ pixelX, pixelY, row, column, radius, lineY, line, previousConnectionIndex, }) {
  8933. return `<line
  8934. x1="${pixelX / 2 + (column - 1) * pixelX + radius}"
  8935. y1="${lineY / 2 + previousConnectionIndex * lineY}"
  8936. x2="${pixelX / 2 + column * pixelX - radius}"
  8937. y2="${pixelY / 2 + row * pixelY}"
  8938. style="stroke:${line.color};stroke-width:${line.width}"
  8939. class="${line.className}" />`;
  8940. }
  8941. function neuralNetworkToInnerSVG(options) {
  8942. const { sizes, height, width } = options;
  8943. let svg = '';
  8944. const pixelX = width / sizes.length;
  8945. for (let column = 0; column < sizes.length; column++) {
  8946. const size = sizes[column];
  8947. const pixelY = height / size;
  8948. for (let row = 0; row < size; row++) {
  8949. if (column === 0) {
  8950. svg += drawInput({ pixelX, pixelY, row, column, ...options });
  8951. }
  8952. else {
  8953. if (column === sizes.length - 1) {
  8954. svg += drawOutput({ pixelX, pixelY, row, column, ...options });
  8955. }
  8956. else {
  8957. svg += drawNeuron({ pixelX, pixelY, row, column, ...options });
  8958. }
  8959. const previousSize = sizes[column - 1];
  8960. const lineY = height / previousSize;
  8961. for (let previousConnectionIndex = 0; previousConnectionIndex < previousSize; previousConnectionIndex++) {
  8962. svg += drawBackwardConnections({
  8963. pixelX,
  8964. pixelY,
  8965. row,
  8966. column,
  8967. lineY,
  8968. previousConnectionIndex,
  8969. ...options,
  8970. });
  8971. }
  8972. }
  8973. }
  8974. }
  8975. return svg;
  8976. }
  8977. function drawRecurrentConnections({ pixelX, pixelY, row, column, radius, recurrentLine, }) {
  8978. const moveX = pixelX / 2 + column * pixelX + radius + 1;
  8979. const moveY = pixelY / 2 + row * pixelY;
  8980. const x = moveX - radius * 2 - 2;
  8981. const y = moveY;
  8982. const x1 = x + 100;
  8983. const y1 = y + 50;
  8984. const x2 = moveX - 100;
  8985. const y2 = moveY + 50;
  8986. return `<path
  8987. d="M ${moveX} ${moveY} C ${x1} ${y1}, ${x2} ${y2}, ${x} ${y}"
  8988. stroke="${recurrentLine.color}"
  8989. stroke-width="${recurrentLine.width}"
  8990. fill="transparent"
  8991. stroke-linecap="round"
  8992. marker-end="url(#arrow)"
  8993. class="${recurrentLine.className}" />`;
  8994. }
  8995. function rnnToInnerSVG(options) {
  8996. const { width, height, recurrentLine, sizes, radius } = options;
  8997. const pixelX = width / sizes.length;
  8998. let svg = `<defs>
  8999. <marker id="arrow" markerWidth="10" markerHeight="10" refX="8" refY="3" orient="auto" markerUnits="strokeWidth">
  9000. <path d="M0,0 L0,6 L9,3 z" fill="${recurrentLine.color}" />
  9001. </marker>
  9002. </defs>`;
  9003. svg += neuralNetworkToInnerSVG(options);
  9004. for (let column = 1; column < sizes.length; column++) {
  9005. const size = sizes[column];
  9006. const pixelY = height / size;
  9007. for (let row = 0; row < size; row++) {
  9008. svg += drawRecurrentConnections({
  9009. pixelX,
  9010. pixelY,
  9011. row,
  9012. column,
  9013. radius,
  9014. recurrentLine,
  9015. });
  9016. }
  9017. }
  9018. return svg;
  9019. }
  9020. function getFeedForwardLayers(network) {
  9021. const { options } = network;
  9022. if (!options) {
  9023. throw new Error('options not defined');
  9024. }
  9025. if (!options.inputLayer) {
  9026. throw new Error('options.inputLater not defined');
  9027. }
  9028. if (!options.hiddenLayers) {
  9029. throw new Error('options.hiddenLayers not defined');
  9030. }
  9031. if (options.hiddenLayers.length < 1) {
  9032. throw new Error('options.hiddenLayers is empty');
  9033. }
  9034. if (!options.outputLayer) {
  9035. throw new Error('options.outputLayer not defined');
  9036. }
  9037. const inputLayer = options.inputLayer();
  9038. const hiddenLayers = [];
  9039. hiddenLayers.push(options.hiddenLayers[0](inputLayer, 0));
  9040. for (let i = 1; i < options.hiddenLayers.length; i++) {
  9041. hiddenLayers.push(options.hiddenLayers[i](hiddenLayers[i - 1], i));
  9042. }
  9043. const outputLayer = options.outputLayer(hiddenLayers[hiddenLayers.length - 1], hiddenLayers.length);
  9044. return {
  9045. inputSize: inputLayer.height,
  9046. hiddenLayers: hiddenLayers.map((hiddenLayer) => hiddenLayer.height),
  9047. outputSize: outputLayer.height,
  9048. };
  9049. }
  9050. function getRecurrentLayers(network) {
  9051. const hiddenLayers = [];
  9052. const { options } = network;
  9053. if (!options.inputLayer) {
  9054. throw new Error('inputLayer not defined');
  9055. }
  9056. if (!options.outputLayer) {
  9057. throw new Error('outputLayer not defined');
  9058. }
  9059. const inputLayer = options.inputLayer();
  9060. hiddenLayers.push(options.hiddenLayers[0](inputLayer, recurrentZeros(), 0));
  9061. for (let i = 1; i < options.hiddenLayers.length; i++) {
  9062. hiddenLayers.push(options.hiddenLayers[i](hiddenLayers[i - 1], recurrentZeros(), i));
  9063. }
  9064. const outputLayer = options.outputLayer(hiddenLayers[hiddenLayers.length - 1], -1);
  9065. return {
  9066. inputSize: inputLayer.height,
  9067. hiddenLayers: hiddenLayers.map((hiddenLayer) => hiddenLayer.height),
  9068. outputSize: outputLayer.height,
  9069. };
  9070. }
  9071. function wrapOuterSVG(svgBody, width, height) {
  9072. // language=html
  9073. return `<svg
  9074. xmlns="http://www.w3.org/2000/svg"
  9075. xmlns:xlink="http://www.w3.org/1999/xlink"
  9076. version="1.1"
  9077. width="${width}"
  9078. height="${height}">${svgBody}</svg>`;
  9079. }
  9080. function getNeuralNetworkJSONSizes(json) {
  9081. return json.sizes;
  9082. }
  9083. function getNeuralNetworkSizes(net) {
  9084. const { options, sizes } = net;
  9085. const { inputSize, outputSize, hiddenLayers } = options;
  9086. if (!sizes) {
  9087. if (typeof inputSize === 'number' && inputSize < 1) {
  9088. throw new Error('inputSize not set');
  9089. }
  9090. if (typeof outputSize === 'number' && outputSize < 1) {
  9091. throw new Error('outputSize not set');
  9092. }
  9093. if (hiddenLayers === null || hiddenLayers === void 0 ? void 0 : hiddenLayers.some((v) => v < 1)) {
  9094. throw new Error('hiddenLayers not set');
  9095. }
  9096. }
  9097. return typeof inputSize === 'number' &&
  9098. Array.isArray(hiddenLayers) &&
  9099. typeof outputSize === 'number'
  9100. ? [inputSize].concat(hiddenLayers).concat([outputSize])
  9101. : sizes;
  9102. }
  9103. function getRNNSizes(net) {
  9104. const { options } = net;
  9105. const { inputSize, outputSize, hiddenLayers } = options;
  9106. return [inputSize].concat(hiddenLayers).concat([outputSize]);
  9107. }
  9108. function defaultOptions() {
  9109. return {
  9110. line: {
  9111. width: 0.5,
  9112. color: 'black',
  9113. className: 'connection',
  9114. },
  9115. recurrentLine: {
  9116. width: 1,
  9117. color: 'red',
  9118. className: 'recurrence',
  9119. },
  9120. inputs: {
  9121. color: 'rgba(0, 128, 0, 0.5)',
  9122. labels: null,
  9123. className: 'input',
  9124. },
  9125. outputs: {
  9126. color: 'rgba(100, 149, 237, 0.5)',
  9127. className: 'output',
  9128. },
  9129. hidden: {
  9130. color: 'rgba(255, 127, 80, 0.5)',
  9131. className: 'hidden-neuron',
  9132. },
  9133. fontSize: '14px',
  9134. fontClassName: 'label',
  9135. radius: 8,
  9136. width: 400,
  9137. height: 250,
  9138. sizes: [],
  9139. };
  9140. }
  9141. function toSVG(net, options) {
  9142. const mergedOptions = { ...defaultOptions(), ...options };
  9143. const { width, height, inputs } = mergedOptions;
  9144. // Get network size array for NeuralNetwork or NeuralNetworkGPU
  9145. let sizes = [];
  9146. if (net instanceof NeuralNetwork || net instanceof NeuralNetworkGPU) {
  9147. sizes = getNeuralNetworkSizes(net);
  9148. }
  9149. // get network size for Recurrent
  9150. else if (net instanceof Recurrent) {
  9151. const { inputSize, hiddenLayers, outputSize } = getRecurrentLayers(net);
  9152. sizes = [inputSize].concat(hiddenLayers).concat([outputSize]);
  9153. }
  9154. // get network size for FeedForward
  9155. else if (net instanceof FeedForward) {
  9156. const { inputSize, hiddenLayers, outputSize } = getFeedForwardLayers(net);
  9157. sizes = [inputSize].concat(hiddenLayers).concat([outputSize]);
  9158. }
  9159. // handle json, recurrent first
  9160. else if (net instanceof RNN ||
  9161. net instanceof LSTM ||
  9162. net instanceof GRU ||
  9163. net instanceof RNNTimeStep ||
  9164. net instanceof LSTMTimeStep ||
  9165. net instanceof GRUTimeStep) {
  9166. return wrapOuterSVG(rnnToInnerSVG({
  9167. ...mergedOptions,
  9168. sizes: checkSizes(getRNNSizes(net), inputs.labels),
  9169. }), width, height);
  9170. }
  9171. // handle json, NeuralNetwork
  9172. else if (net.hasOwnProperty('type')) {
  9173. switch (net.type) {
  9174. case 'NeuralNetwork':
  9175. case 'NeuralNetworkGPU':
  9176. return wrapOuterSVG(neuralNetworkToInnerSVG({
  9177. ...mergedOptions,
  9178. sizes: checkSizes(getNeuralNetworkJSONSizes(net), inputs.labels),
  9179. }), width, height);
  9180. case 'RNN':
  9181. case 'GRU':
  9182. case 'LSTM':
  9183. case 'RNNTimeStep':
  9184. case 'GRUTimeStep':
  9185. case 'LSTMTimeStep':
  9186. return wrapOuterSVG(rnnToInnerSVG({
  9187. ...mergedOptions,
  9188. sizes: checkSizes(getRNNSizes(net), inputs.labels),
  9189. }), width, height);
  9190. default:
  9191. throw new Error('unrecognized network');
  9192. }
  9193. }
  9194. else if (net.hasOwnProperty('inputSize') &&
  9195. net.hasOwnProperty('hiddenLayers') &&
  9196. net.hasOwnProperty('outputSize')) {
  9197. const { inputSize, hiddenLayers, outputSize } = net;
  9198. sizes = [inputSize, ...hiddenLayers, outputSize];
  9199. }
  9200. else if (net.hasOwnProperty('sizes')) {
  9201. sizes = net.sizes;
  9202. }
  9203. else {
  9204. throw new Error('unrecognized network');
  9205. }
  9206. return wrapOuterSVG(neuralNetworkToInnerSVG({
  9207. ...mergedOptions,
  9208. sizes: checkSizes(sizes, inputs.labels),
  9209. }), width, height);
  9210. }
  9211. function checkSizes(sizes, labels) {
  9212. if (!sizes) {
  9213. throw new Error('sizes not set');
  9214. }
  9215. if (sizes.some((size) => size < 1)) {
  9216. throw new Error('sizes not set correctly');
  9217. }
  9218. if (labels && labels.length !== sizes[0]) {
  9219. throw new Error('not enough labels for inputs');
  9220. }
  9221. return sizes;
  9222. }
  9223. const recurrent = {
  9224. RNNTimeStep,
  9225. LSTMTimeStep,
  9226. GRUTimeStep,
  9227. RNN,
  9228. LSTM,
  9229. GRU,
  9230. };
  9231. const utilities = {
  9232. max,
  9233. mse: mse$1,
  9234. ones: ones$1,
  9235. ones2D,
  9236. random: random$1,
  9237. randomWeight,
  9238. randos,
  9239. range,
  9240. toArray,
  9241. DataFormatter,
  9242. zeros: zeros$1,
  9243. toSVG,
  9244. };
  9245. exports.CrossValidate = CrossValidate;
  9246. exports.FeedForward = FeedForward;
  9247. exports.NeuralNetwork = NeuralNetwork;
  9248. exports.NeuralNetworkGPU = NeuralNetworkGPU;
  9249. exports.Recurrent = Recurrent;
  9250. exports.activation = index$1;
  9251. exports.layer = layer;
  9252. exports.layerTypes = layerTypes;
  9253. exports.likely = likely;
  9254. exports.lookup = lookup;
  9255. exports.praxis = index;
  9256. exports.recurrent = recurrent;
  9257. exports.utilities = utilities;
  9258. Object.defineProperty(exports, '__esModule', { value: true });
  9259. })));
  9260. //# sourceMappingURL=brain-browser.js.map