Skip to content

Instantly share code, notes, and snippets.

@esshka
Created March 23, 2023 22:29
Show Gist options
  • Save esshka/b8f03feb53d7302227c4eca863fc87f8 to your computer and use it in GitHub Desktop.
Save esshka/b8f03feb53d7302227c4eca863fc87f8 to your computer and use it in GitHub Desktop.
function compatibilityDistance(network1, network2, c1 = 1, c2 = 1, c3 = 0.4) {
const i1 = new Set(network1.connections.map((c) => c.innovation));
const i2 = new Set(network2.connections.map((c) => c.innovation));
const disjoint =
[...i1].filter((i) => !i1.has(i)).length +
[...i2].filter((i) => !i2.has(i)).length;
const excess = Math.max(i1.size, i2.size) - Math.min(i1.size, i2.size);
const matching = network1.connections.filter((c1) => i2.has(c1.innovation));
const avgWeightDiff =
matching.reduce((sum, c1) => {
const c2 = network2.connections.find(
(c) => c.innovation === c1.innovation
);
return sum + Math.abs(c1.weight - c2.weight);
}, 0) / matching.length;
const N = Math.min(i1.size, i2.size) > 20 ? Math.min(i1.size, i2.size) : 1;
return (c1 * excess) / N + (c2 * disjoint) / N + c3 * avgWeightDiff;
}
@esshka
Copy link
Author

esshka commented Mar 23, 2023

c1: This coefficient assigns importance to the excess genes. Excess genes are those that have higher innovation numbers in one genome compared to the other. A larger c1 value means that genomes with more excess genes are considered more dissimilar.

c2: This coefficient assigns importance to the disjoint genes. Disjoint genes are those with innovation numbers present in one genome but not in the other. A larger c2 value means that genomes with more disjoint genes are considered more dissimilar.

c3: This coefficient assigns importance to the average weight differences between matching genes (i.e., genes with the same innovation numbers in both genomes). A larger c3 value means that genomes with greater weight differences are considered more dissimilar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment