0

More than 5 years have passed since last update.

Posted at

# 概要

tensorflow.jsでfizzbuzz問題やってみた。

# サンプルコード

function fizzbuzz(n) {
if (n % 15 == 0)
{
return [1, 0, 0, 0];
}
else if (n % 5 == 0)
{
return [0, 1, 0, 0];
}
else if (n % 3 == 0)
{
return [0, 0, 1, 0];
}
else
{
return [0, 0, 0, 1];
}
}
function toarray(n) {
var ary = new Array;
for (var i = -1 ; i < 7; i++)
{
var s = 1;
if (i > -1) s = 2 << i;
var b = n & (s)
if (b > 0)
{
ary.push(1.0);
}
else
{
ary.push(0.0);
}
}
return ary;
};
function tofizz(i, f) {
var str = "";
if (f == 3)
{
str = i;
}
else if (f == 2)
{
str = "fizz";
}
else if (f == 1)
{
str = "buzz";
}
else if (f == 0)
{
str = "fizzbuzz";
}
return str;
}
const model = tf.sequential();
units: 40,
activation: 'relu',
inputShape: [8]
}));
units: 4,
activation: 'softmax'
}));
model.compile({
loss: 'categoricalCrossentropy',
metrics: ['accuracy'],
});
const buffer = tf.buffer([100, 8]);
for (var i = 1; i < 101; i++)
{
var x = toarray(i);
for (var j = 0; j < 8; j++)
{
buffer.set(x[j], i - 1, j);
}
}
const xs = buffer.toTensor();
const buffer2 = tf.buffer([100, 4]);
for (i = 1; i < 101; i++)
{
x = fizzbuzz(i);
for (j = 0; j < 4; j++)
{
buffer2.set(x[j], i - 1, j);
}
}
const ys = buffer2.toTensor();
model.fit(xs, ys, {
batchSize: 100,
epochs: 1000
}).then((d) => {
var str = "loss = ";
str += d.history.loss[0];
for (i = 1; i < 101; i++)
{
str += "<br>" + i + " = ";
var pre0 = model.predict(tf.tensor2d(toarray(i), [1, 8]));
var f = pre0.argMax().dataSync();
str += tofizz(i, f);
}
document.write(str);
});

# 成果物

Register as a new user and use Qiita more conveniently

1. You get articles that match your needs
2. You can efficiently read back useful information
3. You can use dark theme
What you can do with signing up
0