WebNN with Tensorflow Train a simple neural network XOR with Tensorflow save the trained network out to localstorage We then load it back in and print the data weights and biases to check they look correct We then use the weights biases for the WebNN network and use it for input output checks https xbdev net internet webnn Minimal tensorflow example using very simple sgd for xor html head script src https cdn jsdelivr net npm tensorflow tfjs script head body script async function trainAndSaveModel const model tf sequential model add tf layers dense units 3 inputShape 2 activation sigmoid model add tf layers dense units 1 activation sigmoid model compile optimizer sgd loss binaryCrossentropy const xs tf tensor2d 0 0 0 1 1 0 1 1 const ys tf tensor2d 0 1 1 0 await model fit xs ys epochs 1000 await model save localstorage xor model console log Model trained and saved trainAndSaveModel script body html Improved training model use adam we also print out the training progress and example input output and error values before saving the data html head script src https cdn jsdelivr net npm tensorflow tfjs script head body script document body style minHeight 300px script div h3 Training Progress h3 p id training progress Initializing p div div h3 Model Predictions and Errors h3 ul id predictions ul div script async function trainAndSaveModel const model tf sequential model add tf layers dense units 3 inputShape 2 activation sigmoid model add tf layers dense units 1 activation sigmoid model compile optimizer adam loss binaryCrossentropy or model compile optimizer sgd loss binaryCrossentropy const xs tf tensor2d 0 0 0 1 1 0 1 1 const ys tf tensor2d 0 1 1 0 await model fit xs ys epochs 4000 callbacks onEpochEnd async epoch logs document getElementById training progress innerText Epoch epoch 1 Loss logs loss toFixed 4 await model save localstorage xor model console log Model trained and saved async function loadAndTestModel try const model await tf loadLayersModel localstorage xor model console log Model loaded const xs tf tensor2d 0 0 0 1 1 0 1 1 const ys tf tensor2d 0 1 1 0 Predict the outputs for the input const predictions model predict xs const actualOutputs ys arraySync const predictedOutputs predictions arraySync const predictionList document getElementById predictions predictionList innerHTML Clear existing results predictedOutputs forEach pred i const error Math abs actualOutputs i 0 pred 0 const listItem document createElement li listItem innerText Input xs arraySync i Predicted pred 0 toFixed 4 Actual actualOutputs i 0 Error error toFixed 4 predictionList appendChild listItem Free up memory predictions dispose xs dispose ys dispose catch error console error Error loading model error async function await trainAndSaveModel await loadAndTestModel script body html Load the trained data weights and biases and print them out check script src https cdn jsdelivr net npm tensorflow tfjs script script type module const model await tf loadLayersModel localstorage xor model console log loaded model model Extract weights and biases from the model const weights1 model layers 0 getWeights 0 arraySync const bias1 model layers 0 getWeights 1 arraySync const weights2 model layers 1 getWeights 0 arraySync const bias2 model layers 1 getWeights 1 arraySync console log weights1 weights1 console log bias1 bias1 console log weights2 weights2 console log bias2 bias2 script Extracted weights and biases we trained earlier for our network let weights1 5 0457587242126465 4 262533187866211 3 101445198059082 4 485400199890137 3 8678324222564697 3 0417561531066895 let bias1 1 336327075958252 0 8802632689476013 4 299434661865234 let weights2 3 7681884765625 3 1797313690185547 4 114118576049805 let bias2 0 48499512672424316 weights1 weights1 flat 2 bias1 bias1 flat 2 weights2 weights2 flat 2 bias2 bias2 flat 2 const context await navigator ml createContext const builder new MLGraphBuilder context Tensors are multidimensional arrays and the shape of a tensor defines its dimensions A tensor with shape 1 is a 1D array with a single element while a tensor with shape 1 1 is a 2D array with 1 row and 1 column Define input placeholders const inputShape 1 2 Input shape should be 1 2 for 2 input neurons as it s a 1d array const inputType float32 const outputShape 1 1 Output shape 1 for single output const input builder input input dataType inputType shape inputShape Create weights and biases as constants const W1 builder constant dataType inputType shape 2 3 new Float32Array weights1 const b1 builder constant dataType inputType shape 1 3 new Float32Array bias1 const W2 builder constant dataType inputType shape 3 1 new Float32Array weights2 const b2 builder constant dataType inputType shape 1 1 new Float32Array bias2 Create the network const hiddenLayer builder sigmoid builder add builder matmul input W1 b1 const outputLayer builder sigmoid builder add builder matmul hiddenLayer W2 b2 Build the graph const graph await builder build output outputLayer Create reusable tensors for inputs and output const inputTensor await context createTensor dataType inputType shape inputShape writable true const outputTensor await context createTensor dataType inputType shape outputShape readable true Define different input values for testing const inputValuesList new Float32Array 0 0 0 0 new Float32Array 0 0 1 0 new Float32Array 1 0 0 0 new Float32Array 1 0 1 0 Execute the graph with different input values for const inputValues of inputValuesList Write the input values to the tensor await context writeTensor inputTensor inputValues Execute the graph const inputs input inputTensor const outputs output outputTensor await context dispatch graph inputs outputs Read and print the result const result await context readTensor outputTensor const out new Float32Array result console log Input Object values inputValues Output Object values out const trainingSet input 0 0 output 0 input 0 1 output 1 input 1 0 output 1 input 1 1 output 0
console error Error loading model error async function await trainAndSaveModel await loadAndTestModel script body html Load the trained data weights and biases and print them out check script src https cdn jsdelivr net npm tensorflow tfjs script script type module const model await tf loadLayersModel localstorage xor model console log loaded model model Extract weights and biases from the model const weights1 model layers 0 getWeights 0 arraySync const bias1 model layers 0 getWeights 1 arraySync const weights2 model layers 1 getWeights 0 arraySync const bias2 model layers 1 getWeights 1 arraySync console log weights1 weights1 console log bias1 bias1 console log weights2 weights2 console log bias2 bias2 script Extracted weights and biases we trained earlier for our network let weights1 5 0457587242126465 4 262533187866211 3 101445198059082 4 485400199890137 3 8678324222564697 3 0417561531066895 let bias1 1 336327075958252 0 8802632689476013 4 299434661865234 let weights2 3 7681884765625 3 1797313690185547 4 114118576049805 let bias2 0 48499512672424316 weights1 weights1 flat 2 bias1 bias1 flat 2 weights2 weights2 flat 2 bias2 bias2 flat 2 const context await navigator ml createContext const builder new MLGraphBuilder context Tensors are multidimensional arrays and the shape of a tensor defines its dimensions A tensor with shape 1 is a 1D array with a single element while a tensor with shape 1 1 is a 2D array with 1 row and 1 column Define input placeholders const inputShape 1 2 Input shape should be 1 2 for 2 input neurons as it s a 1d array const inputType float32 const outputShape 1 1 Output shape 1 for single output const input builder input input dataType inputType shape inputShape Create weights and biases as constants const W1 builder constant dataType inputType shape 2 3 new Float32Array weights1 const b1 builder constant dataType inputType shape 1 3 new Float32Array bias1 const W2 builder constant dataType inputType shape 3 1 new Float32Array weights2 const b2 builder constant dataType inputType shape 1 1 new Float32Array bias2 Create the network const hiddenLayer builder sigmoid builder add builder matmul input W1 b1 const outputLayer builder sigmoid builder add builder matmul hiddenLayer W2 b2 Build the graph const graph await builder build output outputLayer Create reusable tensors for inputs and output const inputTensor await context createTensor dataType inputType shape inputShape writable true const outputTensor await context createTensor dataType inputType shape outputShape readable true Define different input values for testing const inputValuesList new Float32Array 0 0 0 0 new Float32Array 0 0 1 0 new Float32Array 1 0 0 0 new Float32Array 1 0 1 0 Execute the graph with different input values for const inputValues of inputValuesList Write the input values to the tensor await context writeTensor inputTensor inputValues Execute the graph const inputs input inputTensor const outputs output outputTensor await context dispatch graph inputs outputs Read and print the result const result await context readTensor outputTensor const out new Float32Array result console log Input Object values inputValues Output Object values out const trainingSet input 0 0 output 0 input 0 1 output 1 input 1 0 output 1 input 1 1 output 0