ビルドにPARCELを使って、tensorflowのjavascript版のサンプルを動かしてみます。

 参考するサイトは、これ「Setup TensorFlow.js」です。

ファイル構成

 フォルダ、「first_tensorflowjs」を作成して、そのなかにこの3つのファイルを作っていきます。

準備

 まずは、package.jsonをこんな感じで用意します。

{
  "name": "first_parcel",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "@tensorflow/tfjs": "^0.14.2"
  }
}

  yarnコマンドでインストール

yarn install

実装

index.html

<html>
<body>
  hello tensorflow.js
  <script src="./index.js"></script>
</body>
</html>

index.js

import * as tf from '@tensorflow/tfjs';

// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));

model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

// Generate some synthetic data for training.
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);

// Train the model using the data.
model.fit(xs, ys, {epochs: 10}).then(() => {
  // Use the model to do inference on a data point the model hasn't seen before:
  model.predict(tf.tensor2d([5], [1, 1])).print();
  // Open the browser devtools to see the output
});

動作確認

 parcelコマンドを使って、localhost:1234で確認してみます。

parcel index.html

 こんな感じで、tensorflowのログが表示されます。