1&&(t=n.slice(1,n.length)),n=n[0]}function r(a){return a==null||Array.isArray(a)?a:[a]}return t=r(t),e=r(e),{inputs:n,initialState:t,constants:e}}function Ky(n,t,e,i,r,a,s,o){return i===void 0&&(i=!1),s===void 0&&(s=!1),o===void 0&&(o=!1),y.tidy(function(){var l=t.shape.length;if(l<3)throw new M("Input should be at least 3D, but is "+l+"D.");var u=[1,0].concat(pn(2,l));if(t=y.transpose(t,u),a!=null)throw new Te("The rnn() functoin of the deeplearn.js backend does not support constants yet.");s&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),r!=null&&(r=r.asType("bool").asType("float32"),r.rank===l-1&&(r=y.expandDims(r,-1)),r=y.transpose(r,u)),i&&(t=y.reverse(t,0),r!=null&&(r=y.reverse(r,0)));var c=[],h,d=e,p=t.shape[0],f=y.unstack(t),m;r!=null&&(m=y.unstack(r));for(var g=function(S){var L=f[S],x=y.tidy(function(){return n(L,d)});if(r==null)h=x[0],d=x[1];else{var C=y.tidy(function(){var R=m[S],D=y.onesLike(R).sub(R),k=x[0].mul(R).add(d[0].mul(D)),W=d.map(function(F,P){return x[1][P].mul(R).add(F.mul(D))});return{output:k,newStates:W}});h=C.output,d=C.newStates}o&&c.push(h)},v=0;v1?lh(r,[1,a]):r}):i.cell.stateSize>1?[lh(r,[1,i.cell.stateSize])]:[r]})},Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),t.prototype.setFastWeightInitDuringBuild=function(e){n.prototype.setFastWeightInitDuringBuild.call(this,e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)},t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this),i={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(i.numConstants=this.numConstants);var r=this.cell.getConfig();return this.getClassName()===t.className&&(i.cell={className:this.cell.getClassName(),config:r}),Vt({},r,e,i)},t.fromConfig=function(e,i,r){r===void 0&&(r={});var a=i.cell,s=mn(a,r);return new e(Object.assign(i,{cell:s}))},t.className="RNN",t}(De);y.serialization.registerClass(yi);var Hr=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t}(De),Mh=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.DEFAULT_ACTIVATION="tanh",i.DEFAULT_KERNEL_INITIALIZER="glorotNormal",i.DEFAULT_RECURRENT_INITIALIZER="orthogonal",i.DEFAULT_BIAS_INITIALIZER="zeros",i.units=e.units,It(i.units,"units"),i.activation=vi(e.activation==null?i.DEFAULT_ACTIVATION:e.activation),i.useBias=e.useBias==null?!0:e.useBias,i.kernelInitializer=et(e.kernelInitializer||i.DEFAULT_KERNEL_INITIALIZER),i.recurrentInitializer=et(e.recurrentInitializer||i.DEFAULT_RECURRENT_INITIALIZER),i.biasInitializer=et(e.biasInitializer||i.DEFAULT_BIAS_INITIALIZER),i.kernelRegularizer=tt(e.kernelRegularizer),i.recurrentRegularizer=tt(e.recurrentRegularizer),i.biasRegularizer=tt(e.biasRegularizer),i.kernelConstraint=yt(e.kernelConstraint),i.recurrentConstraint=yt(e.recurrentConstraint),i.biasConstraint=yt(e.biasConstraint),i.dropout=Br([1,pi([0,e.dropout==null?0:e.dropout])]),i.recurrentDropout=Br([1,pi([0,e.recurrentDropout==null?0:e.recurrentDropout])]),i.stateSize=i.units,i.dropoutMask=null,i.recurrentDropoutMask=null,i}return t.prototype.build=function(e){e=Ye(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){if(e=e,e.length!==2)throw new M("SimpleRNNCell expects 2 input Tensors, got "+e.length+".");var a=e[1];e=e[0];var s=i.training==null?!1:i.training;01){for(var s=[0],o=2;o1)throw new M("Can not merge tensors with different batch sizes. "+("Got tensors with shapes: "+JSON.stringify(e)+"."));for(var o=e[0]==null?null:e[0].slice(1),l=1;l1){var S=pn(1,h).concat([0]);a.push(y.transpose(c,S)),p=!0}else a.push(c)}var L=r.mergeFunction(a),x=L.rank;if(p){if(x==null){var C=L.shape,R=C.length,v=C[R-1],b=[v].concat(C.slice(0,C.length-1));L=y.transpose(L.reshape([-1,v]),[1,0]).reshape(b)}else if(x>1){var S=[x-1].concat(pn(0,x-1));L=y.transpose(L,S)}}return L}}else return r.mergeFunction(e)})},t.prototype.computeOutputShape=function(e){e=e;var i;e[0]==null?i=null:i=e[0].slice(1);for(var r=1;r1)throw new M("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))},t.prototype.mergeFunction=function(e){var i=this;return y.tidy(function(){return ch(e,i.axis)})},t.prototype.computeOutputShape=function(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new M("A `Concatenate` layer should be called on a list of inputs.");for(var i=e,r=i[0].slice(),a=this.axis<0?r.length+this.axis:this.axis,s=0,o=i.slice(1);s3||t.shape.length>3)throw new Te("batchDot is not implemented for tensors of 4D or higher rank yet");if(y.util.assert(n.shape.length>=2,function(){return"batchDot requires the rank of x to be >= 2, "+("but got "+n.shape.length)}),y.util.assert(n.shape.length>=2,function(){return"batchDot requires the rank of y to be >= 2, "+("but got "+t.shape.length)}),typeof e=="number"&&(e=[e,e]),n.dtype==="complex64"||t.dtype==="complex64")throw new Te("batchDot is not implemented for complex64-type Tensors yet.");var i=n.shape.length,r=t.shape.length;e==null&&(e=[i-1,r-2]);var a=e;return y.tidy(function(){var s;if(i>r){s=i-r;for(var o=[],l=0;li){s=r-i;for(var o=[],l=0;l0){var d=void 0;i>r?d=i+r-3:d=i-1;for(var p=[],l=d;l3||r.length>3)throw new Te("Dot layer does not support tensors of 4D or higher rank yet.");var a=this.interpretAxes(i,r);if(i[a[0]]!==r[a[1]])throw new M("Dimension incompatibility: "+(i[a[0]]+" !== "+r[a[1]]))},t.prototype.mergeFunction=function(e){if(e.length!==2)throw new M("A `Dot` layer must be called on exactly 2 inputs, "+("but received "+e.length+" input(s)."));var i=e[0],r=e[1],a;return Array.isArray(this.axes)?a=this.axes.map(function(s,o){return Va(s,e[o].shape.length)}):a=[Va(this.axes,i.shape.length),Va(this.axes,r.shape.length)],this.normalize&&(i=co(i,a[0]),r=co(r,a[1])),nF(i,r,a)},t.prototype.interpretAxes=function(e,i){var r;return Array.isArray(this.axes)?r=this.axes:r=[Va(this.axes,e.length),Va(this.axes,i.length)],r},t.prototype.computeOutputShape=function(e){y.util.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var i=e[0].slice(),r=e[1].slice();if(i.length>3||r.length>3)throw new Te("Dot layer does not support tensors of 4D or higher rank yet.");var a=this.interpretAxes(i,r);i.splice(a[0],1),r.splice(a[1],1),r.splice(0,1);var s=i.concat(r);return s.length===1&&s.push(1),s},t.prototype.computeMask=function(e,i){return null},t.prototype.getConfig=function(){var e={axes:this.axes,normalize:this.normalize},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t.className="Dot",t}(Zi);y.serialization.registerClass(pb);var fb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.supportsMasking=!0,i.stddev=e.stddev,i}return t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this),i={stddev:this.stddev};return Object.assign(i,e),i},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){r.invokeCallHook(e,i);var a=xe(e),s=function(){return ro(a.shape,0,r.stddev).add(a)},o=Ba(s,function(){return a},i.training||!1);return o})},t.className="GaussianNoise",t}(De);y.serialization.registerClass(fb);var mb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.supportsMasking=!0,i.rate=e.rate,i}return t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this),i={rate:this.rate};return Object.assign(i,e),i},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){r.invokeCallHook(e,i);var a=xe(e);if(r.rate>0&&r.rate<1){var s=function(){var o=Math.sqrt(r.rate/(1-r.rate));return a.mul(ro(a.shape,1,o))};return Ba(s,function(){return a},i.training||!1)}return a})},t.className="GaussianDropout",t}(De);y.serialization.registerClass(mb);var gb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.supportsMasking=!0,i.rate=e.rate,i.noiseShape=e.noiseShape,i}return t.prototype._getNoiseShape=function(e){return this.noiseShape||xe(e).shape},t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this),i={rate:this.rate};return Object.assign(i,e),i},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){if(r.rate<1&&r.rate>0){var a=r._getNoiseShape(e),s=function(){var o=xe(e),l=1.6732632423543772,u=1.0507009873554805,c=-l*u,h=y.greaterEqual(y.randomUniform(a),r.rate);h=Fa(h,"float32");var d=Math.pow((1-r.rate)*(1+r.rate*Math.pow(c,2)),-.5),p=-d*c*r.rate,f=o.mul(h).add(h.add(-1).mul(c));return f.mul(d).add(p)};return Ba(s,function(){return xe(e)},i.training||!1)}return e})},t.className="AlphaDropout",t}(De);y.serialization.registerClass(gb);function qa(n,t,e,i,r,a){a===void 0&&(a=.001);var s;if(n.rank===2)s=y.batchNorm2d(n,t,e,i,r,a);else if(n.rank===3)s=y.batchNorm3d(n,t,e,i,r,a);else if(n.rank===4)s=y.batchNorm4d(n,t,e,i,r,a);else throw new Te("batchNormalization is not implemented for array of rank "+n.rank+" yet");return s}function iF(n,t,e,i,r){return r===void 0&&(r=.001),y.tidy(function(){var a=y.moments(n,i),s=a.mean,o=a.variance,l=qa(n,s,o,e,t,r);return[l,s,o]})}function rF(n,t,e,i,r){return r===void 0&&(r=.001),y.tidy(function(){for(var a=y.moments(n,i),s=a.mean,o=a.variance,l=[],u=0,c=pn(0,n.rank);u=0?this.axis:this.axis+e.length,a=e[r];if(a==null)throw new M("Axis "+r+" of input tensor should have a defined dimension but the layer received an input with shape "+(JSON.stringify(e)+"."));this.inputSpec=[new At({ndim:e.length,axes:(i={},i[r]=a,i)})];var s=[a];this.scale&&(this.gamma=this.addWeight("gamma",s,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",s,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",s,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",s,null,this.movingVarianceInitializer,null,!1),this.built=!0},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){var a=i.training==null?!1:i.training,s=xe(e),o=s.shape,l=o.length,u=pn(0,l),c=r.axis>=0?r.axis:r.axis+l;u.splice(c,1);var h=Yi(1,l);h[c]=o[c];var d=u.slice();d.sort();var p=!y.util.arraysEqual(d,pn(0,l).slice(0,l-1)),f=function(){if(p){var L=r.movingMean.read().reshape(h),x=r.movingVariance.read().reshape(h),C=r.center?r.beta.read().reshape(h):null,R=r.scale?r.gamma.read().reshape(h):null;return qa(s,L,x,C,R,r.epsilon)}else return qa(s,r.movingMean.read(),r.movingVariance.read(),r.beta==null?null:r.beta.read(),r.gamma==null?null:r.gamma.read(),r.epsilon)};if(!a)return f();var m=aF(s,r.gamma.read(),r.beta.read(),u,r.epsilon),g=m[0],v=m[1],b=m[2],w=function(L,x,C){y.tidy(function(){var R=1-C,D=L.read(),k=D.sub(x).mul(R);L.write(D.sub(k))})},S=function(){w(r.movingMean,v,r.momentum),w(r.movingVariance,b,r.momentum)};return S(),g})},t.prototype.getConfig=function(){var e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:at(this.betaInitializer),gammaInitializer:at(this.gammaInitializer),movingMeanInitializer:at(this.movingMeanInitializer),movingVarianceInitializer:at(this.movingVarianceInitializer),betaRegularizer:Ke(this.betaRegularizer),gammaRegularizer:Ke(this.gammaRegularizer),betaConstraint:vt(this.betaConstraint),gammaConstraint:vt(this.gammaConstraint)},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t.className="BatchNormalization",t}(De);y.serialization.registerClass(vb);var yb=function(n){Q(t,n);function t(e){var i=this;if(e==null&&(e={}),i=n.call(this,e)||this,i.axis=e.axis==null?-1:e.axis,typeof i.axis=="number"){if(!Number.isInteger(i.axis))throw new Error("Expected axis to be an integer, but received "+i.axis)}else if(Array.isArray(i.axis))for(var r=0,a=i.axis;r=i)throw new Error("Invalid axis: "+o)}if(this.axis.length!==hi(this.axis).length)throw new Error("Found duplicate axes in: "+this.axis);var l=this.axis.map(function(c){return e[c]}),u=!0;this.scale?this.gamma=this.addWeight("gamma",l,"float32",this.gammaInitializer,this.gammaRegularizer,u):this.gamma=null,this.center?this.beta=this.addWeight("beta",l,"float32",this.betaInitializer,this.betaRegularizer,u):this.beta=null,this.built=!0},t.prototype.call=function(e,i){var r=this,a=xe(e),s=a.shape,o=s.length;return y.tidy(function(){for(var l=!0,u=y.moments(a,r.axis,l),c=u.mean,h=u.variance,d=Yi(1,o),p=0,f=r.axis;p=0?i=e[2]+this.padding[0][0]+this.padding[0][1]:i=null,e[3]!=null&&e[3]>=0?r=e[3]+this.padding[1][0]+this.padding[1][1]:r=null,[e[0],e[1],i,r]):(e[1]!=null&&e[1]>=0?i=e[1]+this.padding[0][0]+this.padding[0][1]:i=null,e[2]!=null&&e[2]>=0?r=e[2]+this.padding[1][0]+this.padding[1][1]:r=null,[e[0],i,r,e[3]])},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){return sF(xe(e),r.padding,r.dataFormat)})},t.prototype.getConfig=function(){var e={padding:this.padding,dataFormat:this.dataFormat},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t.className="ZeroPadding2D",t}(De);y.serialization.registerClass(bb);function Io(n,t,e,i,r,a){return y.tidy(function(){ut(r),Rv(a),Qt(i),e==null&&(e=[1,1]),i==null&&(i="valid"),r==null&&(r=dn()),a==null&&(a="max"),n=zh(n,r);var s,o=i==="same"?"same":"valid";return a==="max"?s=y.maxPool(n,t,e,o):s=y.avgPool(n,t,e,o),r==="channelsFirst"&&(s=y.transpose(s,[0,3,1,2])),s})}function wb(n,t,e,i,r,a){return y.tidy(function(){ut(r),Rv(a),Qt(i),e==null&&(e=[1,1,1]),i==null&&(i="valid"),r==null&&(r=dn()),a==null&&(a="max"),n=Uy(n,r);var s,o=i==="same"?"same":"valid";return a==="max"?s=y.maxPool3d(n,t,e,o):s=y.avgPool3d(n,t,e,o),r==="channelsFirst"&&(s=y.transpose(s,[0,4,1,2,3])),s})}var Sb=function(n){Q(t,n);function t(e){var i=this;if(e.poolSize==null&&(e.poolSize=2),i=n.call(this,e)||this,typeof e.poolSize=="number")i.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")i.poolSize=e.poolSize;else throw new M("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+(""+JSON.stringify(e.poolSize)));if(It(i.poolSize,"poolSize"),e.strides==null)i.strides=i.poolSize;else if(typeof e.strides=="number")i.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")i.strides=e.strides;else throw new M("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+(""+JSON.stringify(e.strides)));return It(i.strides,"strides"),i.padding=e.padding==null?"valid":e.padding,Qt(i.padding),i.inputSpec=[new At({ndim:3})],i}return t.prototype.computeOutputShape=function(e){e=Ye(e);var i=gn(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],i,e[2]]},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){r.invokeCallHook(e,i),e=Wa(xe(e),2);var a=r.poolingFunction(xe(e),[r.poolSize[0],1],[r.strides[0],1],r.padding,"channelsLast");return y.squeeze(a,[2])})},t.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t}(De),Lb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ut(s),Qt(a),Io(e,i,r,a,s,"max")},t.className="MaxPooling1D",t}(Sb);y.serialization.registerClass(Lb);var Ib=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ut(s),Qt(a),Io(e,i,r,a,s,"avg")},t.className="AveragePooling1D",t}(Sb);y.serialization.registerClass(Ib);var Ab=function(n){Q(t,n);function t(e){var i=this;if(e.poolSize==null&&(e.poolSize=[2,2]),i=n.call(this,e)||this,i.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)i.strides=i.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new M("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+(e.strides.length+"."));i.strides=e.strides}else i.strides=[e.strides,e.strides];return It(i.poolSize,"poolSize"),It(i.strides,"strides"),i.padding=e.padding==null?"valid":e.padding,i.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,ut(i.dataFormat),Qt(i.padding),i.inputSpec=[new At({ndim:4})],i}return t.prototype.computeOutputShape=function(e){e=Ye(e);var i=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2];return i=gn(i,this.poolSize[0],this.padding,this.strides[0]),r=gn(r,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],i,r]:[e[0],i,r,e[3]]},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){return r.invokeCallHook(e,i),r.poolingFunction(xe(e),r.poolSize,r.strides,r.padding,r.dataFormat)})},t.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t}(De),Tb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ut(s),Qt(a),Io(e,i,r,a,s,"max")},t.className="MaxPooling2D",t}(Ab);y.serialization.registerClass(Tb);var Nb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ut(s),Qt(a),Io(e,i,r,a,s,"avg")},t.className="AveragePooling2D",t}(Ab);y.serialization.registerClass(Nb);var xb=function(n){Q(t,n);function t(e){var i=this;if(e.poolSize==null&&(e.poolSize=[2,2,2]),i=n.call(this,e)||this,i.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)i.strides=i.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new M("If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length "+(e.strides.length+"."));i.strides=e.strides}else i.strides=[e.strides,e.strides,e.strides];return It(i.poolSize,"poolSize"),It(i.strides,"strides"),i.padding=e.padding==null?"valid":e.padding,i.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,ut(i.dataFormat),Qt(i.padding),i.inputSpec=[new At({ndim:5})],i}return t.prototype.computeOutputShape=function(e){e=Ye(e);var i=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[4]:e[3];return i=gn(i,this.poolSize[0],this.padding,this.strides[0]),r=gn(r,this.poolSize[1],this.padding,this.strides[1]),a=gn(a,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],i,r,a]:[e[0],i,r,a,e[4]]},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){return r.invokeCallHook(e,i),r.poolingFunction(xe(e),r.poolSize,r.strides,r.padding,r.dataFormat)})},t.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t}(De),Cb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ut(s),Qt(a),wb(e,i,r,a,s,"max")},t.className="MaxPooling3D",t}(xb);y.serialization.registerClass(Cb);var Rb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ut(s),Qt(a),wb(e,i,r,a,s,"avg")},t.className="AveragePooling3D",t}(xb);y.serialization.registerClass(Rb);var Ob=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.inputSpec=[new At({ndim:3})],i}return t.prototype.computeOutputShape=function(e){return[e[0],e[2]]},t.prototype.call=function(e,i){throw new Te},t}(De),Eb=function(n){Q(t,n);function t(e){return n.call(this,e||{})||this}return t.prototype.call=function(e,i){return y.tidy(function(){var r=xe(e);return y.mean(r,1)})},t.className="GlobalAveragePooling1D",t}(Ob);y.serialization.registerClass(Eb);var Db=function(n){Q(t,n);function t(e){return n.call(this,e||{})||this}return t.prototype.call=function(e,i){return y.tidy(function(){var r=xe(e);return y.max(r,1)})},t.className="GlobalMaxPooling1D",t}(Ob);y.serialization.registerClass(Db);var kb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,ut(i.dataFormat),i.inputSpec=[new At({ndim:4})],i}return t.prototype.computeOutputShape=function(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]},t.prototype.call=function(e,i){throw new Te},t.prototype.getConfig=function(){var e={dataFormat:this.dataFormat},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t}(De),Fb=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.call=function(e,i){var r=this;return y.tidy(function(){var a=xe(e);return r.dataFormat==="channelsLast"?y.mean(a,[1,2]):y.mean(a,[2,3])})},t.className="GlobalAveragePooling2D",t}(kb);y.serialization.registerClass(Fb);var Wb=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.call=function(e,i){var r=this;return y.tidy(function(){var a=xe(e);return r.dataFormat==="channelsLast"?y.max(a,[1,2]):y.max(a,[2,3])})},t.className="GlobalMaxPooling2D",t}(kb);y.serialization.registerClass(Wb);var Ub=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.layer=e.layer,i}return t.prototype.build=function(e){this.built=!0},Object.defineProperty(t.prototype,"trainable",{get:function(){return this.layer!=null?this.layer.trainable:!1},set:function(e){this.layer!=null&&(this.layer.trainable=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.layer.trainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.layer.nonTrainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"updates",{get:function(){return this.layer._updates},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function(){return this.layer.losses},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.layer.getWeights()},t.prototype.setWeights=function(e){this.layer.setWeights(e)},t.prototype.getConfig=function(){var e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t.prototype.setFastWeightInitDuringBuild=function(e){n.prototype.setFastWeightInitDuringBuild.call(this,e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)},t.fromConfig=function(e,i,r){r===void 0&&(r={});var a=i.layer,s=mn(a,r);delete i.layer;var o={layer:s};return Object.assign(o,i),new e(o)},t}(De),Bb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.supportsMasking=!0,i}return t.prototype.build=function(e){if(e=Ye(e),e.length<3)throw new M("TimeDistributed layer expects an input shape >= 3D, but received "+("input shape "+JSON.stringify(e)));this.inputSpec=[{shape:e}];var i=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(i),this.layer.built=!0),n.prototype.build.call(this,e)},t.prototype.computeOutputShape=function(e){e=Ye(e);var i=[e[0]].concat(e.slice(2)),r=this.layer.computeOutputShape(i),a=e[1];return[r[0],a].concat(r.slice(1))},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){e=xe(e);var a=function(l,u){var c=xe(r.layer.call(l,i));return[c,[]]},s=Ky(a,e,[],!1,null,null,!1,!0),o=s[1];return o})},t.className="TimeDistributed",t}(Ub);y.serialization.registerClass(Bb);function oF(n){Wr(ZD,"BidirectionalMergeMode",n)}var lF="concat",zb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this,r=e.layer.getConfig(),a={};a.className=e.layer.getClassName(),a.config=r,i.forwardLayer=mn(a),r.goBackwards=!(r.goBackwards===!0);var s={};if(s.className=e.layer.getClassName(),s.config=r,i.backwardLayer=mn(s),i.forwardLayer.name="forward_"+i.forwardLayer.name,i.backwardLayer.name="backward_"+i.backwardLayer.name,i.mergeMode=e.mergeMode===void 0?lF:e.mergeMode,oF(i.mergeMode),e.weights)throw new Te("weights support is not implemented for Bidirectional layer yet.");return i._stateful=e.layer.stateful,i.returnSequences=e.layer.returnSequences,i.returnState=e.layer.returnState,i.supportsMasking=!0,i._trainable=!0,i.inputSpec=e.layer.inputSpec,i.numConstants=null,i}return Object.defineProperty(t.prototype,"trainable",{get:function(){return this._trainable},set:function(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},t.prototype.setWeights=function(e){var i=e.length,r=Math.floor(i/2);this.forwardLayer.setWeights(e.slice(0,r)),this.backwardLayer.setWeights(e.slice(r))},t.prototype.computeOutputShape=function(e){var i=this.forwardLayer.computeOutputShape(e);Array.isArray(i)&&Array.isArray(i[0])||(i=[i]),i=i;var r,a,s;return this.returnState&&(s=i.slice(1)),r=i[0],r=r,this.mergeMode==="concat"?(r[r.length-1]*=2,a=[r]):this.mergeMode==null?a=[r,r.slice()]:a=[r],this.returnState?this.mergeMode==null?a.concat(s).concat(s.slice()):[r].concat(s).concat(s.slice()):zt(a)},t.prototype.apply=function(e,i){var r=i==null?null:i.initialState,a=i==null?null:i.constants;i==null&&(i={});var s=Yy(e,r,a,this.numConstants);if(e=s.inputs,r=s.initialState,a=s.constants,Array.isArray(e)&&(r=e.slice(1),e=e[0]),(r==null||r.length===0)&&a==null)return n.prototype.apply.call(this,e,i);var o=[],l=[];if(r!=null){var u=r.length;if(u%2>0)throw new M("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");i.initialState=r,o.push.apply(o,r);var c=r.map(function(w){return new At({shape:w.shape})});this.forwardLayer.stateSpec=c.slice(0,u/2),this.backwardLayer.stateSpec=c.slice(u/2),l.push.apply(l,c)}if(a!=null)throw new Te("Support for constants in Bidirectional layers is not implemented yet.");for(var h=o[0]instanceof fn,d=0,p=o;dt}var Gb=function(n){Q(t,n);function t(e){var i=n.call(this)||this;if(e==null&&(e={}),e.restoreBestWeights)throw new Te("restoreBestWeights = True is not implemented in EarlyStopping yet.");return i.monitor=e.monitor||"val_loss",i.minDelta=Math.abs(e.minDelta||0),i.patience=e.patience||0,i.verbose=e.verbose||0,i.mode=e.mode||"auto",i.baseline=e.baseline,["auto","min","max"].indexOf(i.mode)===-1&&(console.warn("EarlyStopping mode '"+i.mode+"' is invalid. Falling back to mode 'auto'."),i.mode="auto"),i.mode==="min"?i.monitorFunc=Ao:i.mode==="max"||i.monitor.indexOf("acc")!==-1?i.monitorFunc=qb:i.monitorFunc=Ao,i.monitorFunc===Ao&&(i.minDelta*=-1),i}return t.prototype.onTrainBegin=function(e){return Le(this,void 0,void 0,function(){return ye(this,function(i){return this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Ao?Infinity:-Infinity,[2]})})},t.prototype.onEpochEnd=function(e,i){return Le(this,void 0,void 0,function(){var r;return ye(this,function(a){switch(a.label){case 0:return[4,fi(i)];case 1:return a.sent(),r=this.getMonitorValue(i),r==null?[2]:(this.monitorFunc(r-this.minDelta,this.best)?(this.best=r,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)),[2])}})})},t.prototype.onTrainEnd=function(e){return Le(this,void 0,void 0,function(){return ye(this,function(i){return this.stoppedEpoch>0&&this.verbose&&console.log("Epoch "+this.stoppedEpoch+": early stopping."),[2]})})},t.prototype.getMonitorValue=function(e){e==null&&(e={});var i=e[this.monitor];return i==null&&console.warn("Metric for EarlyStopping "+this.monitor+" is not available. "+("Available metrics are: "+Object.keys(e))),i},t}(Vb);function _W(n){return new Gb(n)}var MW={earlyStopping:_W};$e.Callback=Vb;$e.CallbackList=ey;$e.CustomCallback=ny;$e.EarlyStopping=Gb;$e.History=ty;$e.InputSpec=At;$e.LayerVariable=$v;$e.LayersModel=mi;$e.RNN=yi;$e.Sequential=Wh;$e.SymbolicTensor=fn;$e.callbacks=MW;$e.constraints=jD;$e.initializers=Ck;$e.input=Ty;$e.layers=yW;$e.loadLayersModel=W3;$e.metrics=FW;$e.model=k3;$e.models=WW;$e.registerCallbackConstructor=U3;$e.regularizers=PW;$e.sequential=F3;$e.version_layers=Rh});var ow=ge(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});var B=Gi();var Kb=Object.assign||function(t){for(var e,i=1,r=arguments.length;i0&&a[a.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]0?Object.keys(h).forEach(function(g){var v=Kn(g)[0],b=l[v];b&&(b.signatureKey=h[g],u.push(b))}):u=a;var f={};t.library!=null&&t.library.function!=null&&(f=t.library.function.reduce(function(g,v){return g[v.signature.name]=i.mapFunction(v),g},{}));var m={nodes:l,inputs:u,outputs:c,weights:s,placeholders:a,signature:e,functions:f};return o.length>0&&(m.initNodes=o),m},n.prototype.mapSignatureEntries=function(t){return Object.keys(t||{}).reduce(function(e,i){return e[t[i].name]=i,e},{})},n.prototype.mapNode=function(t){var e=$b(t.op)||this.opMappers[t.op]||{};t.attr==null&&(t.attr={});var i={name:t.name,op:t.op,category:e.category,inputNames:(t.input||[]).map(function(r){return r.startsWith("^")?r.substr(1):r}),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:t.attr};return e.inputs!=null&&(i.inputParams=e.inputs.reduce(function(r,a){return r[a.name]={type:a.type,inputIndexStart:a.start,inputIndexEnd:a.end},r},{})),e.attrs!=null&&(i.attrParams=e.attrs.reduce(function(r,a){var s=a.type,o=void 0;switch(a.type){case"string":o=$h(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=$h(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"string[]":o=id(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=id(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"number":o=Jh(t.attr,a.tfName,a.defaultValue||0),o===void 0&&!!a.tfDeprecatedName&&(o=Jh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"number[]":o=nd(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=nd(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool":o=Xh(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Xh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool[]":o=ad(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=ad(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape":o=td(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=td(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape[]":o=rd(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=rd(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype":o=Qh(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Qh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype[]":o=ed(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=ed(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"func":o=Xb(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Xb(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+a.type+" for op: "+t.op)}return r[a.name]={value:o,type:s},r},{})),i},n.prototype.mapFunction=function(t){var e=this,i=t.nodeDef,r=[],a=[],s={};i!=null&&(s=i.reduce(function(d,p){return d[p.name]=e.mapNode(p),p.op==="Const"&&a.push(d[p.name]),d},{}));var o=[],l=[];t.signature.inputArg.forEach(function(d){var p=Kn(d.name)[0],f={name:p,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Zh(d.type),type:"dtype"}},children:[]};f.signatureKey=d.name,o.push(f),s[p]=f});var u=Object.keys(s);u.forEach(function(d){var p=s[d];p.inputNames.forEach(function(f){var m=Kn(f)[0];p.inputs.push(s[m]),s[m].children.push(p)})});var c=t.ret;t.signature.outputArg.forEach(function(d){var p=Kn(c[d.name]),f=p[0],m=p[1],g=s[f];g!=null&&(g.defaultOutput=m,l.push(g))});var h=this.mapArgsToSignature(t);return{nodes:s,inputs:o,outputs:l,weights:a,placeholders:r,signature:h}},n.prototype.mapArgsToSignature=function(t){var e=this;return{methodName:t.signature.name,inputs:t.signature.inputArg.reduce(function(i,r){return i[r.name]=e.mapArgToTensorInfo(r),i},{}),outputs:t.signature.outputArg.reduce(function(i,r){return i[r.name]=e.mapArgToTensorInfo(r,t.ret),i},{})}},n.prototype.mapArgToTensorInfo=function(t,e){var i=t.name;return e!=null&&(i=e[i]),{name:i,dtype:t.type}},n}();function I4(n){var t=B.env().global;if(typeof t.atob!="undefined")return t.atob(n);if(typeof Buffer!="undefined")return new Buffer(n,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function Zb(n,t){var e=Array.isArray(n)?String.fromCharCode.apply(null,n):I4(n);return t?e:e.toLowerCase()}function $h(n,t,e,i){i===void 0&&(i=!1);var r=n[t];return r!=null?Zb(r.s,i):e}function Xh(n,t,e){var i=n[t];return i?i.b:e}function Jh(n,t,e){var i=n[t]||{},r=i.i!=null?i.i:i.f!=null?i.f:e;return typeof r=="number"?r:parseInt(r,10)}function Zh(n){typeof n=="string"&&(n=yn[n]);switch(n){case yn.DT_FLOAT:return"float32";case yn.DT_INT32:case yn.DT_INT64:case yn.DT_INT8:case yn.DT_UINT8:return"int32";case yn.DT_BOOL:return"bool";case yn.DT_DOUBLE:return"float32";case yn.DT_STRING:return"string";default:return null}}function Xb(n,t,e){var i=n[t];return i&&i.func?i.func.name:e}function Qh(n,t,e){var i=n[t];return i&&i.type?Zh(i.type):e}function ed(n,t,e){var i=n[t];return i&&i.list&&i.list.type?i.list.type.map(function(r){return Zh(r)}):e}function Qb(n){return n.unknownRank?void 0:n.dim!=null?n.dim.map(function(t){return typeof t.size=="number"?t.size:parseInt(t.size,10)}):[]}function td(n,t,e){var i=n[t];return i&&i.shape?Qb(i.shape):e}function nd(n,t,e){var i=n[t];return i?((i.list.f&&i.list.f.length?i.list.f:i.list.i)||[]).map(function(r){return typeof r=="number"?r:parseInt(r,10)}):e}function id(n,t,e,i){i===void 0&&(i=!1);var r=n[t];return r&&r.list&&r.list.s?r.list.s.map(function(a){return Zb(a,i)}):e}function rd(n,t,e){var i=n[t];return i&&i.list&&i.list.shape?i.list.shape.map(function(r){return Qb(r)}):e}function ad(n,t,e){var i=n[t];return i&&i.list&&i.list.b?i.list.b:e}var A4=function(){function n(t,e,i){var r=this;this.node=t,this.tensorMap=e,this.context=i,this.inputs=[],this.attrs={},this.inputs=t.inputNames.map(function(a){return r.getInput(a)}),t.rawAttrs!=null&&(this.attrs=Object.keys(t.rawAttrs).reduce(function(a,s){return a[s]=r.getAttr(s),a},{}))}return n.prototype.getInput=function(t){return Pt(t,this.tensorMap,this.context)},n.prototype.getAttr=function(t,e){var i=this.node.rawAttrs[t];if(i.tensor!=null)return Pt(t,this.tensorMap,this.context);if(i.i!=null||i.f!=null)return Jh(this.node.rawAttrs,t,e);if(i.s!=null)return $h(this.node.rawAttrs,t,e);if(i.b!=null)return Xh(this.node.rawAttrs,t,e);if(i.shape!=null)return td(this.node.rawAttrs,t,e);if(i.type!=null)return Qh(this.node.rawAttrs,t,e);if(i.list!=null){if(i.list.i!=null||i.list.f!=null)return nd(this.node.rawAttrs,t,e);if(i.list.s!=null)return id(this.node.rawAttrs,t,e);if(i.list.shape!=null)return rd(this.node.rawAttrs,t,e);if(i.list.b!=null)return ad(this.node.rawAttrs,t,e);if(i.list.type!=null)return ed(this.node.rawAttrs,t,e)}return e},n}();var T4=function(n,t,e){switch(n.op){case"BiasAdd":case"AddV2":case"Add":return[B.add(A("a",n,t,e),A("b",n,t,e))];case"AddN":return[B.addN(A("tensors",n,t,e))];case"FloorMod":case"Mod":return[B.mod(A("a",n,t,e),A("b",n,t,e))];case"Mul":return[B.mul(A("a",n,t,e),A("b",n,t,e))];case"RealDiv":case"Div":return[B.div(A("a",n,t,e),A("b",n,t,e))];case"DivNoNan":return[B.divNoNan(A("a",n,t,e),A("b",n,t,e))];case"FloorDiv":return[B.floorDiv(A("a",n,t,e),A("b",n,t,e))];case"Sub":return[B.sub(A("a",n,t,e),A("b",n,t,e))];case"Minimum":return[B.minimum(A("a",n,t,e),A("b",n,t,e))];case"Maximum":return[B.maximum(A("a",n,t,e),A("b",n,t,e))];case"Pow":return[B.pow(A("a",n,t,e),A("b",n,t,e))];case"SquaredDifference":return[B.squaredDifference(A("a",n,t,e),A("b",n,t,e))];default:throw TypeError("Node type "+n.op+" is not implemented")}};var N4=function(n,t,e){switch(n.op){case"Abs":case"ComplexAbs":return[B.abs(A("x",n,t,e))];case"Acos":return[B.acos(A("x",n,t,e))];case"Acosh":return[B.acosh(A("x",n,t,e))];case"Asin":return[B.asin(A("x",n,t,e))];case"Asinh":return[B.asinh(A("x",n,t,e))];case"Atan":return[B.atan(A("x",n,t,e))];case"Atan2":return[B.atan2(A("x",n,t,e),A("y",n,t,e))];case"Atanh":return[B.atanh(A("x",n,t,e))];case"Ceil":return[B.ceil(A("x",n,t,e))];case"Complex":return[B.complex(A("real",n,t,e),A("imag",n,t,e))];case"Cos":return[B.cos(A("x",n,t,e))];case"Cosh":return[B.cosh(A("x",n,t,e))];case"Elu":return[B.elu(A("x",n,t,e))];case"Erf":return[B.erf(A("x",n,t,e))];case"Exp":return[B.exp(A("x",n,t,e))];case"Expm1":return[B.expm1(A("x",n,t,e))];case"Floor":return[B.floor(A("x",n,t,e))];case"Log":return[B.log(A("x",n,t,e))];case"Log1p":return[B.log1p(A("x",n,t,e))];case"Imag":return[B.imag(A("x",n,t,e))];case"Neg":return[B.neg(A("x",n,t,e))];case"Reciprocal":return[B.reciprocal(A("x",n,t,e))];case"Real":return[B.real(A("x",n,t,e))];case"Relu":return[B.relu(A("x",n,t,e))];case"Round":return[B.round(A("x",n,t,e))];case"Selu":return[B.selu(A("x",n,t,e))];case"Sigmoid":return[B.sigmoid(A("x",n,t,e))];case"Sin":return[B.sin(A("x",n,t,e))];case"Sign":return[B.sign(A("x",n,t,e))];case"Sinh":return[B.sinh(A("x",n,t,e))];case"Softplus":return[B.softplus(A("x",n,t,e))];case"Sqrt":return[B.sqrt(A("x",n,t,e))];case"Square":return[B.square(A("x",n,t,e))];case"Tanh":return[B.tanh(A("x",n,t,e))];case"Tan":return[B.tan(A("x",n,t,e))];case"Relu6":case"ClipByValue":return[B.clipByValue(A("x",n,t,e),A("clipValueMin",n,t,e),A("clipValueMax",n,t,e))];case"Rsqrt":return[B.rsqrt(Pt(n.inputNames[0],t,e))];case"Prod":return[B.prod(A("x",n,t,e),A("axes",n,t,e))];case"LeakyRelu":return[B.leakyRelu(A("x",n,t,e),A("alpha",n,t,e))];case"Prelu":return[B.prelu(A("x",n,t,e),A("alpha",n,t,e))];default:throw TypeError("Node type "+n.op+" is not implemented")}};function on(n,t,e){e===void 0&&(e=""),B.util.assert(x4(n,t),function(){return e+(" Shapes "+n+" and "+t+" must match")})}function x4(n,t){if(n.length!==t.length)return!1;for(var e=0;e=this.size())throw new Error("Tried to read from index "+t+", but array size is: "+this.size());var e=this.tensors[t];if(e.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+t+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(e.cleared=!0),e.read=!0,e.tensor},n.prototype.readMany=function(t){var e=this;return t.map(function(i){return e.read(i)})},n.prototype.write=function(t,e){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(t<0||!this.dynamicSize&&t>=this.maxSize)throw new Error("Tried to write to index "+t+", but array is not resizeable and size is: "+this.maxSize);var i=this.tensors[t]||{};if(e.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+`,
+`+("2. The custom "+i+" is defined in JavaScript, ")+"but is not registered properly with tf.serialization.registerClass().");if(p!=null){for(var f={},m=0,g=Object.keys(an);mt?1:0}function ro(n,t){return-1*YD(n,t)}function hi(n){if(n==null)return n;for(var t=[],e=0,i=n;e=0),On(i>=e),Array.isArray(n)&&n.length>=e&&n.length<=i&&n.every(function(r){return typeof r===t})}function It(n,t){Array.isArray(n)?(y.util.assert(n.length>0,function(){return t+" is unexpectedly an empty array."}),n.forEach(function(e,i){return It(e,"element "+(i+1)+" of "+t)})):y.util.assert(Number.isInteger(n)&&n>0,function(){return"Expected "+t+" to be a positive integer, but got "+(Lv(n)+".")})}function Lv(n){return n===null?"null":Array.isArray(n)?"["+n.map(function(t){return Lv(t)}).join(",")+"]":typeof n=="string"?'"'+n+'"':""+n}function jD(n,t){var e=y.util.now(),i,r=function(){for(var a=[],s=0;s0){var e=n+"_"+t;return Br.set(e,1),e}else return n}var ak=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Dv(n){return!!n.match(ak)}function sk(n){return n===parseInt(n.toString(),10)}function di(n,t,e){t==null&&(t=0),e==null&&(e=n.length);for(var i=1,r=t;r= 2"+(" but got x shape = "+n.shape+" and y shape = "+t.shape));if(t.rank>=3){var r=n.shape.slice(-1)[0],a=t.shape.slice(-2)[0];if(r!==a)throw new Te("If rank y >= 3, then the second last dim"+(" of y must equal the last dim of x but got x shape = "+n.shape+" and ")+(" y shape = "+t.shape))}if(n.rank===2&&t.rank===2){var s=!1,o=!1;return y.fused.matMul({a:n,b:t,transposeA:s,transposeB:o,bias:i?hh(n.rank,i,dn()):null,activation:e})}else{var l=n.shape.slice(),u=l.pop();n=n.reshape([-1,u]);var c=t.shape.slice(),h=c.pop(),a=c.pop(),d=c.concat([h]),p=Array.from({length:t.rank},function(b,w){return w===0?t.rank-2:w<=t.rank-2?w-1:w});t=t.transpose(p).reshape([a,-1]);var f=l.concat(d),s=!1,o=!1;return y.fused.matMul({a:n,b:t,transposeA:s,transposeB:o,bias:i?hh(n.rank,i,dn()):null,activation:e}).reshape(f)}}function Bv(n,t,e){return y.tidy(function(){return Array.isArray(t)?t=y.tensor1d(t,"int32"):t=t.toInt(),y.gather(n,t,e)})}function Ba(n){return y.mul(n,n)}function hh(n,t,e){var i=t.shape;if(t.rank!==1&&t.rank!==n)throw new M("Unexpected bias dimensions: "+t.rank+("; expected it to be 1 or "+n));if(n===5){if(e==="channelsFirst")return i.length===1?t.reshape([1,i[0],1,1,1]):t.reshape([1,i[3],i[0],i[1],i[2]]);if(e==="channelsLast")return i.length===1?t.reshape([1,1,1,1,i[0]]):t.reshape([1].concat(i))}else if(n===4){if(e==="channelsFirst")return i.length===1?t.reshape([1,i[0],1,1]):t.reshape([1,i[2],i[0],i[1]]);if(e==="channelsLast")return i.length===1?t.reshape([1,1,1,i[0]]):t.reshape([1].concat(i))}else if(n===3){if(e==="channelsFirst")return i.length===1?t.reshape([1,i[0],1]):t.reshape([1,i[1],i[0]]);if(e==="channelsLast")return i.length===1?t.reshape([1,1,i[0]]):t.reshape([1].concat(i))}else if(n<3)return t;throw new M("Unsupported input rank by biasAdd: "+t.rank)}function Dn(n,t,e){return y.tidy(function(){return e==null&&(e=dn()),ut(e),n.add(hh(n.rank,t,e))})}function ck(n,t){if(t===void 0&&(t=1),t!==1)throw new Te("Support for alpha values other than 1 ("+t+") is not implemented yet.");return y.elu(n)}function hk(n){return y.tidy(function(){return y.div(n,y.abs(n).add(1))})}function zv(n,t,e,i){return y.tidy(function(){return y.dropout(n,t,e,i)})}function dk(n){return y.tidy(function(){var t=y.add(.5,y.mul(.2,n));return y.clipByValue(t,0,1)})}function za(n,t,e){return e===void 0&&(e=!1),e?n():t()}var pk=["fanIn","fanOut","fanAvg"],fk=["normal","uniform","truncatedNormal"];function mk(n){Ur(pk,"FanMode",n)}function gk(n){Ur(fk,"Distribution",n)}var sn=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.fromConfigUsesCustomObjects=function(){return!1},t.prototype.getConfig=function(){return{}},t}(y.serialization.Serializable),Pv=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.apply=function(e,i){return y.zeros(e,i)},t.className="Zeros",t}(sn);y.serialization.registerClass(Pv);var dh=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.apply=function(e,i){return y.ones(e,i)},t.className="Ones",t}(sn);y.serialization.registerClass(dh);var _v=function(n){Q(t,n);function t(e){var i=n.call(this)||this;if(typeof e!="object")throw new M("Expected argument of type ConstantConfig but got "+e);if(e.value===void 0)throw new M("config must have value set but got "+e);return i.value=e.value,i}return t.prototype.apply=function(e,i){var r=this;return y.tidy(function(){return y.mul(y.scalar(r.value),y.ones(e,i))})},t.prototype.getConfig=function(){return{value:this.value}},t.className="Constant",t}(sn);y.serialization.registerClass(_v);var Mv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.DEFAULT_MINVAL=-.05,i.DEFAULT_MAXVAL=.05,i.minval=e.minval||i.DEFAULT_MINVAL,i.maxval=e.maxval||i.DEFAULT_MAXVAL,i.seed=e.seed,i}return t.prototype.apply=function(e,i){return y.randomUniform(e,this.minval,this.maxval,i)},t.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},t.className="RandomUniform",t}(sn);y.serialization.registerClass(Mv);var Hv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.DEFAULT_MEAN=0,i.DEFAULT_STDDEV=.05,i.mean=e.mean||i.DEFAULT_MEAN,i.stddev=e.stddev||i.DEFAULT_STDDEV,i.seed=e.seed,i}return t.prototype.apply=function(e,i){if(i=i||"float32",i!=="float32"&&i!=="int32")throw new Te("randomNormal does not support dType "+i+".");return so(e,this.mean,this.stddev,i,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="RandomNormal",t}(sn);y.serialization.registerClass(Hv);var Vv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.DEFAULT_MEAN=0,i.DEFAULT_STDDEV=.05,i.mean=e.mean||i.DEFAULT_MEAN,i.stddev=e.stddev||i.DEFAULT_STDDEV,i.seed=e.seed,i}return t.prototype.apply=function(e,i){if(i=i||"float32",i!=="float32"&&i!=="int32")throw new Te("truncatedNormal does not support dType "+i+".");return y.truncatedNormal(e,this.mean,this.stddev,i,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="TruncatedNormal",t}(sn);y.serialization.registerClass(Vv);var qv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.gain=e.gain!=null?e.gain:1,i}return t.prototype.apply=function(e,i){var r=this;return y.tidy(function(){if(e.length!==2||e[0]!==e[1])throw new M("Identity matrix initializer can only be used for 2D square matrices.");return y.mul(r.gain,y.eye(e[0]))})},t.prototype.getConfig=function(){return{gain:this.gain}},t.className="Identity",t}(sn);y.serialization.registerClass(qv);function vk(n,t){t===void 0&&(t="channelsLast");var e,i;if(ut(t),n.length===2)e=n[0],i=n[1];else if([3,4,5].indexOf(n.length)!==-1){if(t==="channelsFirst"){var r=di(n,2);e=n[1]*r,i=n[0]*r}else if(t==="channelsLast"){var r=di(n,0,n.length-2);e=n[n.length-2]*r,i=n[n.length-1]*r}}else{var a=di(n);e=Math.sqrt(a),i=Math.sqrt(a)}return[e,i]}var qt=function(n){Q(t,n);function t(e){var i=n.call(this)||this;if(e.scale<0)throw new M("scale must be a positive float. Got: "+e.scale);return i.scale=e.scale==null?1:e.scale,i.mode=e.mode==null?"fanIn":e.mode,mk(i.mode),i.distribution=e.distribution==null?"normal":e.distribution,gk(i.distribution),i.seed=e.seed,i}return t.prototype.apply=function(e,i){var r=vk(e),a=r[0],s=r[1],o=this.scale;if(this.mode==="fanIn"?o/=Math.max(1,a):this.mode==="fanOut"?o/=Math.max(1,s):o/=Math.max(1,(a+s)/2),this.distribution==="normal"){var l=Math.sqrt(o);if(i=i||"float32",i!=="float32"&&i!=="int32")throw new Te(this.getClassName()+" does not support dType "+i+".");return y.truncatedNormal(e,0,l,i,this.seed)}else{var u=Math.sqrt(3*o);return y.randomUniform(e,-u,u,i)}},t.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},t.className="VarianceScaling",t}(sn);y.serialization.registerClass(qt);var ph=function(n){Q(t,n);function t(e){return n.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return qt.className},t.className="GlorotUniform",t}(qt);y.serialization.registerClass(ph);var fh=function(n){Q(t,n);function t(e){return n.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return qt.className},t.className="GlorotNormal",t}(qt);y.serialization.registerClass(fh);var mh=function(n){Q(t,n);function t(e){return n.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return qt.className},t.className="HeNormal",t}(qt);y.serialization.registerClass(mh);var gh=function(n){Q(t,n);function t(e){return n.call(this,{scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return qt.className},t.className="HeUniform",t}(qt);y.serialization.registerClass(gh);var vh=function(n){Q(t,n);function t(e){return n.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return qt.className},t.className="LeCunNormal",t}(qt);y.serialization.registerClass(vh);var yh=function(n){Q(t,n);function t(e){return n.call(this,{scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return qt.className},t.className="LeCunNormal",t}(qt);y.serialization.registerClass(yh);var Gv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;if(i.DEFAULT_GAIN=1,i.gain=e.gain==null?i.DEFAULT_GAIN:e.gain,i.seed=e.seed,i.seed!=null)throw new Te("Random seed is not implemented for Orthogonal Initializer yet.");return i}return t.prototype.apply=function(e,i){var r=this;return y.tidy(function(){if(e.length<2)throw new Te("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more "+("than 2000 ("+e[0]*e[1]+") elements: ")+"Slowness may result.");var a=e[0]>e[1]?[e[1],e[0]]:e,s=so(a,0,1,"float32"),o=y.linalg.gramSchmidt(s);return e[0]>e[1]&&(o=o.transpose()),y.mul(r.gain,o)})},t.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},t.className="Orthogonal",t}(sn);y.serialization.registerClass(Gv);var Yv={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function Kv(n,t){return t===void 0&&(t={}),Da(n,y.serialization.SerializationMap.getMap().classNameMap,t,"initializer")}function at(n){return rh(n)}function et(n){if(typeof n=="string"){var t=n in Yv?Yv[n]:n;if(t==="GlorotNormal")return new fh;if(t==="GlorotUniform")return new ph;if(t==="HeNormal")return new mh;if(t==="HeUniform")return new gh;if(t==="LeCunNormal")return new vh;if(t==="LeCunUniform")return new yh;var e={};return e.className=t,e.config={},Kv(e)}else return n instanceof sn?n:Kv(n)}function yk(){return new Pv}function bk(){return new dh}function wk(n){return new _v(n)}function Sk(n){return new Mv(n)}function Lk(n){return new Hv(n)}function Ik(n){return new Vv(n)}function Ak(n){return new qv(n)}function Tk(n){return new qt(n)}function Nk(n){return new ph(n)}function xk(n){return new fh(n)}function Ck(n){return new mh(n)}function Rk(n){return new gh(n)}function Ok(n){return new vh(n)}function Ek(n){return new yh(n)}function Dk(n){return new Gv(n)}var kk={__proto__:null,zeros:yk,ones:bk,constant:wk,randomUniform:Sk,randomNormal:Lk,truncatedNormal:Ik,identity:Ak,varianceScaling:Tk,glorotUniform:Nk,glorotNormal:xk,heNormal:Ck,heUniform:Rk,leCunNormal:Ok,leCunUniform:Ek,orthogonal:Dk};var Fk=0;function jv(){return Fk++}var oo={};function lo(n){return n===void 0&&(n=""),n in oo||(oo[n]=0),oo[n]+=1,n+oo[n].toString()}function bh(n){return Array.isArray(n)&&Array.isArray(n[0])}function uo(n){return n.length===0?[]:Array.isArray(n[0])?n:[n]}function xe(n){var t;if(Array.isArray(n)){if(n.length!==1)throw new M("Expected Tensor length to be 1; got "+n.length);t=n[0]}else t=n;return t}function Ye(n){if(Array.isArray(n)&&Array.isArray(n[0])){if(n.length===1)return n=n,n[0];throw new M("Expected exactly 1 Shape; got "+n.length)}else return n}function co(n){for(var t=0,e=0,i=n;e1)throw new ci("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `getInputAt(nodeIndex)` instead.');if(this.inboundNodes.length===0)throw new ci("Layer "+this.name+" is not connected, no input to return.");return zt(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){if(this.inboundNodes.length===0)throw new ci("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new ci("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return zt(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),t.prototype.calculateLosses=function(){return this.losses.map(function(e){return e()})},Object.defineProperty(t.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"built",{get:function(){return this._built},set:function(e){this._built=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainable",{get:function(){return this.trainable_},set:function(e){this._trainableWeights.forEach(function(i){return i.trainable=e}),this.trainable_=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable_?this._trainableWeights.filter(function(e){return e.trainable}):[]},set:function(e){this._trainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this._trainableWeights.filter(function(e){return!e.trainable}).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)},set:function(e){this._nonTrainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),t.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},t.prototype.assertInputCompatibility=function(e){if(e=Xe(e),this.inputSpec==null||this.inputSpec.length===0)return;var i=Xe(this.inputSpec);if(e.length!==i.length)throw new M("Layer "+this.name+" expects "+i.length+" inputs, "+("but it received "+e.length+" input tensors. ")+("Input received: "+e));for(var r=0;r=0?l[c]:l[l.length+c];if(h!=null&&[h,null].indexOf(d)===-1)throw new M("Input "+r+" is incompatible with layer "+(this.name+": expected axis "+c+" of input shape to ")+("have value "+h+" but got shape "+l+"."))}}if(s.shape!=null)for(var p=0;p0&&Array.isArray(R[0])?v=R.map(function(W,F){return new fn(D,W,r,Xe(e),i,r.name,F)}):v=new fn(D,R,r,Xe(e),i,r.name),r.addInboundNode(e,v,null,null,C,R,i),r._refCount++,r.activityRegularizer!=null)throw new Te("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return v}})},t.prototype.warnOnIncompatibleInputShape=function(e){if(this.batchInputShape==null)return;if(e.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+(JSON.stringify(e)+") does not match that of the ")+("batchInputShape ("+JSON.stringify(this.batchInputShape)+") ")+("of the layer "+this.name));else{var i=!1;this.batchInputShape.forEach(function(r,a){r!=null&&e[a]!=null&&e[a]!==r&&(i=!0)}),i&&console.warn("The shape of the input tensor "+("("+JSON.stringify(e)+") does not ")+("match the expectation of layer "+this.name+": ")+(""+JSON.stringify(this.batchInputShape)))}},Object.defineProperty(t.prototype,"outputShape",{get:function(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new ci("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var e=[],i=0,r=this.inboundNodes;i0)&&(t=n.sourceLayer,e=n.nodeIndex),t.inboundNodes.length===0)return[n];var i=t.inboundNodes[e];if(i.inboundLayers.length===0)return i.inputTensors;for(var r=[],a=0;a0?[4,Promise.all(t)]:[3,2];case 1:for(o=u.sent(),l=0;l=0&&Number.isInteger(t),function(){return"Verbosity level is expected to be an integer >= 0, "+("but got "+t)}),n.checkForDuplicate(e),n.constructors[t]==null&&(n.constructors[t]=[]),n.constructors[t].push(e)},n.checkForDuplicate=function(t){for(var e in n.constructors){var i=n.constructors[+e];i.forEach(function(r){if(r===t)throw new M("Duplicate callback constructor.")})}},n.clear=function(){n.constructors={}},n.createCallbacks=function(t){var e=[];for(var i in n.constructors){var r=+i;t>=r&&e.push.apply(e,n.constructors[r])}return e.map(function(a){return new a})},n.constructors={},n}();function sy(n,t,e,i,r,a,s,o,l){var u=new ny,c=[new Mk].concat(ay.createCallbacks(t));n!=null&&c.push.apply(c,n),c.push(u);var h=new ty(c);return h.setParams({epochs:e,initialEpoch:i,samples:r,steps:a,batchSize:s,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:u}}function mn(n,t,e){return t===void 0&&(t={}),e===void 0&&(e=!1),Da(n,y.serialization.SerializationMap.getMap().classNameMap,t,"layer",e)}function po(n,t){return y.tidy(function(){n.dtype!=="float32"&&(n=n.asType("float32"));var e=y.sum(Ba(n),t,!0),i=y.fill(e.shape,gt()),r=y.sqrt(y.maximum(e,i));return y.div(n,r)})}function Ji(n,t){return y.tidy(function(){return y.mean(Ba(y.sub(t,n)),-1)})}function fo(n,t){return y.tidy(function(){return y.mean(y.abs(y.sub(t,n)),-1)})}function _r(n,t){return y.tidy(function(){var e=y.sub(n,t),i=y.clipByValue(y.abs(n),gt(),Number.MAX_VALUE),r=y.abs(y.div(e,i));return y.mul(100,y.mean(r,-1))})}function Hk(n,t){return y.tidy(function(){var e=y.clipByValue(t,gt(),Number.MAX_VALUE),i=y.log(y.add(1,e)),r=y.clipByValue(n,gt(),Number.MAX_VALUE),a=y.log(y.add(1,r));return y.mean(Ba(y.sub(i,a)),-1)})}function Vk(n,t){return y.tidy(function(){var e=y.maximum(0,y.sub(1,y.mul(n,t)));return y.mean(Ba(e),-1)})}function qk(n,t){return y.tidy(function(){var e=y.maximum(0,y.sub(1,y.mul(n,t)));return y.mean(e,-1)})}function Gk(n,t){return y.tidy(function(){var e=y.sum(y.mul(n,t),-1),i=y.max(y.mul(y.sub(1,n),t),-1);return y.maximum(0,y.add(1,y.sub(i,e)))})}function Yk(n,t){return y.tidy(function(){var e=Math.log(2),i=y.sub(t,n),r=y.sub(y.add(i,y.softplus(y.mul(-2,i))),e);return y.mean(r,-1)})}function _a(n,t,e){return e===void 0&&(e=!1),y.tidy(function(){if(e)t=y.softmax(t);else{var i=y.sum(t,t.shape.length-1,!0);t=y.div(t,i)}return t=y.clipByValue(t,gt(),1-gt()),y.neg(y.sum(y.mul(n.toFloat(),y.log(t)),t.shape.length-1))})}function mo(n,t,e){return e===void 0&&(e=!1),y.tidy(function(){var i=y.floor(lk(n)).toInt();t=y.clipByValue(t,gt(),1-gt());var r=t.shape,a=y.oneHot(i,r[r.length-1]).reshape(r);return _a(a,t,e)})}function Kk(n,t){if(!y.util.arraysEqual(n.shape,t.shape))throw new M("logits and labels must have the same shape, but got shapes "+(JSON.stringify(n.shape)+" and "+JSON.stringify(t.shape)));return y.tidy(function(){var e=t.relu(),i=t.abs().neg();return e.sub(t.mul(n)).add(i.exp().log1p())})}function go(n,t){return y.tidy(function(){var e;return e=y.clipByValue(t,gt(),1-gt()),e=y.log(y.div(e,y.sub(1,e))),y.mean(Kk(n,e),-1)})}function jk(n,t){return y.tidy(function(){var e=y.clipByValue(n,gt(),1),i=y.clipByValue(t,gt(),1);return y.sum(y.mul(n,y.log(y.div(e,i))),-1)})}function $k(n,t){return y.tidy(function(){var e=y.log(y.add(gt(),t));return y.mean(y.sub(t,y.mul(n,e)),-1)})}function Lh(n,t){return y.tidy(function(){var e=po(n,-1),i=po(t,-1),r=y.mul(e,i);return y.neg(y.sum(r,-1))})}var vo={meanSquaredError:Ji,meanAbsoluteError:fo,meanAbsolutePercentageError:_r,meanSquaredLogarithmicError:Hk,squaredHinge:Vk,hinge:qk,categoricalHinge:Gk,logcosh:Yk,categoricalCrossentropy:_a,sparseCategoricalCrossentropy:mo,binaryCrossentropy:go,kullbackLeiblerDivergence:jk,poisson:$k,cosineProximity:Lh};function Ih(n){if(typeof n=="string"){if(n in vo)return vo[n];var t="Unknown loss "+n;throw n.toLowerCase().includes("softmaxcrossentropy")&&(t="Unknown loss "+n+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'),new M(t)}else return n}function Ah(n,t){return y.tidy(function(){var e=y.mul(.5,y.onesLike(t)),i=Wa(y.greater(t,e),n.dtype);return y.mean(y.equal(n,i),-1)})}function Th(n,t){return y.tidy(function(){return Wa(y.equal(y.argMax(n,-1),y.argMax(t,-1)),"float32")})}function oy(n,t){return y.tidy(function(){return y.logicalAnd(n.equal(1),t.equal(1)).sum().cast("float32")})}function Xk(n,t){return y.tidy(function(){return y.logicalAnd(n.equal(1),t.equal(0)).sum().cast("float32")})}function Jk(n,t){return y.tidy(function(){return y.logicalAnd(n.equal(0),t.equal(1)).sum().cast("float32")})}function ly(n,t){return y.tidy(function(){var e=oy(n,t),i=Jk(n,t),r=e.add(i);return y.where(y.greater(r,0),e.div(r),0).cast("float32")})}function Zk(n,t){return y.tidy(function(){var e=oy(n,t),i=Xk(n,t),r=e.add(i);return y.where(y.greater(r,0),e.div(r),0).cast("float32")})}function uy(n,t){return go(n,t)}function cy(n,t){return n.rank===t.rank&&(n=n.squeeze([n.rank-1])),t=t.argMax(-1),t.dtype!==n.dtype&&(t=t.asType(n.dtype)),y.equal(n,t).asType("float32")}var Qk=Ji,e3=Ji,t3=fo,n3=fo,i3=_r,r3=_r,Nh=_a,a3=Lh,hy=mo,yo={binaryAccuracy:Ah,categoricalAccuracy:Th,precision:ly,categoricalCrossentropy:Nh,sparseCategoricalCrossentropy:hy,mse:Qk,MSE:e3,mae:t3,MAE:n3,mape:i3,MAPE:r3,cosine:a3};function s3(n){if(typeof n=="string"&&n in yo)return yo[n];if(typeof n!="string"&&n!=null)return n;throw new M("Unknown metric "+n)}function bo(n){if(On(n!==null,"Unknown LossOrMetricFn "+n),typeof n=="string")return n;for(var t=void 0,e=0,i=Object.keys(vo);edy&&console.warn('User-defined metadata of model "'+t+'" is too large in '+("size (length="+i.length+" when serialized). It is not ")+"recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= "+(dy+"."))}}function xh(n){if(n===null)return!0;if(typeof n=="object")if(Object.getPrototypeOf(n)===Object.prototype){for(var t=Object.keys(n),e=0,i=t;e1||o.length===1&&o[0].inboundLayers.length>1){t=!1;break}i.push.apply(i,o)}if(t)for(var l=0,u=n.layers;l0&&(i=i.slice(0,i.length-1)+" "),i+=n[r],i=i.slice(0,t[r]),i+=" ".repeat(t[r]-i.length);e(i)}function c3(n,t,e){var i;try{i=JSON.stringify(n.outputShape)}catch(o){i="multiple"}var r=n.name,a=n.getClassName(),s=[r+" ("+a+")",i,n.countParams().toString()];wo(s,t,e)}function h3(n,t,e,i){var r;try{r=JSON.stringify(n.outputShape)}catch(v){r="multiple"}for(var a=[],s=0,o=n.inboundNodes;s0&&e.indexOf(l)===-1)continue;for(var u=0;ui.maxNumTensors&&(i.maxNumTensors=w),w0,function(){return"Expected at least one fetch, got none"});var e=[],i={};if(n.length===1){var r=gy(n[0],t);e=r.sorted,i=r.recipientMap}else for(var a=new Set,s=0,o=n;s0;){var c=l[l.length-1];if(e.has(c.name)){l.pop();continue}var h=u[u.length-1]===l.length-1;if(c.inputs.length===0||h)l.pop(),i.push(c),e.add(c.name),h&&u.pop();else{u.push(l.length-1);for(var d=0,p=c.inputs;d1 nodes"),On(c===0,"input layer has >1 tensors"),i.inputLayers.push(l),i.inputLayersNodeIndices.push(u),i.inputLayersTensorIndices.push(c)}i.inputNames=[],i.outputNames=[],i.feedInputShapes=[],i.feedInputNames=[],i.feedOutputNames=[];for(var p=0;p=0;)dt.splice(dt.indexOf(Ft),1);L.push(Ft)},C=[],R=[],D=0,k=i.outputs;Dnn?1:0});for(var he=0,be=le;he0)throw new M("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];for(var e=[],i=0,r=this.layers;i0)throw new M(v.length+" of "+a+" weights are not set: "+(""+v))}Sh(d)},t.prototype.updatedConfig=function(){var e=this.getConfig(),i={};return i.className=this.getClassName(),i.config=e,i.kerasVersion="tfjs-layers "+Rh,i.backend="TensorFlow.js",i},t.prototype.toJSON=function(e,i){i===void 0&&(i=!0);var r=Ch(this.updatedConfig());return i?JSON.stringify(r):r},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){e=Xe(e);for(var a=new Mr,s=0;s1)for(var c=0,h=u;c0){for(var m=[],g=0;g0&&G.apply(zt(X),ee)}function c(G){var Z=G.name,X=mn(G,i.customObjects!=null?i.customObjects:{});X.setFastWeightInitDuringBuild(a),s[Z]=X;var ee=G.inboundNodes;ee.forEach(function(ne){if(!(ne instanceof Array))throw new M("Corrupted configuration, expected array for nodeData: "+ne);l(X,ne)})}for(var h=i.name,d=i.layers,p=0,f=d;p0&&typeof n[Object.keys(n)[0]]=="object"){var r=[];return t.forEach(function(a){a in n?r.push(n[a]):r.push(null)}),r}else throw new Error("The model has multiple ("+i+") outputs, "+("so "+e+" must be either an array with ")+(i+" elements or an object with "+t+" keys. ")+("Provided "+e+" not understood: "+JSON.stringify(n)))}function vy(n,t){return y3(n,t,"classWeight")}function yy(n,t,e,i){return Le(this,void 0,void 0,function(){var r,a,s,o,l;return ye(this,function(u){switch(u.label){case 0:if(t!=null||i!=null)throw new Error("Support sampleWeight is not implemented yet");return e!=null?(r=y.tidy(function(){if(n.shape.length===1)return n.clone();if(n.shape.length===2)if(n.shape[1]>1){var c=1;return n.argMax(c)}else{if(n.shape[1]===1)return n.reshape([n.shape[0]]);throw new Error("Encountered unexpected last-dimension size ("+n.shape[1]+") during handling of class weights. The size is expected to be >= 1.")}else throw new Error("Unexpected rank of target (y) tensor ("+n.rank+") during handling of class weights. The rank is expected to be 1 or 2.")}),o=(s=Array).from,[4,r.data()]):[3,2];case 1:return a=o.apply(s,[u.sent()]),y.dispose(r),l=[],a.forEach(function(c){if(e[c]==null)throw new Error("classWeight must contain all classes in the training data. "+("The class "+c+" exists in the data but not in ")+"classWeight");l.push(e[c])}),[2,y.tensor1d(l,"float32")];case 2:return[2,null]}})})}function b3(n,t){return y.mul(n,t)}var w3=32;function wy(n,t){var e,i,r=t;e=r.xs,i=r.ys,y.util.assert(e!=null&&i!=null,function(){return"A Dataset iterator for fitDataset() is expected to generate objects of the form `{xs: xVal, ys: yVal}`, where the two values may be `tf.Tensor`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates "+(""+t)});var a=by("input",n.inputNames,e),s=by("output",n.outputNames,i),o=a[0].shape[0];y.util.assert(a.length===n.inputs.length,function(){return"LayersModel has "+n.inputs.length+" inputs, but the dataset "+("provides "+a.length+" inputs. (Expected input keys: ")+(JSON.stringify(n.inputNames)+")")}),y.util.assert(s.length===n.outputs.length,function(){return"LayersModel has "+n.outputs.length+" outputs, but the dataset "+("provides "+s.length+" outputs. (Expected output keys: ")+(JSON.stringify(n.outputNames)+")")});for(var l=function(d){y.util.assert(a[d].shape[0]===o,function(){return"Batch size mismatch: input "+(n.inputNames[d]+" has "+a[d].shape[0]+"; ")+("expected "+o+" based on input "+n.inputNames[0]+".")})},u=0;u0&&Number.isInteger(e.epochs),function(){return"For fitDataset(), config.epochs is expected to be a positive "+("integer, but got "+e.epochs)}),y.util.assert(!i||e.batchesPerEpoch>0&&Number.isInteger(e.batchesPerEpoch),function(){return"For fitDataset(), config.batchesPerEpoch is expected to be a "+("positive integer if specified, but got "+e.batchesPerEpoch)}),y.util.assert(e.validationSplit==null,function(){return"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."}),n.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");n.isTraining=!0,X.label=1;case 1:return X.trys.push([1,,26,27]),r=e.validationData!=null,a=void 0,s=void 0,r&&(Sy(e.validationData)?y.util.assert(e.validationBatches==null||e.validationBatches>0&&Number.isInteger(e.validationBatches),function(){return"For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, "+("but got "+e.validationBatches)}):(o=S3(e.validationData),a=o.xs,s=o.ys)),l=n.makeTrainFunction(),u=n.getDedupedMetricsNames(),c=void 0,r?c=u.slice().concat(u.map(function(ee){return"val_"+ee})):c=u.slice(),h=ry(e.callbacks,e.yieldEvery),d=e.verbose==null?1:e.verbose,p=sy(h,d,e.epochs,null,null,L3(t,e),null,r,c),f=p.callbackList,m=p.history,f.setModel(n),n.history=m,[4,f.onTrainBegin()];case 2:return X.sent(),n.stopTraining_=!1,g=e.initialEpoch==null?0:e.initialEpoch,[4,t.iterator()];case 3:v=X.sent(),X.label=4;case 4:return g=e.batchesPerEpoch:L.done)?r?(G=void 0,Sy(e.validationData)?(Z=Xe,[4,n.evaluateDataset(e.validationData,{batches:e.validationBatches})]):[3,17]):[3,19]:[3,20];case 16:return G=Z.apply(void 0,[X.sent()]),[3,18];case 17:G=Xe(n.evaluate(a,s,{batchSize:e.validationBatchSize==null?w3:e.validationBatchSize,verbose:0})),X.label=18;case 18:for(F=0;F0)throw new Te("Verbose mode is not implemented yet.");return y.util.assert(!i||e.batches>0&&Number.isInteger(e.batches),function(){return"Test loop expects `batches` to be a positive integer, but "+("received "+JSON.stringify(e.batches))}),A3(t)?(o=t,[3,3]):[3,1];case 1:return[4,t.iterator()];case 2:o=f.sent(),f.label=3;case 3:s=o,l=0,u=0,c=function(){var m;return ye(this,function(g){switch(g.label){case 0:return[4,s.next()];case 1:return m=g.sent(),a=y.tidy(function(){if(m.value){var v=wy(n,m.value),b=v.xs,w=v.ys,S=b.concat(w),L=y.tidy(function(){return r(S)});if(y.dispose(S),u===0)for(var x=0;x0&&y.dispose(W)},x=0;x0&&Number.isInteger(n),function(){return"batchSize is required to be a positive integer, but got "+n})}function Va(n,t,e){return n==null?[null]:Array.isArray(n)?n.map(function(i){return Xi(i,t,e-t)}):Xi(n,t,e-t)}function Dh(n,t){return y.tidy(function(){return n==null?null:Array.isArray(n)?n.map(function(e){return Dh(e,t)}):Bv(n,t.dtype==="int32"?t:t.toInt())})}function kh(n,t){for(var e=[],i=0,r=null;i=n&&(r=n),e.push([i,r]),i=r;return e}function N3(n,t,e,i,r,a,s,o,l,u,c,h,d,p,f){return Le(this,void 0,void 0,function(){var m,g,v,b,w,S,L,x,C;return ye(this,function(R){switch(R.label){case 0:if(r==null&&(r=32),a==null&&(a=1),c==null&&(c=!0),d==null&&(d=0),m=!1,l!=null&&u!=null&&(m=!0),f!=null&&(m=!0,p==null))throw new M("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return g=n.checkNumSamples(e,r,p,"steps_per_epoch"),g!=null&&(v=pn(0,g)),s==null&&(s=1),b=sy(o,s,a,d,g,p,r,m,h),w=b.callbackList,S=b.history,w.setModel(n),n.history=S,[4,w.onTrainBegin()];case 1:R.sent(),n.stopTraining_=!1,L=function(D){var k,W,F,P,H,_;return ye(this,function(K){switch(K.label){case 0:return[4,w.onEpochBegin(D)];case 1:if(K.sent(),k={},!(p!=null))return[3,2];throw new Te("stepsPerEpoch mode is not implemented yet.");case 2:if(c==="batch")throw new Te("batch shuffling is not implemneted yet");c&&y.util.shuffle(v),W=y.tensor1d(v),F=kh(g,r),P=function(j){var q;return ye(this,function(G){switch(G.label){case 0:return q={},[4,w.onBatchBegin(j,q)];case 1:return G.sent(),y.tidy(function(){var Z=F[j][0],X=F[j][1],ee=Xi(W,Z,X-Z);q.batch=j,q.size=X-Z;for(var ne=Dh(e,ee),ie=t(ne),te=0;te0))return[3,4];if(f=!0,i.validationData.length===2)s=i.validationData[0],o=i.validationData[1];else throw i.validationData.length===3?new Te("validationData including sample weights is not supported yet."):new M("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+(i.validationData+" is invalid."));return g=!0,[4,n.standardizeUserData(s,o,null,null,g,h)];case 3:return v=W.sent(),l=v[0],u=v[1],m=l.concat(u),[3,5];case 4:i.validationSplit!=null&&i.validationSplit>0&&i.validationSplit<1?(f=!0,b=Math.floor(r[0].shape[0]*(1-i.validationSplit)),w=r[0].shape[0],l=Va(r,b,w),r=Va(r,0,b),u=Va(a,b,w),a=Va(a,0,b),m=l.concat(u)):i.validationSteps!=null&&(f=!0),W.label=5;case 5:return S=r.concat(a).concat(c),n.checkTrainableWeightsConsistency(),L=n.makeTrainFunction(),x=n.getDedupedMetricsNames(),C=void 0,R=void 0,f?(n.makeTestFunction(),C=n.testFunction,R=x.slice().concat(x.map(function(F){return"val_"+F}))):(C=null,m=[],R=x.slice()),D=ry(i.callbacks,i.yieldEvery),[4,N3(n,L,S,x,h,i.epochs,i.verbose,D,C,m,i.shuffle,R,i.initialEpoch,null,null)];case 6:return k=W.sent(),[2,k];case 7:return n.isTraining=!1,Zi(r,t),Zi(a,e),Zi(l,s),Zi(u,o),c!=null&&y.dispose(c),[7];case 8:return[2]}})})}function Ly(n){var t=[];n instanceof y.Tensor&&(n=[n]);for(var e=0;e0)a=!0;else if(Iy(n)){for(var s in n)if(n.hasOwnProperty(s)){a=!0;break}}else a=!0;if(a)throw new M("Error when checking model "+r+" expected no data, "+("but got "+n))}return[]}if(n==null)return t.map(function(g){return null});var o;if(Iy(n)){n=n,o=[];for(var l=0,u=t;l