diff --git a/lib/matrix.js b/lib/matrix.js index 34b2d97..f83475e 100644 --- a/lib/matrix.js +++ b/lib/matrix.js @@ -18,6 +18,17 @@ class Matrix { return m; } + static crossover(a, b, ratio = 0.5) { + if (!a instanceof this || !b instanceof this || a.rows !== b.rows || a.cols !== b.cols) { + console.log('Columns and Rows of A must match Columns and Rows of B.'); + return; + } + + let m = a.copy(); + m.map((value, i, j) => Math.random() < ratio ? value : b.data[i][j]); + return m; + } + static fromArray(arr) { return new Matrix(arr.length, 1).map((e, i) => arr[i]); } diff --git a/lib/nn.js b/lib/nn.js index 0260280..8895f03 100644 --- a/lib/nn.js +++ b/lib/nn.js @@ -175,6 +175,19 @@ class NeuralNetwork { this.bias_o.map(mutate); } + static crossover(a, b, ratio = 0.5) { + if (!a instanceof this || !b instanceof this || a.input_nodes !== b.input_nodes || a.hidden_nodes !== b.hidden_nodes || a.output_nodes !== b.output_nodes) { + console.error('Only NeuralNetworks of the same breed can generate offspring.'); + return; + } + + let nn = a.copy(); + nn.weights_ih = Matrix.crossover(a.weights_ih, b.weights_ih, ratio); + nn.weights_ho = Matrix.crossover(a.weights_ho, b.weights_ho, ratio); + nn.bias_h = Matrix.crossover(a.bias_h, b.bias_h, ratio); + nn.bias_o = Matrix.crossover(a.bias_o, b.bias_o, ratio); + return nn; + } }