0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

tensorflow.jsAdvent Calendar 2019

Day 6

plunkerでtensorflow.js その16

Last updated at Posted at 2019-11-04

#概要

plunkerでtensorflow.jsやってみた。
lstm使ってみた。
abならc、bcならd、xyならzと学習させて、
abでcが出たら、bcにして、推定繰り返して、
abcを答えさせる実験。

#サンプルコード

tf.setBackend('cpu');
let index2alphabet = [];
let alphabet2vector = {};
let trainXArray = [], 
  trainYArray = [];
for (let i = 0; i < 26; i++) 
{
  index2alphabet[i] = String.fromCharCode('a'.charCodeAt(0) + i);
}
for (let i = 0; i < 26; i++) 
{
  alphabet2vector[index2alphabet[i]] = Array(26).fill(0);
  alphabet2vector[index2alphabet[i]][i] = 1;
}
trainXArray.push([alphabet2vector['y'], alphabet2vector['z']]);
trainYArray.push(alphabet2vector['a']);
trainXArray.push([alphabet2vector['z'], alphabet2vector['a']]);
trainYArray.push(alphabet2vector['b']);
for (let i = 0; i < 26 - 2; i++)
{
  trainXArray.push([alphabet2vector[index2alphabet[i]], alphabet2vector[index2alphabet[i + 1]]]);
  trainYArray.push(alphabet2vector[index2alphabet[i + 2]]);
}
const trainX = tf.tensor3d(trainXArray);
const trainY = tf.tensor2d(trainYArray);
const model = tf.sequential();
model.add(tf.layers.lstm({ 
  units: 64,
  returnSequences: false,
  inputShape: [2, 26]
}));
model.add(tf.layers.dense({
  units: 64, 
  activation: "relu"
}));
model.add(tf.layers.dense({
  units: 26, 
  activation: "softmax"
}));
model.compile({
  optimizer: 'adam',
  loss: 'categoricalCrossentropy'
});
model.fit(trainX, trainY, {
  epochs: 160,
  verbose: 0,
  validationData: [trainX, trainY],
}).then(() => {
  let i = 0;
  let p0 = 'y';
  let p1 = 'z';
  for (i = 0; i < 26; i++)
  {
    let testXArray = trainXArray;
    testXArray[0] = [alphabet2vector[p0], alphabet2vector[p1]];
    const testX = tf.tensor3d(testXArray);
    const predicts = model.predict(testX);
    const predictsArray = predicts.argMax().arraySync();
    const predictAlphabet = String.fromCharCode('a'.charCodeAt(0) + predictsArray[0]);
    document.write(predictAlphabet);
    p0 = p1;
    p1 = predictAlphabet;
    alert(p0 + ' ' + p1)
  }
});

#成果物

以上。

0
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?