Skip to content

Instantly share code, notes, and snippets.

@sempostma
Last active May 28, 2018 16:59
Show Gist options
  • Save sempostma/ba2beef73f2545aafbc0f68e69dcd720 to your computer and use it in GitHub Desktop.
Save sempostma/ba2beef73f2545aafbc0f68e69dcd720 to your computer and use it in GitHub Desktop.
const { Architect, Trainer } = synaptic;
const int = Math.floor;
const catagorical = i => {
const arr = new Array(26).fill(0);
arr[i] = 1;
return arr;
};
Jimp.loadFont(Jimp.FONT_SANS_16_BLACK).then(function (font) {
const trainingData = new Array(26);
for (let i = 0; i < 26; i++) {
const letter = String.fromCharCode(65 + i);
const image = new Jimp(16, 16);
image.opaque();
image.brightness(1);
image.print(font, 0, 0, letter);
// image.write(`training-images/${letter}.png`);
const d = image.bitmap.data;
trainingData[i] = {
input: catagorical(i),
output: new Array(16 * 16).fill(0)
.map((x, i) => d[i * 4] + d[i * 4 + 1] + d[i * 4 + 2])
.map(c => c / 765)
};
}
let neuralNetwork = new Architect.Perceptron(26, 26, 16 * 16);
const trainer = new Trainer(neuralNetwork);
console.log('Please wait... This might take up to 10 minutes.');
trainer.train(trainingData, { iterations: 190 /* change to 300 for accurate results (longer loading times) */, rate: .04 });
console.log('Done training!');
// remove loading message
var loadingMessage = document.getElementById('msg');
loadingMessage.parentElement.removeChild(loadingMessage);
document.addEventListener('keypress', e => {
var code = String.fromCharCode(e.charCode).toUpperCase().charCodeAt(0);
if (code < 65 || code > 90) return alert('Invalid letter');
const res = neuralNetwork.activate(catagorical(code - 65));
const col = x => Math.max(0, Math.min(255, x * 255));
const image = new Jimp(16, 16);
image.bitmap.data = [].concat.apply([], res.map(c => [c, c, c, 1].map(col)));
image.getBase64(Jimp.MIME_JPEG, function (err, src) {
var img = document.createElement("img");
img.setAttribute("src", src);
document.body.appendChild(img);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment