Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding crossover function #100

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions lib/matrix.js
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
}
Expand Down
13 changes: 13 additions & 0 deletions lib/nn.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}


}