Etikett: Visualisering
AI Visualisering
Fel: 0
const canvas = document.getElementById('nnCanvas'); const ctx = canvas.getContext('2d');
let w = { i1h1: Math.random()*2-1, i2h1: Math.random()*2-1, i1h2: Math.random()*2-1, i2h2: Math.random()*2-1,
h1o: Math.random()*2-1, h2o: Math.random()*2-1 };
const trainingData = [ {x:[0,0], y:0}, {x:[0,1], y:1}, {x:[1,0], y:1}, {x:[1,1], y:0} ];
function sigmoid(x){ return 1/(1+Math.exp(-x)); }
function forward(x1,x2){
let h1 = sigmoid(x1*w.i1h1 + x2*w.i2h1);
let h2 = sigmoid(x1*w.i1h2 + x2*w.i2h2);
let out = sigmoid(h1*w.h1o + h2*w.h2o);
return {h1,h2,out}; }
function train(){
for(let epoch=0; epoch<100; epoch++){ let sample = trainingData[ Math.floor( Math.random()*4)]; let x1 = sample.x[0]; let x2 = sample.x[1]; let target = sample.y; let {h1,h2,out} = forward(x1,x2); let error = target - out; let lr = 0.2; w.h1o += lr*error*h1; w.h2o += lr*error*h2; w.i1h1 += lr*error*x1; w.i2h1 += lr*error*x2; w.i1h2 += lr*error*x1; w.i2h2 += lr*error*x2; } render(); } function line(x1,y1,x2,y2,weight){ ctx.beginPath(); ctx.moveTo(x1,y1); ctx.lineTo(x2,y2); let thickness = Math.abs(weight)*8+1; ctx.lineWidth = thickness; if(weight > 0) ctx.strokeStyle="green"; else ctx.strokeStyle="red";
ctx.stroke(); }
function neuron(x,y,label){
ctx.beginPath(); ctx.arc(x,y,25,0,Math.PI*2);
ctx.fillStyle="white"; ctx.fill();
ctx.strokeStyle="black"; ctx.stroke();
ctx.fillStyle="black"; ctx.fillText(label,x-10,y+5); }
function render(){
ctx.clearRect( 0,0, canvas.width, canvas.height);
let in1={x:100,y:150}; let in2={x:100,y:350};
let h1={x:450,y:150}; let h2={x:450,y:350};
let out={x:800,y:250};
line( in1.x,in1.y, h1.x,h1.y, w.i1h1);
line( in2.x,in2.y, h1.x,h1.y, w.i2h1);
line( in1.x,in1.y, h2.x,h2.y, w.i1h2);
line( in2.x,in2.y, h2.x,h2.y, w.i2h2);
line( h1.x,h1.y, out.x,out.y, w.h1o);
line( h2.x,h2.y, out.x,out.y, w.h2o);
neuron(in1.x,in1.y,"I1"); neuron(in2.x,in2.y,"I2");
neuron(h1.x,h1.y,"H1"); neuron(h2.x,h2.y,"H2");
neuron(out.x,out.y,"O");
let loss=0;
trainingData.forEach(t=>{
let p= forward( t.x[0], t.x[1] ).out;
loss += Math.pow( t.y-p,2); });
loss/=4;
document .getElementById("loss") .innerHTML= loss.toFixed(4); }
function resetNetwork(){
Object.keys(w) .forEach(k=>{
w[k]= Math.random()*2-1;
});
render(); }
render();
Posted by Lars Lindmark on 31 maj, 2026Kategori: Output