要深入了解TensorFlow.js的功能,可以查看官方文档:https://www.tensorflow.org/js
mkdir tfjs-project cd tfjs-project2.初始化一个新的Node.js项目:
npm init -y3.安装TensorFlow.js:
npm install @tensorflow/tfjs4.创建一个HTML文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>TensorFlow.js Example</title> </head> <body> <script src="node_modules/@tensorflow/tfjs/dist/tf.min.js"></script> <script src="main.js"></script> </body> </html>6.创建一个JavaScript文件:
import * as tf from '@tensorflow/tfjs'; // 定义一个简单的模型 const model = tf.sequential(); model.add(tf.layers.dense({units: 1, inputShape: [1]})); // 编译模型 model.compile({optimizer: 'sgd', loss: 'meanSquaredError'}); // 堆代码 duidaima.com // 生成一些训练用的合成数据 const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]); const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]); // 训练模型 model.fit(xs, ys, {epochs: 10}).then(() => { // 使用模型进行预测 model.predict(tf.tensor2d([5], [1, 1])).print(); });7.运行本地服务器:使用http-server工具本地运行文件。
npm install -g http-server http-server在Node.js中使用TensorFlow.js
mkdir tfjs-node-project cd tfjs-node-project2.初始化一个新的Node.js项目:
npm init -y3.安装TensorFlow.js for Node.js:
npm install @tensorflow/tfjs-node4.创建一个JavaScript文件:
const tf = require('@tensorflow/tfjs-node'); // 定义一个简单的模型 const model = tf.sequential(); model.add(tf.layers.dense({units: 1, inputShape: [1]})); // 编译模型 model.compile({optimizer: 'sgd', loss: 'meanSquaredError'}); // 生成一些训练用的合成数据 const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]); const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]); // 训练模型 model.fit(xs, ys, {epochs: 10}).then(() => { // 使用模型进行预测 model.predict(tf.tensor2d([5], [1, 1])).print(); });5.运行你的Node.js脚本:
node main.js三.构建和训练机器学习模型
const model = tf.sequential(); model.add(tf.layers.dense({units: 10, inputShape: [4]})); model.add(tf.layers.dense({units: 1})); model.compile({optimizer: 'adam', loss: 'meanSquaredError'});示例:功能性模型
const input = tf.input({shape: [4]}); const dense1 = tf.layers.dense({units: 10, activation: 'relu'}).apply(input); const output = tf.layers.dense({units: 1}).apply(dense1); const model = tf.model({inputs: input, outputs: output}); model.compile({optimizer: 'adam', loss: 'meanSquaredError'});训练模型
const xs = tf.tensor2d([[1, 2, 3, 4], [2, 3, 4, 5]], [2, 4]); const ys = tf.tensor2d([[5], [7]], [2, 1]); model.fit(xs, ys, {epochs: 10, batchSize: 2}).then(() => { model.predict(tf.tensor2d([[3, 4, 5, 6]], [1, 4])).print(); });实际应用案例
const img = document.getElementById('image'); const model = await tf.loadGraphModel('https://tfhub.dev/google/tfjs-model/imagenet/mobilenet_v2_140_224/classification/3/default/1'); const tensor = tf.browser.fromPixels(img).resizeNearestNeighbor([224, 224]).toFloat().expandDims(); const predictions = await model.predict(tensor).data(); console.log(predictions);2.自然语言处理(NLP)
const model = await tf.loadLayersModel('https://tfhub.dev/google/tfjs-model/toxicity/1/default/1/model.json'); const sentences = ['I love this!', 'I hate this!']; const predictions = await model.classify(sentences); predictions.forEach((p, i) => { console.log(`${sentences[i]}: ${p.label} - ${p.results[0].match}`); });3.实时对象检测
const video = document.getElementById('video'); const model = await tf.loadGraphModel('https://tfhub.dev/tensorflow/tfjs-model/coco-ssd/1/default/1/model.json'); const detectObjects = async () => { const predictions = await model.detect(video); console.log(predictions); }; video.addEventListener('play', () => { setInterval(detectObjects, 100); });性能考虑和优化技巧
const model = await tf.loadLayersModel('model.json', {fromTFHub: true, useWebGL: true});优化模型大小:较小的模型加载和运行更快。使用模型量化和剪枝技术来减少模型大小。