Skip to content

Instantly share code, notes, and snippets.

class NeuralNetwork {
constructor(
inputNodes,
hiddenNodes,
outputNodes,
learningRate,
bias,
trainingCycles,
normalizer
) {
normalize(inputArray) {
return inputArray.map((input) => {
return input / this.normalizer
})
}
feedforward(inputArray) {
inputArray = this.normalize(inputArray)
const input = Matrix.fromArray(inputArray)
const hidden = this.calculateFF(
input,
this.weightsInputToHidden,
this.biasForHidden
)
const output = this.calculateFF(
hidden,
module.exports = class Matrix {
static randomNormalized() {
let r = 0
const v = 4
for (let i = v; i > 0; i--) {
r += Math.random()
}
return r / v
}
class GeneticAlgorithm {
constructor(phraseToGuess, populationSize, mutationRate, pow) {
this.phraseToGuess = phraseToGuess
this.populationSize = populationSize
this.mutationRate = mutationRate
this.pow = pow
this.population = []
this.foundIndex = -1
this.cycle = 0
this.rateSum = 0
const mutationRate = 0.01
mutate(child) {
const chars = child.split('')
for (let i = 0; i < chars.length; i++) {
if (Math.random() <= mutationRate) {
chars[i] = newChar()
}
}
return chars.join('')
}
crossover(a, b) {
const midpoint = Math.floor(Math.random() * (phraseToGuess.length - 2)) + 1
let crossed = ''
for (let i = 0; i < phraseToGuess.length; i++) {
if (i <= midpoint) {
crossed += a[i]
} else {
crossed += b[i]
}
}
selection() {
let index = 0
let random = Math.random()
while (random > 0) {
random = random - population[index].powRate
index++
}
index-- // index++ jumped to the next phrase
return population[index]
}
DNAchanges() {
population.forEach((_, index) => {
const a = selection()
const b = selection()
let child = crossover(a.randomPhrase, b.randomPhrase)
child = mutate(child)
population[index].randomPhrase = child
})
}
normalization() {
let powSum = 0
population.forEach((p, i) => {
powSum += population[i].powRate
})
population.forEach((p, i) => {
population[i].powRate = p.powRate / powSum
})
}