Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

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.

plunkerでtensorflow.js その15

Last updated at Posted at 2019-11-03

概要

plunkerでtensorflow.jsやってみた。
argMax使ってみた。

サンプルコード


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: tf.train.adam(),
  loss: tf.losses.softmaxCrossEntropy
});
model.fit(trainX, trainY, {
  epochs: 160,
  verbose: 0,
  validationData: [trainX, trainY],
}).then(() => {
  const testX = tf.tensor3d(trainXArray);
  const predicts = model.predict(testX);
  const predictsArray = predicts.argMax().arraySync();
  for (let i = 0; i < predictsArray.length; i++) 
  {
    let predictAlphabet = String.fromCharCode('a'.charCodeAt(0) + predictsArray[i]);
    document.write(predictAlphabet);
  }
  alert("ok");
});

成果物

以上。

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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
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?