LoginSignup
40
44

More than 5 years have passed since last update.

Parcelで始めるTensorFlow.js (ブラウザ/Node.js)

Last updated at Posted at 2018-04-02

2018年3月末にGoogleがTensorFlow.js発表しました。
早速触ってみたので、Parcelを使って「TensorFlow.js - Getting Started」に掲載されているコードをブラウザとNode.jsで動かすまでを紹介します。
成果物は 「shisama/tfjs-practice#getting-started」にあります。

以下の環境で動作確認済
- Chrome: 65
- Node.js: 8.9.1

TL;DR

  • ビルドはparcel使うだけ
  • ブラウザでもNode.jsでも動かすことができる
  • とにかく始めたい人はこれ使ってください

Tensorflow.jsをインストール

TensorFlow.js - Getting Started」に載っているそのままです。

npm
npm install @tensorflow/tfjs
yarn
yarn add @tensorflow/tfjs

Parcelをインストール

Parcelに関しては、昨年末バズった「webpack時代の終わりとparcel時代のはじまり」という記事をお読み下さい。
以下はグローバルにインストールしていますが、--save-devでプロジェクトにインストールしても、もちろん問題ありません。

npm
npm install -g parcel-bundler
yarn
yarn global add parcel-bundler

Tensorflow.jsを使ったコード

TensorFlow.js - Getting Started」に載っているそのままです。
ここではファイル名をmain.jsにします。

main.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]}));

// Prepare the model for training: Specify the loss and the optimizer.
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).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();
});

ブラウザ用HTML

ここではビルド後のJavaScriptファイルを読み込むだけのHTMLファイルを用意します。
あとから紹介するparcelでのビルドでこのhtmlを指定します。

index.html
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script src="main.js"></script>
</body>
</html>

ブラウザで動かす

まずはブラウザで動かすためにparcelでビルドします。

parcel build index.html --public-url ./

ビルド後はdistというディレクトリが作成されています。

.
├── dist
│   ├── index.html
│   ├── main.31f12d6f.map
│   └── main.f903cd46.js
├── index.html
├── main.js
├── node_modules
├── package-lock.json
└── package.json

あとはdist/index.htmlをブラウザで開いてDevToolsのコンソールを確認してください。
リロードするたびにモデルの学習結果が変わります。

Node.jsで動かす

Node.jsで動かすためにJavaScriptをビルドします。
以下例ではビルド後のJavaScriptファイルをdist_nodeというディレクトリに出力するために-dオプションを付けています。

parcel build main.js -d dist_node

dist_nodeに出力されたJavaScriptファイルを実行します。

node dist_node/main.js

出力結果

ブラウザでもNode.jsでも実行内容は変わりません。以下は例です。
結果は学習結果によるので、以下とは違う結果になるかと思います。

Tensor
     [[8.2074938],]

参考

次にやること

babelだけでも問題無いはずなので試したい。webpackでもいけるはず。

最後までお読み頂きありがとうございました。
不備や質問はコメント欄またはTwitter(@shisama_)からお願い致します。

40
44
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
40
44