如何在Node.js服务器上使用TensorFlow.js?

我想在服务器端使用Node.js结合TensorFlow.js插件,并使用cocossd和mobilenet模型。我已经在客户端编写了一个工作脚本,当用户提交表单时,我会运行tfjs:

const img = new Image(100, 100);img.src = //base64 encoded image// 加载模型mobilenet.load().then(async model => {    const post_predictions = [];     model.classify(img).then(classify_predictions => {        classify_predictions.forEach(function(element){            const each_class = element["className"].split(", ")            each_class.forEach(function(this_element){                post_predictions.push([this_element, (element.probability*100)]);            })        })        cocoSsd.load().then(model => {            // 在图像中检测对象            model.detect(img).then(predictions => {                predictions.forEach(function(this_element){                    post_predictions.unshift([this_element.class, (this_element.score*100)]);                });                post_predictions.sort(function(a, b) {                    return b[1]-a[1];                });                console.log(post_predictions)            });        })    });});

我想在服务器端做同样的事情,但我不知道需要哪些模块,或者如何从base64加载图像。

我尝试在服务器上下载cocossd和mobilenet:

npm i @tensorflow-models/mobilenet

npm i @tensorflow-models/coco-ssd

然后我尝试为Node.js安装TensorFlow.js:

npm i @tensorflow/tfjs-node

但当我执行:

npm i tensorflow

我得到了以下错误:

npm ERR! code EBADPLATFORM

npm ERR! notsup Unsupported platform for [email protected]: wanted {“os”:”linux,darwin”,”arch”:”any”} (current: {“os”:”win32″,”arch”:”x64″})

npm ERR! notsup Valid OS: linux,darwin

npm ERR! notsup Valid Arch: any

npm ERR! notsup Actual OS: win32

npm ERR! notsup Actual Arch: x64

npm ERR! A complete log of this run can be found in:

npm ERR! C:\Users\johan\AppData\Roaming\npm-cache_logs\2020-02-16T05_27_15_276Z-debug.log

请有人帮帮我 🙏谢谢


回答:

当我执行”npm i @tensorflow-models/mobilenet”时,我也遇到了另一个问题。
这是截图。
看起来包有问题。enter image description here

你可以尝试这个替代方法。

所以我最终使用了TensorFlow mobilenet的CDN
请参考以下代码行

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"> </script> //<!-- 加载MobileNet模型。 --><script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/[email protected]/dist/mobilenet.min.js"> </script>

以下是步骤:
1. 使用npm init创建一个简单的Node项目。这将创建一个package.json文件。这是包所在或列出的地方。
2. 请注意,你需要在命令行中执行”npm install express –save”,这样express包将被添加到packages.json中
3. 创建一个包含以下代码的index.html文件。在用户界面方面,你将被要求上传一张图片,该图片将在控制台上进行评估或显示为警报消息。

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"> </script> //<!-- 加载MobileNet模型。 --><script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/[email protected]/dist/mobilenet.min.js"> </script><input type='file' /><br><img id="myImg" src="#" alt="你的图片将在这里显示" ><script>  window.addEventListener('load', function() {  document.querySelector('input[type="file"]').addEventListener('change', function() {      if (this.files && this.files[0]) {          var img = document.querySelector('img');  // $('img')[0]          img.src = URL.createObjectURL(this.files[0]); // 将src设置为blob url          img.onload = imageIsLoaded;      }  });});async function run() {    const img = document.getElementById('myImg');    print(img)    const version = 2;    const alpha = 0.5;    // 加载模型。    const model = await mobilenet.load({version, alpha});    // 分类图像。    const predictions = await model.classify(img);    console.log('预测');    console.log(predictions);    // 获取logits。    const logits = model.infer(img);    console.log('Logits');    logits.print(true);    // 获取嵌入。    const embedding = model.infer(img, true);    console.log('嵌入');    embedding.print(true);  }function imageIsLoaded() {   run();}</script>

步骤3: 创建一个server.js文件。该文件将使用express npm包在本地服务器上渲染index文件。以下是代码:

const express = require('express');app = express();app.get('/',function(req,res) {    res.sendFile('/demo/index.html', { root: __dirname });});const port = 3000app.listen(port, function(){    console.log(`正在监听端口 ${port}`);})

步骤4: 打开浏览器并访问localhost:3000
以下是项目工作截图。enter image description here

更新: 在Node.js上加载
看起来问题出在安装顺序上
步骤1: 安装以下包

npm install @tensorflow/tfjs @tensorflow/tfjs-node --save// 或者...npm install @tensorflow/tfjs @tensorflow/tfjs-node-gpu --save

步骤2: 现在你可以安装@tensorflow-models/mobilenet -save

npm install @tensorflow-models/mobilenet -save

步骤3: server.js示例用法

const tf = require('@tensorflow/tfjs')// 加载绑定(CPU计算)const mobilenet = require('@tensorflow-models/mobilenet');// 获取图像数据var image = require('get-image-data')image('./cup.jpg', async function (err, image) {    const numChannels = 3;    const numPixels = image.width * image.height;    const values = new Int32Array(numPixels * numChannels);    pixels = image.data    for (let i = 0; i < numPixels; i++) {        for (let channel = 0; channel < numChannels; ++channel) {            values[i * numChannels + channel] = pixels[i * 4 + channel];        }    }    const outShape = [image.height, image.width, numChannels];    const input = tf.tensor3d(values, outShape, 'int32');    await load(input)});async function load(img){    // 加载模型。    const model = await mobilenet.load();    // 分类图像。    const predictions = await model.classify(img);    console.log('预测: ');    console.log(predictions);}

预测的截图enter image description here

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注