Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                 <canvas id="graph" width="400" height="400"></canvas>
    <button onclick="train()">Train</button>
    <button onclick="classifyPoints()">Classify Points</button>
<button onclick="reset()">Reset</button>
              
            
!

CSS

              
                
              
            
!

JS

              
                class NeuralNetwork {
    constructor(inputLen, outputLen) {
        this.inputLen = inputLen;
        this.outputLen = outputLen;
        this.weights = Array.from({ length: this.outputLen }, () =>
            Array.from({ length: this.inputLen }, () => Math.random())
        );
        //this.bias = Array(this.outputLen).fill(0);
        this.learningRate = 0.1;
        this.points = [];
        console.log(this.weights, this.sigmoid(1), this.sigmoid(16), this.sigmoid(-2), this.sigmoid(0));
    }

    propagate(inputs) {
        const output = new Array(this.outputLen);
        for (let i = 0; i < this.outputLen; i++) {
            output[i] = 0;
            for (let j = 0; j < this.inputLen; j++) {
                output[i] += this.weights[i][j] * inputs[j];
            }
            //output[i] += this.bias[i];
            //console.log("bias", i, this.bias[i]);
            output[i] = this.sigmoid(output[i]);
        }
        return output;
    }
    sigmoid(x) {
        return 1 / (1 + Math.exp(-x));
    }
    train(inputs, target) {
        const output = this.propagate(inputs);
        const errors = new Array(this.outputLen);

        for (let i = 0; i < this.outputLen; i++) {
            errors[i] = target[i] - output[i];
            for (let j = 0; j < this.inputLen; j++) {
                this.weights[i][j] +=
                    this.learningRate *
                    errors[i] *
                    output[i] *
                    (1 - output[i]) *
                    inputs[j];
            }
            //this.bias[i] += this.learningRate * errors[i];
        }
    }
}

const trainingData = [
    { x: -0.5, y: -0.5, label: "blue" },
    { x: 0.5, y: -0.5, label: "red" },
    { x: -0.5, y: 0.5, label: "green" },
    { x: 0.5, y: 0.5, label: "purple" }
];

function train() {
    for (let i = 0; i < 10000; i++) {
        const data =
            trainingData[Math.floor(Math.random() * trainingData.length)];
        neuralNetwork.train([data.x, data.y], encode(data.label));
    }
    console.log("Training complete");
}

function reset() {
    neuralNetwork = new NeuralNetwork(2, 4);
}


const canvas = document.getElementById("graph");
const ctx = canvas.getContext("2d");
const pointRadius = 5; // Radius of the points


let neuralNetwork = new NeuralNetwork(2, 4);


function classifyPoints() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawAxes();
    this.points = [];
    for (let i = 0; i < 100; i++) {
        const x = Math.random() * 2 - 1; // Random x-coordinate between -1 and 1
        const y = Math.random() * 2 - 1; // Random y-coordinate between -1 and 1
        const output = neuralNetwork.propagate([x, y]);
        const predictedLabel = decode(output);
        drawPoint(x, y, predictedLabel);
        points.push({ x, y, predictedLabel });
    }
    //console.log(points);
}
function encode(label) {
    const encoding = {
        blue: [1, 0, 0, 0],
        red: [0, 1, 0, 0],
        green: [0, 0, 1, 0],
        purple: [0, 0, 0, 1]
    };
    return encoding[label];
}

function decode(output) {
    const labels = ["blue", "red", "green", "purple"];
    const maxIndex = output.indexOf(Math.max(...output));
    return labels[maxIndex];
}


function drawPoint(x, y, color) {
    ctx.beginPath();
    ctx.arc(
        ((x + 1) * canvas.width) / 2,
        canvas.height - ((y + 1) * canvas.height) / 2,
        pointRadius,
        0,
        2 * Math.PI
    );
    ctx.fillStyle = color;
    ctx.fill();
    ctx.closePath();
}

function drawAxes() {
    
    const canvasHalfWidth = canvas.width / 2;
    const canvasHalfHeight = canvas.height / 2;
    
    ctx.beginPath();
    ctx.fillStyle = `rgba(0,255,0,0.2)`;
    ctx.fillRect(0, 0, canvasHalfWidth, canvasHalfHeight);
    ctx.fillStyle = `rgba(225,0,255,0.2)`;
    ctx.fillRect(canvasHalfWidth, 0, canvasHalfWidth, canvasHalfHeight);
    ctx.fillStyle = `rgba(0,0,255,0.2)`;
    ctx.fillRect(0, canvasHalfHeight, canvasHalfWidth, canvasHalfHeight);
    ctx.fillStyle = `rgba(255,0,0,0.2)`;
    ctx.fillRect(canvasHalfWidth, canvasHalfHeight, canvasHalfWidth, canvasHalfHeight);
    
    ctx.moveTo(0, canvas.height / 2);
    ctx.lineTo(canvas.width, canvas.height / 2); // X-axis
    ctx.moveTo(canvas.width / 2, 0);
    ctx.lineTo(canvas.width / 2, canvas.height); // Y-axis
    ctx.strokeStyle = "black";
    ctx.stroke();
    ctx.closePath();
}

              
            
!
999px

Console