WebNN with Synaptic js Going to build and train a neworking using synaptic js we ll then save the result trained network values we ll then load the network values and build a WebNN network setup the weights biases Synatpic js XOR network build the network train it and save the weights biases etc to a json file Store in local storage so it can be accessed in the next step let sp await fetch https cdnjs cloudflare com ajax libs synaptic 1 1 4 synaptic js let st await sp text let synapticlibrary document createElement script synapticlibrary innerHTML st document body appendChild synapticlibrary const Layer Network Trainer synaptic Create the layers const inputLayer new Layer 2 const hiddenLayer new Layer 3 const outputLayer new Layer 1 Connect the layers inputLayer project hiddenLayer hiddenLayer project outputLayer Create the network const myNetwork new Network input inputLayer hidden hiddenLayer output outputLayer Training data const trainingSet input 0 0 output 0 input 0 1 output 1 input 1 0 output 1 input 1 1 output 0 Train the network const trainer new Trainer myNetwork trainer train trainingSet rate 0 2 iterations 20000 error 0 005 shuffle true log 1000 cost Trainer cost CROSS_ENTROPY Get the trained network JSON const trainedNetworkJSON myNetwork toJSON console log trainedNetworkJSON Save the trained network JSON for later use localStorage setItem trainedXORNetwork JSON stringify trainedNetworkJSON console log finished building training and saving xor using synaptic js This is whaat the json file looks like that we saved out from the synatpic js const trainedNetworkJSON neurons bias 0 squash LOGISTIC bias 0 squash LOGISTIC bias 1 9161856128464938 squash LOGISTIC bias 7 800569287153675 squash LOGISTIC bias 2 855484363201624 squash LOGISTIC bias 6 2824414258821815 squash LOGISTIC connections from 0 to 2 weight 4 874716835319492 from 0 to 3 weight 5 174847897175317 from 0 to 4 weight 6 614910780182805 from 1 to 2 weight 4 8880964776615565 from 1 to 3 weight 5 178397838699644 from 1 to 4 weight 6 627869792271866 from 2 to 5 weight 4 466847840684589 from 3 to 5 weight 12 747217749402143 from 4 to 5 weight 8 501598114378476 const trainedNetworkJSON neurons bias 0 squash LOGISTIC bias 0 squash LOGISTIC bias 1 9161856128464938 squash LOGISTIC bias 7 800569287153675 squash LOGISTIC bias 2 855484363201624 squash LOGISTIC bias 6 2824414258821815 squash LOGISTIC connections from 0 to 2 weight 4 874716835319492 from 0 to 3 weight 5 174847897175317 from 0 to 4 weight 6 614910780182805 from 1 to 2 weight 4 8880964776615565 from 1 to 3 weight 5 178397838699644 from 1 to 4 weight 6 627869792271866 from 2 to 5 weight 4 466847840684589 from 3 to 5 weight 12 747217749402143 from 4 to 5 weight 8 501598114378476 Load the trained network JSON from local storage const trainedNetworkJSON JSON parse localStorage getItem trainedXORNetwork console log trainedNetworkJSON neurons length trainedNetworkJSON neurons length console log trainedNetworkJSON connections length trainedNetworkJSON connections length const context await navigator ml createContext const builder new MLGraphBuilder context Create input placeholders const inputShape 1 const inputType float32 const inputs for let i 0 i trainedNetworkJSON neurons length i inputs push builder input input i dataType inputType shape inputShape Create nodes for the neurons const neurons trainedNetworkJSON neurons map neuron index const bias builder constant dataType float32 shape 1 new Float32Array neuron bias return neuron node builder add inputs index bias bias Create connections trainedNetworkJSON connections forEach connection const fromNode neurons connection from node const toNode neurons connection to node const weight builder constant dataType float32 shape 1 new Float32Array connection weight const weightedInput builder mul fromNode weight neurons connection to node builder add neurons connection to node weightedInput Apply activation functions squash neurons forEach neuron if neuron squash LOGISTIC neuron node builder sigmoid neuron node Add more activation functions if needed Build the graph const graph await builder build output neurons neurons length 1 node Create reusable tensors for inputs and output const inputTensors await Promise all neurons map context createTensor dataType inputType shape inputShape writable true const outputTensor await context createTensor dataType inputType shape 1 readable true const inputValues new Float32Array 1 0 Example input await Promise all inputTensors map tensor context writeTensor tensor inputValues Execute the graph const inputDict neurons reduce dict neuron index dict input index inputTensors index return dict const outputs output outputTensor context dispatch graph inputDict outputs Read and print the result const result await context readTensor outputTensor console log Output new Float32Array result
ash LOGISTIC bias 6 2824414258821815 squash LOGISTIC connections from 0 to 2 weight 4 874716835319492 from 0 to 3 weight 5 174847897175317 from 0 to 4 weight 6 614910780182805 from 1 to 2 weight 4 8880964776615565 from 1 to 3 weight 5 178397838699644 from 1 to 4 weight 6 627869792271866 from 2 to 5 weight 4 466847840684589 from 3 to 5 weight 12 747217749402143 from 4 to 5 weight 8 501598114378476 Load the trained network JSON from local storage const trainedNetworkJSON JSON parse localStorage getItem trainedXORNetwork console log trainedNetworkJSON neurons length trainedNetworkJSON neurons length console log trainedNetworkJSON connections length trainedNetworkJSON connections length const context await navigator ml createContext const builder new MLGraphBuilder context Create input placeholders const inputShape 1 const inputType float32 const inputs for let i 0 i trainedNetworkJSON neurons length i inputs push builder input input i dataType inputType shape inputShape Create nodes for the neurons const neurons trainedNetworkJSON neurons map neuron index const bias builder constant dataType float32 shape 1 new Float32Array neuron bias return neuron node builder add inputs index bias bias Create connections trainedNetworkJSON connections forEach connection const fromNode neurons connection from node const toNode neurons connection to node const weight builder constant dataType float32 shape 1 new Float32Array connection weight const weightedInput builder mul fromNode weight neurons connection to node builder add neurons connection to node weightedInput Apply activation functions squash neurons forEach neuron if neuron squash LOGISTIC neuron node builder sigmoid neuron node Add more activation functions if needed Build the graph const graph await builder build output neurons neurons length 1 node Create reusable tensors for inputs and output const inputTensors await Promise all neurons map context createTensor dataType inputType shape inputShape writable true const outputTensor await context createTensor dataType inputType shape 1 readable true const inputValues new Float32Array 1 0 Example input await Promise all inputTensors map tensor context writeTensor tensor inputValues Execute the graph const inputDict neurons reduce dict neuron index dict input index inputTensors index return dict const outputs output outputTensor context dispatch graph inputDict outputs Read and print the result const result await context readTensor outputTensor console log Output new Float32Array result