Skip to content

Instantly share code, notes, and snippets.

@MrLeebo
Last active April 9, 2018 20:22
Show Gist options
  • Save MrLeebo/5ba106cdaae31df63c4d59aaa497d94b to your computer and use it in GitHub Desktop.
Save MrLeebo/5ba106cdaae31df63c4d59aaa497d94b to your computer and use it in GitHub Desktop.
Learning neural networks
const brain = require('brain.js')
const mimir = require('mimir')
const net = new brain.NeuralNetwork
// The specific structure here isn't important, this exists
// simply to teach the NN these words.
const voc = mimir.dict([
"a conflict of programmers",
"a murder of crows",
"a flock of geese",
"all other things are known as a group"
])
// Converts words into arrays of 0s and 1s, e.g. bow`conflict` => [0,1,0,0,0,0,0,0]
// Uses template syntax just to make the training data a little more readable.
const bow = ([term]) => mimir.bow(term, voc)
// Opposite of `bow`, converting output back to words.
const word = data => voc.words[data.indexOf(1)]
// Test the neural network with a particular term
const test = ([term]) => {
const result = word(net.run(bow([term])).map(Math.round))
console.log(`A ${result} of ${term}`)
}
const trainingData = [
{ input: bow`programmers`, output: bow`conflict` },
{ input: bow`crows`, output: bow`murder` },
{ input: bow`geese`, output: bow`flock` },
{ input: bow``, output: bow`group` }
]
console.log("NN trained:", net.train(trainingData))
test`programmers`
test`crows`
test`geese`
test`dwarves`
test`elves`
NN trained: { error: 0.004977871869409048, iterations: 540 }
A conflict of programmers
A murder of crows
A flock of geese
A group of dwarves
A group of elves
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment