#概要
tensorflow.jsでxor問題やってみた。
#サンプルコード
const model = tf.sequential();
model.add(tf.layers.dense({
units: 20,
activation: 'relu',
inputShape: [2]
}));
model.add(tf.layers.dense({
units: 2,
activation: 'softmax'
}));
model.compile({
optimizer: 'Adam',
loss: 'categoricalCrossentropy',
metrics: ['accuracy'],
});
const xs = tf.tensor2d([[1, 0], [0, 1], [1, 1], [0, 0]], [4, 2]);
const ys = tf.tensor2d([[1, 0], [1, 0], [0, 1], [0, 1]], [4, 2]);
model.fit(xs, ys, {
batchSize: 4,
epochs: 1000
}).then((d) => {
var str = "loss = ";
str += d.history.loss[0];
str += "<br>1, 1 = ";
var pre0 = model.predict(tf.tensor2d([1, 1], [1, 2]));
str += pre0.argMax().dataSync() + "<br>0, 0 = ";
var pre1 = model.predict(tf.tensor2d([0, 0], [1, 2]));
str += pre1.argMax().dataSync() + "<br>0, 1 = ";
var pre2 = model.predict(tf.tensor2d([0, 1], [1, 2]));
str += pre2.argMax().dataSync() + "<br>1, 0 = ";
var pre3 = model.predict(tf.tensor2d([1, 0], [1, 2]));
str += pre3.argMax().dataSync() + "<br>";
document.write(str);
});
#成果物
http://jsdo.it/ohisama1/SBmN
以上。