TensorFlow.jsチュートリアル
TensorFlow.jsとは何ですか?
機械学習で人気のあるJavaScriptライブラリ。
ブラウザで機械学習モデルをトレーニングしてデプロイしましょう。
任意のWebアプリケーションに機械学習機能を追加しましょう。
TensorFlowの使用
TensorFlow.jsを使用するには、次のスクリプトタグをHTMLファイルに追加します。
例
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>
常に最新バージョンを使用するようにするには、次を使用します。
例2
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
TensorFlowは、Googleの内部で使用するためにGoogle Brain Teamによって開発されましたが、2015年にオープンソフトウェアとしてリリースされました。
2019年1月、Googleの開発者はTensorFlowのJavaScript実装であるTensorFlow.jsをリリースしました。
Tensorflow.jsは、Pythonで記述された元のTensorFlowライブラリと同じ機能を提供するように設計されています。
テンソル
TensorFlow.jsは、Tensorを定義および操作するためのJavaScriptライブラリです。
テンソルは多次元配列とほとんど同じです。
テンソルには、(1つ以上の)次元形状の数値が含まれています。
Tensorには次の主なプロパティがあります。
財産 | 説明 |
---|---|
dtype | データ型 |
ランク | 次元数 |
形 | 各寸法のサイズ |
テンソルの作成
テンソルは、任意のN次元配列から作成できます。
例1
const tensorA = tf.tensor([[1, 2], [3, 4]]);
例2
const tensorA = tf.tensor([[1, 2], [3, 4], [5, 6]]);
テンソル形状
テンソルは、配列と形状パラメーター から作成することもできます。
例1
const shape = [2, 2];
const tensorA = tf.tensor([1, 2, 3, 4], shape);
例2
const tensorA = tf.tensor([1, 2, 3, 4], [2, 2]);
例3
const tensorA = tf.tensor([[1, 2], [3, 4]], [2, 2]);
テンソルデータ型
Tensorは、次のデータ型を持つことができます。
- ブール
- int32
- float32(デフォルト)
- complex64
- ストリング
テンソルを作成するとき、3番目のパラメーターとしてデータ型を指定できます。
例
const tensorA = tf.tensor([1, 2, 3, 4], [2, 2], "int32");
/*
Results:
tensorA.rank = 2
tensorA.shape = 2,2
tensorA.dtype = int32
*/
テンソル値を取得する
tensor.data()を使用して、テンソルの背後にあるデータを取得できます。
例
const tensorA = tf.tensor([[1, 2], [3, 4]]);
tensorA.data().then(data => display(data));
// Result: 1,2,3,4
function display(data) {
document.getElementById("demo").innerHTML = data;
}
tensor.array()を使用して、テンソルの背後にある配列を取得できます。
例
const tensorA = tf.tensor([[1, 2], [3, 4]]);
tensorA.array().then(array => display(array[0]));
// Result: 1,2
function display(data) {
document.getElementById("demo").innerHTML = data;
}