Created
July 15, 2022 11:31
-
-
Save LiorB-D/a78d79ed2c97a879a79033c8961228ba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function startNewGen() { | |
totalFitness = endGen(); | |
let newCarArr = []; // The next generation | |
mutationRate = mrateInput.value() // Pull mutation rate | |
//Get parent weights | |
let parentWeights = []; | |
cars.forEach((c) => { | |
parentWeights.push(c.copyWeights()); | |
}); | |
//Create next generation | |
for (let i = 0; i < 10; i++) { | |
// Initialize Child | |
const child = new Car( | |
outerDi, | |
innerDi, | |
screenHt, | |
screenWd, | |
carDi, | |
obsts | |
); | |
let currWeights = child.model.getWeights(); | |
let newWeights = []; | |
for (let i = 0; i < currWeights.length; i++) { | |
// Iterate through each layer | |
//Get Current Weight information | |
let currVals = currWeights[i].dataSync(); // Array format | |
let shape = currWeights[i].shape; | |
for (let j = 0; j < currVals.length; j++) { | |
// Iterate through each weight | |
// Select trait from random parent | |
currVals[j] = parentWeights[selectRandParent(totalFitness)][i][j]; | |
// Assign random value to weight from Gaussian Distribution(Function from P5) | |
if(random() < mutationRate) { | |
currVals[j] += randomGaussian() | |
} | |
} | |
let newTens = tf.tensor(currVals, shape); | |
newWeights[i] = newTens; | |
} | |
child.model.setWeights(newWeights); | |
newCarArr.push(child); | |
} | |
cars = newCarArr; | |
// Increment Generation and Update Label | |
currGen += 1; | |
infoLbl.elt.innerText = | |
"Gen: " + currGen + ", Top Score: " + topFitnessScore; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment