Notebook - Welcome to Notebook

Contact/Report Bugs
You can contact me at: bkenwright@xbdev.net












PyTorch and WebNN Train and save the neural network using PyTorch for this example a simple XOR neural net Save the dictionary and a json version of the network The json version of the network make a flexible future proof version of the data that we can easily pass across to the WebNN JavaScript Python Code import torch import torch nn as nn import torch optim as optim import json Define the neural network class XORNet nn Module def __init__ self super XORNet self __init__ self fc1 nn Linear 2 2 self fc2 nn Linear 2 1 def forward self x x torch sigmoid self fc1 x x torch sigmoid self fc2 x return x Training data inputs torch tensor 0 0 0 1 1 0 1 1 dtype torch float32 targets torch tensor 0 1 1 0 dtype torch float32 Initialize the network criterion and optimizer model XORNet criterion nn MSELoss optimizer optim SGD model parameters lr 0 1 Training loop with progress updates num_epochs 5000 for epoch in range num_epochs optimizer zero_grad output model inputs loss criterion output targets loss backward optimizer step Print progress every 100 epochs if epoch 1 500 0 or epoch num_epochs 1 print f Epoch epoch 1 num_epochs Loss loss item 4f Progress epoch 1 num_epochs 500 2f Save the trained model to a file torch save model state_dict xor_net pth Convert the state dictionary to JSON format state_dict model state_dict state_dict_json k v tolist for k v in state_dict items with open xor_net json w as f json dump state_dict_json f Print the weights and biases for name param in model named_parameters if param requires_grad print f name param data numpy prints fc1 weight 0 3043185 0 6067796 1 8907964 1 8609867 fc1 bias 0 4322342 0 1948249 fc2 weight 0 01738905 1 469708 fc2 bias 1 16437 If you need to run a server as a localhost to access the files i e json file you can use the following script The cors feature has been enabled so you can access the file using other domains not just localhost Run server directly without py file using this line python m http server Or file version local py which you run with python local py import http server import socketserver Configuration PORT 8000 Port number to serve on e g http localhost 8000 class CORSRequestHandler http server SimpleHTTPRequestHandler def end_headers self self send_header Access Control Allow Origin self send_header Access Control Allow Methods GET POST OPTIONS self send_header Access Control Allow Headers x api key Content Type http server SimpleHTTPRequestHandler end_headers self Create and start the server with socketserver TCPServer PORT CORSRequestHandler as httpd print f Serving at http localhost PORT try httpd serve_forever except KeyboardInterrupt print nShutting down server httpd server_close The code below loads and uses the trained network using WebNN Load the json data in which was trained on PyTorch to be used by WebNN Fetch the model file const response await fetch http localhost 8000 xor_net json const json await response json console log json json let weights1 json fc1 weight flat 2 let bias1 json fc1 bias flat 2 let weights2 json fc2 weight flat 2 let bias2 json fc2 bias flat 2 console log weights1 weights1 console log bias1 bias1 console log weights2 weights2 console log bias2 bias2 json fc1 weight 0 6804810762405396 0 2847576439380646 0 2714926302433014 0 18927520513534546 fc1 bias 0 24895617365837097 0 48802873492240906 fc2 weight 0 3371845781803131 0 3348560333251953 fc2 bias 0 2576610743999481 weights1 0 6804810762405396 0 2847576439380646 0 2714926302433014 0 18927520513534546 bias1 0 24895617365837097 0 48802873492240906 weights2 0 3371845781803131 0 3348560333251953 bias2 0 2576610743999481 const weights1 0 6804810762405396 0 2847576439380646 0 2714926302433014 0 18927520513534546 const bias1 0 24895617365837097 0 48802873492240906 const weights2 0 3371845781803131 0 3348560333251953 const bias2 0 2576610743999481 const context await navigator ml createContext const builder new MLGraphBuilder context Define WebNN network 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 2 new Float32Array weights1 const b1 builder constant dataType inputType shape 1 2 new Float32Array bias1 const W2 builder constant dataType inputType shape 2 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

odel file const response await fetch http localhost 8000 xor_net json const json await response json console log json json let weights1 json fc1 weight flat 2 let bias1 json fc1 bias flat 2 let weights2 json fc2 weight flat 2 let bias2 json fc2 bias flat 2 console log weights1 weights1 console log bias1 bias1 console log weights2 weights2 console log bias2 bias2 json fc1 weight 0 6804810762405396 0 2847576439380646 0 2714926302433014 0 18927520513534546 fc1 bias 0 24895617365837097 0 48802873492240906 fc2 weight 0 3371845781803131 0 3348560333251953 fc2 bias 0 2576610743999481 weights1 0 6804810762405396 0 2847576439380646 0 2714926302433014 0 18927520513534546 bias1 0 24895617365837097 0 48802873492240906 weights2 0 3371845781803131 0 3348560333251953 bias2 0 2576610743999481 const weights1 0 6804810762405396 0 2847576439380646 0 2714926302433014 0 18927520513534546 const bias1 0 24895617365837097 0 48802873492240906 const weights2 0 3371845781803131 0 3348560333251953 const bias2 0 2576610743999481 const context await navigator ml createContext const builder new MLGraphBuilder context Define WebNN network 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 2 new Float32Array weights1 const b1 builder constant dataType inputType shape 1 2 new Float32Array bias1 const W2 builder constant dataType inputType shape 2 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

2dracecargame
3dplot
a4print
about
acecustomkeywords
acecustomkeywords2
acejs
acejs2
acejs3
aessecurity
angularjs
animbackgroundimage
aseformat
assert
asteroidsjs
backgrounds01
backgrounds02
backgrounds03
barnsleyfern
base26
base64
bib
binary
bodypix
bouncy
box2dweb
breakoutjs
browserversion
buslanes
busybutton
bvhreader
calendar
candycrush
candycrush2
canvas
canvas2
canvas3
canvasmandelbrot
canvasmandelbrot2
canvasnumbers
canvaszoom
capsule
car2dsimulationphysics
car2dsimulationphysics2
changingimages
chaosgame
chaosrandom
chaosrandomhisto
chaosrandomhisto2
chatgptusingopenai
chatgptusingopenai2
chatgptusingopenai3
checkboxtoggle
chinesetiles
classes
classfeatures
clipboardbutton
clonenode
codedropdown
codemirror
codemirror2
collada
colorpick
columnresizer
contextmenu
convnet
cookiebanner
countdown
countdown2
countdown3
crop
css3dbarchart
css3dbarchart2
css3dbook
css3dscene
csscube
csscube2
csscube3
csscubevideos
cssfilelist
csshas
csspulse
cssresizeaspect
cssspin
csszooming
csvtoarray
curleffect
customcheckbox
customhexviewer
d3datamap
d3js
d3js10
d3js11
d3js2
d3js3
d3js4
d3js5
d3js6
d3js7
d3js8
d3js9
d3jsanimatedgrid
d3jsarctransition
d3jsarctransition2
d3jsaxis
d3jsaxischanging
d3jsbars
d3jsbrushing
d3jsbuslanes
d3jsbuslanes2
d3jscalendar
d3jscheat
d3jsclock
d3jscloudmap
d3jscogs
d3jscolors
d3jscovid
d3jscovid2
d3jscovid3
d3jsdashboard
d3jsdashboard2
d3jsdashboard3
d3jsdatakeyfunction
d3jsdensity
d3jsdragresizing
d3jsdragresizing2
d3jseach
d3jsease
d3jsevents
d3jsflower
d3jsforcegroups
d3jsforces
d3jsforces2
d3jsfractaltree
d3jsgeo
d3jsgroupbars
d3jsgroups
d3jsheatmap
d3jshex
d3jshierarchies
d3jshierarchies2
d3jshistogram
d3jshistogram2
d3jshistogram3
d3jshistogram4
d3jsinterpolate
d3jsjoin
d3jskmean
d3jskmean2
d3jsline
d3jsline2
d3jsline3
d3jsline4
d3jslinetransition
d3jslinetransition0
d3jslinetransition2
d3jsmaplocations
d3jsmaps
d3jsmaps2
d3jsmaps3
d3jsmisc
d3jsmisc2
d3jsmodule
d3jsmodulecolor
d3jsmultistyles
d3jsnobel
d3jsoverlappinggraphs
d3jspanel
d3jspie
d3jspieinterpolate
d3jssankey
d3jssankey2
d3jsscatter
d3jsshapes
d3jsslider
d3jsspending
d3jsspending2
d3jsspiralplot
d3jsspirograph
d3jssquare
d3jsstack
d3jsstackedbar
d3jsstackedbar2
d3jssunburst
d3jssunmoon
d3jssvglines
d3jssymbols
d3jstimelines
d3jsuk
d3jsvoronoi
d3scatterplot
d3timeline
d3timeline2
datalist
datamuse
date
dblclickhighlight
deviceorientation
dictionaryapi
dockermenu
doodlepad
downloadgif
dragdroplistitems
dragrotateresizediv
dragrotateresizediv2
dragrotateresizediv3
dragrotateresizediv4
dragrotateresizefontsize
dragselectbrush
drawlinesdiv
dropdown
dualquaternionimages
dynamicgrid
easefunctions
easeinterpolate3dplots
echart
echart2
echart3
encapsulation
epubviewer
errorstack
excalidraw
excalidraw2
excalidraw3
excalidraw5
expandable
faker
fetchplus
fileupload
fixedtopbar
fluiddynamics
fluiddynamics2
fluiddynamics3
fluidgaswatergl
fluidsmokedynamics
fluidsmokedynamics2
fonts
fonts2
footerbar
fractalcircles
fractalmaze
fractalmaze2
fractalnoiseimage
fractals
fractals2
fractaltree
freesvg
fresnel
froggerjs
gantt
gifgiphyapi
gifhex
gltffromscratch
gradients
griditems
griditems2
griditems3
griditems4
gridworms
happyfont
heat
hexview
hexview2
highlight
icons
icons2
iframes
ik
imagetracertosvg
imgur
inputfile
invadersjs
ipynb
ipynb2
ipynb3
ipynb4
isbn13
isbn2
jpghex
jquery
jquery2
jqueryui
jqueryui2
jsdraganddrop
jsfire
jslint
jsobfuscate
jsraytracer
jstree
jstree2
jszip
jszipimages
jszipread
keyboardpiano
keyframes
l2dwidget
lcpsolverrigidbodies
lda
leftmenu
less
less2
lineargradientimage
linenumbers
loadimagefromfile
makepdf
maps
markdown
markdown2
markdown3
markdownalerts
markdownalerts2
markdownbookmarks
markovimage
markovpixelblocks
mathjax
matrices
matsandvects
mazegamejs
md2tex
metrotiles
metrowindows
milestones
minkowski2dboxes
misc
misc2
modules
myipdetails
mymodplotly
neataptic
networkstructures
networkstructures2
neural_network_drawshape
neural_network_plot_in_vs_out
neuralnetworkarrays
neuralnetworkblocks
neuralnetworksinewave
neuralnetworksnolibs
neuralnetworkvisualization
noiseflowfield
noiseflowfield2
noiseflowfield3
noiseflowfield4
noiseflowfield5
noiseflowfield6
number
obj
objtojson
openaiimages
opencv
opencv2
opencv3
opencv4
opencv5
outline
p2
p5fractalleaf
p5fractalshape
p5js
p5js2
p5js3
p5jsanimatedcover
p5mengercube
p5snowflakes
palindrome
panel
parallax
paste
paste2
pasteimgfromurl
pdfjs
pdfjs2
pdfkit
pdfkit2
pdfkit3
pdfkit4
pdfkit5
pdfkit6
pdfmake
pdfmake2
pdfmake3
pdfmake4
pdfmake5
pdfmake6
perlin
perlin2
perlin3
perspective
pexels
pixelgridpattern
playground
plotly
plotlynoise
plotlyranddist
plyloader
plyloader2
pngtxtencoder
pongjs
pptxgenjs
prettycode
prism
prn
problems
progress
pseudorandom
px2svg
python
quotes
racergame
random
randomcalcpie
randomgenerator
randomprofilepatterns
randomsinhistogram
randomstring
rating
rayambient
raymonte
raymonteprogressive
raymonteprogressive2
raymontewarmstart
reexpcross
reexpcross2
regex
regexbib
regexpfixbib
regexpmultiline
repeatwordsregexp
resizabletable
resizabletable2
revealjs
revealjs2
revealjsmulti
rigidbodyspheres2d
rigidbodyspheres3
rigidbodysphereslopetangent
ritalanguage
ritalanguage2
ritalanguage3
rotateimg
rough
rsapublicprivatekeys
rss
rss2
sankey
scrappingsvg
scrolltext
scrolltext2
scrollwidth
sdf2dcanvas
sdfboxinboxtwist
sdfchessbishop
sdfchessking
sdfchessknight
sdfchesspawn
sdfchessqueen
sdfchessrook
sdfhollowbox
setintervalexception
shareurl
shuffle
sidecomment
similarity
simplehighlighter
simpleplatformgamejs
sinecanvas
sliderpopout
slides
smileys
snowfall
snowman
sound
soundsignal
sphererayintersection
springs
sqljs
steganography
stereogram
stringmatching
sudoku
sudoku2
sudoku3
svg
svgchaos
svgdragresize
svgdragresize2
svgdragresize3
svgdragrotate
svgdrawing
svglines
svglines2
svglines3
svglines4
svglines5
svglinesmandelbrot
svgpathsdragrotate
svgpathsdragrotateresize
svgpie
svgpie2
svgpie3
svgpiepath
svgpiepath2
svgrandomfaces
symbolcanvas
symbols
synaptic
synaptic2
synonyms
tablerotatecells
tablerotatecells2
tablerotatecells3
tablerotatecells3b
tablerotatecells4
tables
tablezebra
tabularjs
tabularjs2
tabulatordownload
tagcanvas
tensorflowdenoiseencoder
tensorflowgan
tensorflowjs
tensorflowjsbasic
tensorflowjscnn
tensorflowjssinewave
tensorflowjssound
tensorflowmobilenet
tetrahedronfractal
tetrahedronfractalfolding
tetris
textarea
textareaauto
textareadiv
textareadiv2
textmaskimage
theirorthere
thesaurus
threejs
threejs2
threejs3
threejs4
threejsgltf
threejstokyo
tiles
toaster
tooltip
transition
transitionexpandabledropdown
treeview
treeview2
tricks
tshirt
tshirt2
tshirt3
turningpages
unsplash
urlblob
urlblob2
userdefinepoints
vector
videos
videos2
visualsort
vue
w2ui
w2uientertextdialog
webcam
webgl
webgl2
webgl3
webgl4
webgl5
webglbasic1
webglbasic2
webglcube
webglfov
webglfrustum
webgljson
webglleaves
webgllighting
webglorthographic
webglpoints1
webglpoints2
webglpoints3
webglsquare
webgltexture1
webgltexture2
webgltexture3
webgltransforms
webgltriangle
webgpu
webgpu10
webgpu11
webgpu12
webgpu13
webgpu14
webgpu15
webgpu16
webgpu17
webgpu2
webgpu3
webgpu4
webgpu5
webgpu6
webgpu7
webgpu8
webgpu9
webgpubars
webgpubuffers
webgpubuffers2
webgpucellnoise
webgpuclouds
webgpuclydescope
webgpucompute
webgpucubemap
webgpucubemap2
webgpudeferred
webgpudepth
webgpudof
webgpudrops
webgpuetha
webgpufire
webgpufractalcubes
webgpuglassrain
webgpugltf
webgpugltf2
webgpugrass
webgpugrid
webgpukernel
webgpukleinian
webgpulabupdates
webgpulighting
webgpumandelbrot
webgpumeta3d
webgpumetaballs
webgpumouse
webgpunoise
webgpunormalmapping
webgpuobj
webgpuparallax
webgpuparallax2
webgpuparallax3
webgpuparallaxshadow
webgpuparallaxshadow2
webgpupixel
webgpuquad
webgpuray1
webgpuraytracing
webgpuraytracing2
webgpushadowmaps
webgpushadowmaps2
webgpusierpinski2d
webgpusierpinski3d
webgpusinusoid
webgpussao
webgpustadiumobj
webgpuswirl
webgputestpipe3
webgputoon
webgputopology
webgputt
webgpuvolcloud
webgpuwater
webgpuwireframe
webgpuwireframe2
webnn
webnn2
webnnconv2d
webnnlstm
webnnpytorch
webnntraining
webnnwithsynaptic
webnnwithsynaptic2
webnnwithsynapticsinwave
webnnwithtensorflow
webpcanvas
webworkers
webxr
webxr2
wiggly
wikipedia