search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

tfjs-node:Node.js 版本的 TensorFlow

不久前 Google 發表了 TensorFlow.js,終於把 TensorFlow 帶到瀏覽器上,不過對 Node.js 仍然不支援。現在 Google 終於把測試版本的 TensorFlow 丟到 npm 上了!

安裝 TensorFlow.js

首先透過 npm(或 yarn 也行)安裝 TensorFlow.js 和 TensorFlow.js 的 Node.js 版本:

npm install @tensorflow/tfjs
npm install @tensorflow/tfjs-node

之後再安裝對應版本的 NVDIA CUDA、cuDNN 就可以啦!

值得注意的是:

  • tfjs-node 還在測試中(Under development),可能不適合正式環境使用。
  • 目前只有 Linux、macOS 可以使用,~~Windows 的使用者可能無法。~~Windows 也能用啦!

開始使用 TensorFlow.js

首先要引入 TensorFlow.js:

const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');

tf.setBackend('tensorflow');

之後 TensorFlow 就會放在 tf 這個全域變數裡,接著我們改寫官方的範例來試試看 tf.js。

async function myFirstTfjs() {
	// Create a simple model.
	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. (y = 2x - 1)
	const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
	const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);

	// Train the model using the data.
	await model.fit(xs, ys, {epochs: 250});

	// Use the model to do inference on a data point the model hasn't seen.
	// Should print approximately 39.
	const output = model.predict(tf.tensor2d([20], [1, 1])).toString()
	console.log(output);
}

myFirstTfjs();

這個範例用來預測 $y=2x-1$ 這個方程式,而我們在 model.predict 的地方預測了 $20$,預期出來的結果應該要是 $39$。而這是我的預測結果:

[[38.4072647],]

還蠻接近 39 的。

上面的範例取自官方的 tfjs-examples,而為了適應後端環境,我只將最後的 document.getElementById(...).innerText += 改成 console.log 而已。如果有興趣,也能把手寫辨識的範例抓下來跑看看。

參考資料



熱門推薦

本文由 noobtw 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦