Skip to content

Instantly share code, notes, and snippets.

@tehZevo
Created August 16, 2018 23:47
Show Gist options
  • Save tehZevo/91ddeaf2d308c1c4fdfa02a8d0f4328b to your computer and use it in GitHub Desktop.
Save tehZevo/91ddeaf2d308c1c4fdfa02a8d0f4328b to your computer and use it in GitHub Desktop.
//this example was tested in electron; if anyone knows how to get around
//this silliness when using nodejs/electron (without including the .js file in
//html, please let me know)
var tfCore = require("@tensorflow/tfjs-core");
var tfLayers = require("@tensorflow/tfjs-layers");
var tf = Object.assign({}, tfCore, tfLayers);
var xs = tf.tensor([[0, 0], [0, 1], [1, 0], [1, 1]]);
var ys = tf.tensor([[0], [1], [1], [0]]);
var hiddenSize = 10;
var hiddenWeights = tf.variable(tf.randomNormal([2, hiddenSize]), true);
var hiddenBias = tf.variable(tf.zeros([hiddenSize]), true);
var hiddenActivation = tf.relu;
var outputWeights = tf.variable(tf.randomNormal([hiddenSize, 1]), true);
var outputBias = tf.variable(tf.zeros([1]), true);
var outputActivation = tf.tanh;
function apply(x)
{
x = x.dot(hiddenWeights);
x = x.add(hiddenBias);
x = hiddenActivation(x);
x = x.dot(outputWeights);
x = x.add(outputBias);
x = outputActivation(x);
return x;
}
var opt = tf.train.adam(0.01);
var epochs = 1000;
for(var i = 0; i < epochs; i++)
{
var loss = opt.minimize(() =>
{
var pred = apply(xs);
return tf.losses.meanSquaredError(ys, pred);
}, true).dataSync()[0];
console.log(loss);
}
console.log(apply(xs).dataSync());
@tehZevo
Copy link
Author

tehZevo commented Aug 16, 2018

basically-no-cruft XOR solution in tfjs ops api

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment