plunkerでtensorflow.js その2
1555 ワード
概要
plunkerでtensorflow.jsやってみた。
xorやってみた。
tf.modelで書いてみた。
サンプルコード
const xs = tf.tensor2d([[1, 0], [0, 1], [1, 1], [0, 0]], [4, 2]);
const ys = tf.tensor2d([[1], [1], [0], [0]], [4, 1]);
const input = tf.input({
shape: [2]
});
const layer1 = tf.layers.dense({
units: 8,
activation: 'tanh'
});
const layer2 = tf.layers.dense({
units: 1,
activation: 'sigmoid'
});
const output = layer2.apply(layer1.apply(input));
const model = tf.model({
inputs: input,
outputs: output
});
const opti = tf.train.adam(0.01);
model.compile({
optimizer: opti,
loss: 'meanSquaredError'
});
model.fit(xs, ys, {
batchSize: 4,
epochs: 1000,
}).then((d) => {
var str = "loss = ";
str += d.history.loss[0];
str += "<br><br>1, 1 = ";
var pre0 = model.predict(tf.tensor2d([1, 1], [1, 2]));
str += pre0.dataSync() + "<br>0, 0 = ";
var pre1 = model.predict(tf.tensor2d([0, 0], [1, 2]));
str += pre1.dataSync() + "<br>0, 1 = ";
var pre2 = model.predict(tf.tensor2d([0, 1], [1, 2]));
str += pre2.dataSync() + "<br>1, 0 = ";
var pre3 = model.predict(tf.tensor2d([1, 0], [1, 2]));
str += pre3.dataSync() + "<br>";
document.write(str);
});
成果物
const xs = tf.tensor2d([[1, 0], [0, 1], [1, 1], [0, 0]], [4, 2]);
const ys = tf.tensor2d([[1], [1], [0], [0]], [4, 1]);
const input = tf.input({
shape: [2]
});
const layer1 = tf.layers.dense({
units: 8,
activation: 'tanh'
});
const layer2 = tf.layers.dense({
units: 1,
activation: 'sigmoid'
});
const output = layer2.apply(layer1.apply(input));
const model = tf.model({
inputs: input,
outputs: output
});
const opti = tf.train.adam(0.01);
model.compile({
optimizer: opti,
loss: 'meanSquaredError'
});
model.fit(xs, ys, {
batchSize: 4,
epochs: 1000,
}).then((d) => {
var str = "loss = ";
str += d.history.loss[0];
str += "<br><br>1, 1 = ";
var pre0 = model.predict(tf.tensor2d([1, 1], [1, 2]));
str += pre0.dataSync() + "<br>0, 0 = ";
var pre1 = model.predict(tf.tensor2d([0, 0], [1, 2]));
str += pre1.dataSync() + "<br>0, 1 = ";
var pre2 = model.predict(tf.tensor2d([0, 1], [1, 2]));
str += pre2.dataSync() + "<br>1, 0 = ";
var pre3 = model.predict(tf.tensor2d([1, 0], [1, 2]));
str += pre3.dataSync() + "<br>";
document.write(str);
});
以上。
Author And Source
この問題について(plunkerでtensorflow.js その2), 我々は、より多くの情報をここで見つけました https://qiita.com/ohisama@github/items/7a76ffbdbcf5e73d1b79著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .