* * @returns {Function}
()
| 934 | * @returns {Function} |
| 935 | */ |
| 936 | toFunction() { |
| 937 | const activation = this.activation; |
| 938 | const leakyReluAlpha = this.leakyReluAlpha; |
| 939 | let needsVar = false; |
| 940 | function nodeHandle(layers, layerNumber, nodeKey) { |
| 941 | if (layerNumber === 0) { |
| 942 | return (typeof nodeKey === 'string' |
| 943 | ? `input['${nodeKey}']` |
| 944 | : `input[${nodeKey}]`); |
| 945 | } |
| 946 | |
| 947 | const layer = layers[layerNumber]; |
| 948 | const node = layer[nodeKey]; |
| 949 | let result = ['(' , node.bias]; |
| 950 | for (let w in node.weights) { |
| 951 | if (node.weights[w] < 0) { |
| 952 | result.push(`${node.weights[w]}*${nodeHandle(layers, layerNumber - 1, w)}`); |
| 953 | } else { |
| 954 | result.push(`+${node.weights[w]}*${nodeHandle(layers, layerNumber - 1, w)}`); |
| 955 | } |
| 956 | } |
| 957 | result.push(')'); |
| 958 | |
| 959 | switch (activation) { |
| 960 | case 'sigmoid': |
| 961 | return `1/(1+1/Math.exp(${result.join('')}))`; |
| 962 | case 'relu': { |
| 963 | needsVar = true; |
| 964 | return `((v=${result.join('')})<0?0:v)`; |
| 965 | } |
| 966 | case 'leaky-relu': { |
| 967 | needsVar = true; |
| 968 | return `((v=${result.join('')})<0?0:${leakyReluAlpha}*v)`; |
| 969 | } |
| 970 | case 'tanh': |
| 971 | return `Math.tanh(${result.join('')})`; |
| 972 | default: |
| 973 | throw new Error('unknown activation type ' + activation); |
| 974 | } |
| 975 | } |
| 976 | |
| 977 | const layers = this.toJSON().layers; |
| 978 | const layersAsMath = []; |
| 979 | let result; |
| 980 | for (let i in layers[layers.length - 1]) { |
| 981 | layersAsMath.push(nodeHandle(layers, layers.length - 1, i)); |
| 982 | } |
| 983 | if (this.outputLookup) { |
| 984 | result = `{${ |
| 985 | Object.keys(this.outputLookup) |
| 986 | .map((key, i) => `'${key}':${layersAsMath[i]}`) |
| 987 | }}`; |
| 988 | } else { |
| 989 | result = `[${layersAsMath.join(',')}]`; |
| 990 | } |
| 991 | |
| 992 | return new Function('input', `${ needsVar ? 'var v;' : '' }return ${result};`); |
| 993 | } |
nothing calls this directly
no test coverage detected