This library is a pure javascript implementation of a neural network. Let's try running one of the examples in the README:
var brain = require("brain") var net = new brain.NeuralNetwork(); net.train([{input: { r: 0.03, g: 0.7, b: 0.5 }, output: { black: 1 }}, {input: { r: 0.5, g: 0.5, b: 1.0 }, output: { white: 1 }}]); var output ={ r: 1, g: 0.4, b: 0 });
Cool, it works. But what is it doing exactly? The network is trying to learn about contrast. Given a background color, it makes a decision about whether or not black text or white text will be more readbale. Obvious, right? One thing we can do to help us understand is examine the actual properties of the net. We do this by just drilling into the object:
The biases and weights contain the data we need to actually compute a result, and those values were reached by running the training examples above through our network. Of course, it's still hard to really understand exactly what we're doing just looking at these numbers. Let's try examining the results visually:
function textColor(bgColor) { return > .5 ? "black" : "white"; } function toRGB(bgColor) { return "rgb(" + Math.floor(bgColor.r * 255) + ", " + Math.floor(bgColor.g * 255) + ", " + Math.floor(bgColor.b * 255) + ")" } function toDiv(bg, txt) { return '<div style="padding: 6px; background: ' + toRGB(bg) + '; color: '+txt+'">'+ toRGB(bg) + '</div>' } function sample() { var results = []; for (var i = 0; i < 50; i++) { var bg = {r: Math.random(), g: Math.random(), b: Math.random()} var txt = textColor(bg); results.push(toDiv(bg, txt)); } return results; } sample().join("\n");
We've mapped the rgb values to either a black or white text color, and shown the output above as rendered HTML. It's pretty easy to see that with just three training examples we still have a lot of room for improvement. Let's try feeding it 10 more.
net.train([ {"input":{"r":0.0431,"g":0.3458,"b":0.2627},"output":{"black":0}}, {"input":{"r":0.9333,"g":0.8784,"b":0.5686},"output":{"black":1}}, {"input":{"r":0.3490,"g":0.2705,"b":0.8901},"output":{"black":0}}, {"input":{"r":0.3843,"g":0.4862,"b":0.0941},"output":{"black":0}}, {"input":{"r":0.2274,"g":0.0078,"b":0.8627},"output":{"black":0}}, {"input":{"r":0.3764,"g":0.3843,"b":0.6941},"output":{"black":0}}, {"input":{"r":0.2862,"g":0.5960,"b":0.0470},"output":{"black":0}}, {"input":{"r":0.6549,"g":0.7019,"b":0.7098},"output":{"black":1}}, {"input":{"r":0.0431,"g":0.0666,"b":0.4862},"output":{"black":0}}, {"input":{"r":0.8431,"g":0.4431,"b":0.2627},"output":{"black":0}}, ]) sample().join("\n")
The results are definitely an improvement! You can see another version of this demo, and learn more about Brain.js at

no comments

    sign in to comment