www.xbdev.net
xbdev - software development
Friday February 6, 2026
Home | Contact | Support | WebGPU Graphics and Compute ... | Neural Networks and WebGPU Compute.. Learning from Data.....
     
 

Neural Networks and WebGPU Compute..

Learning from Data.....

 


Sine Wave


Having a neural network learn the sine wave function - pass in a single floating point value and it outputs the amplitude of the sinewave signal. Essentially, emulating the
sin(..)
function.



Training neural network to emulate a sine wave signal.
Training neural network to emulate a sine wave signal.



Complete Code


let fp await fetch('https://cdn.plot.ly/plotly-2.1.0.min.js');
let ft await fp.text();
var 
script document.createElement('script');
//script.src = 'https://cdn.plot.ly/plotly-2.1.0.min.js';
script.innerHTML ft;
document.head.appendChild(script); 

  
await xinitialize( {layers:[1,17,17,1], build:'cpu'learningrate:0.2} );

// sine wave signal - deep neural network
// (1) time (time index for input)
// (17,17) hidden layers 
// (1) amplitude


// SINE WAVE


let noSamples       50;
let iteration       0;
var 
trainingSet;// = [];


// Function to shuffle data
function shuffle(array) {
    for (
let i = array.length 10i--) {
        const 
Math.floor(Math.random() * (1));
        [array[
i], array[j]] = [array[j], array[i]];
    }
    return array;
}

// Function to create mini-batches
function createMiniBatches(databatchSize) {
    
let miniBatches = [];
    for (
let i 0data.length+= batchSize) {
        
miniBatches.push(data.slice(ibatchSize));
    }
    return 
miniBatches;
}

async function calcTotalError()
{
  
let totalError 0;
  for (
let tt 0tt noSamplestt+=1)
  {
    
// nn value
    
let amp await xactivate( [ tt/noSamples ] );
    
let val amp[0] * 2.0 1.0;

    
// ideal value
    
let t Math.PI tt/noSamples;
    
let mval Math.sin);

    
totalError totalError Math.absval mval );
  }

  
let elem2 document.getElementById('error');
    if ( 
elem2==undefined ){ elem2 document.createElement('div');
                             
elem2.id 'error';
                             
document.body.appendChildelem2 ); };
  
elem2.innerHTML "Error: " totalError;
}

// iteration starts once the data has been loaded
async function iterate(){

  
iteration++;

  
let elem1 document.getElementById('counter');
    if ( 
elem1==undefined ){ elem1 document.createElement('div');
                             
elem1.id 'counter';
                             
document.body.appendChildelem1 ); };
  
elem1.innerHTML "Iteration: " iteration;


  if ( (
iteration%10) === // only update graph every 5 iterations
  
{
    
await plotData();
  }

  
//calcTotalError();

  
if (trainingSet == undefined )
  {
        
console.log('creating dataset');
    
trainingSet = [];

    for (
let tt 0tt noSamplestt+=1)
    {
      
let t Math.PI tt/noSamples;

      
//console.assert(t>=0 && t<=1 );
      
let amp Math.sin);  //-1 to 1

      
let ampNormalized = (amp 1.0)*0.5// 0 to 1
      
console.assertampNormalized >= );
      
console.assertampNormalized <= );

      
trainingSet.push( {inputs: [tt/noSamples],
                         
outputs:[ampNormalized] } );

    }
  }

  const 
NUM_EPOCHS 5;
  const 
BATCH_SIZE 20;
  
  for (
let epoch 0epoch NUM_EPOCHSepoch++) 
  {
      
let shuffledData shuffle(trainingSet);
    
let miniBatches createMiniBatches(shuffledDataBATCH_SIZE);

      for (
let miniBatch=0miniBatch<miniBatches.lengthminiBatch++)
      {
        
let batches miniBatchesminiBatch ];
          for (
let bat=0bat<batches.lengthbat++)
          {
              
let datum batchesbat ];
              
await xactivatedatum.inputs );
              
await xpropagatedatum.outputs );
          };
      };
  }
  
requestAnimationFrameiterate);
}

requestAnimationFrameiterate );

async function plotData()
{
    
// plot trained data
    
{
  
let x = [];
  
let y = [];
  
let y2 = [];
  for (
let tt 0tt noSamplestt+=1)
  {
    
let t Math.PI tt/noSamples;
    
let amp await xactivate( [ tt/noSamples ] );

    
let val amp[0] * 2.0 1.0;
    
x.pushtt/noSamples  );
    
y.pushval )
    
y2.pushMath.sin) );
  }

  
let plot1 document.getElementById('plot1');
    if ( 
plot1==undefined ){ plot1 document.createElement('div');
                             
plot1.id 'plot1';
               
plot1.style.width  '600px';
                             
plot1.style.height '400px';
                             
document.body.appendChildplot1 ); };
    

  
Plotly.newPlotplot1, [{ xy}], { 
                
margin: { t} }, {showSendToCloud:true} );

  
// plot ideal data
  
Plotly.addTracesplot1, {xyy2} );
  }
}
// end plotData(..)

















WebGPU by Example: Fractals, Image Effects, Ray-Tracing, Procedural Geometry, 2D/3D, Particles, Simulations WebGPU Compute graphics and animations using the webgpu api 12 week course kenwright learn webgpu api kenwright programming compute and graphics applications with html5 and webgpu api kenwright real-time 3d graphics with webgpu kenwright webgpu api develompent a quick start guide kenwright webgpu by example 2022 kenwright webgpu gems kenwright webgpu interactive compute and graphics visualization cookbook kenwright wgsl webgpu shading language cookbook kenwright wgsl webgpugems shading language cookbook kenwright



 
Advert (Support Website)

 
 Visitor:
Copyright (c) 2002-2025 xbdev.net - All rights reserved.
Designated articles, tutorials and software are the property of their respective owners.