class NeuralNetwork { constructor(inputSize = 64, hiddenLayers = 32, hiddenSize = 128, outputSize = 64) { this.inputSize = inputSize; this.hiddenLayers = hiddenLayers; this.hiddenSize = hiddenSize; this.outputSize = outputSize; this.layers = []; // Input → first hidden this.layers.push(this.createLayer(inputSize, hiddenSize)); // Hidden → hidden for (let i = 1; i < hiddenLayers; i++) { this.layers.push(this.createLayer(hiddenSize, hiddenSize)); } // Last hidden → output this.layers.push(this.createLayer(hiddenSize, outputSize)); } createLayer(inputSize, outputSize) { const weights = []; const biases = []; for (let i = 0; i < outputSize; i++) { weights[i] = []; for (let j = 0; j < inputSize; j++) { weights[i][j] = Math.random() * 2 - 1; // random -1..1 } biases[i] = Math.random() * 2 - 1; } return { weights, biases }; } activate(x) { return Math.tanh(x); } forward(inputs) { let output = inputs; for (const layer of this.layers) { const next = []; for (let i = 0; i < layer.weights.length; i++) { let sum = layer.biases[i]; for (let j = 0; j < layer.weights[i].length; j++) { sum += layer.weights[i][j] * output[j]; } next[i] = this.activate(sum); } output = next; } return output; } clone() { const clone = new NeuralNetwork( this.inputSize, this.hiddenLayers, this.hiddenSize, this.outputSize ); clone.layers = JSON.parse(JSON.stringify(this.layers)); return clone; } mutate(rate = 0.05, strength = 0.2) { for (const layer of this.layers) { for (let i = 0; i < layer.weights.length; i++) { for (let j = 0; j < layer.weights[i].length; j++) { if (Math.random() < rate) { layer.weights[i][j] += (Math.random() * 2 - 1) * strength; } } if (Math.random() < rate) { layer.biases[i] += (Math.random() * 2 - 1) * strength; } } } } } // ---------------------- // Example Evolution Training // ---------------------- function evaluate(net) { let score = 0; for (let i = 0; i < 5; i++) { // small batch for speed const input = Array(64).fill().map(() => Math.random()); const output = net.forward(input); // Example: try to copy input to output for (let j = 0; j < 64; j++) { score -= Math.abs(output[j] - input[j]); } } return score; } function evolve(popSize = 20, generations = 10) { let population = []; for (let i = 0; i < popSize; i++) population.push(new NeuralNetwork()); for (let gen = 0; gen < generations; gen++) { population.sort((a, b) => evaluate(b) - evaluate(a)); console.log("Gen", gen, "Best score:", evaluate(population[0])); const survivors = population.slice(0, Math.floor(popSize * 0.2)); while (survivors.length < popSize) { const parent = survivors[Math.floor(Math.random() * survivors.length)]; const child = parent.clone(); child.mutate(); survivors.push(child); } population = survivors; } return population[0]; } // ---------------------- // Run // ---------------------- console.log("Training a huge 32-layer network..."); const best = evolve(10, 5); // smaller numbers to avoid slow JS console.log("Training done.");