【问题标题】:How to use tensorflow js on a nodejs server?如何在 nodejs 服务器上使用 tensorflow js?
【发布时间】:2020-05-31 09:29:21
【问题描述】:

我想在服务器端使用带有 cocossd 的 tensorflow js 插件和带有 nodejs 的 mobilenet。 我已经在客户端完成了一个脚本,当用户提交表单时我运行 tfjs:

const img = new Image(100, 100);
img.src = //base64 encoded image

// Load the model.
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 => {
            // detect objects in the image.
            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)
            });
        })
    });
});

我想在服务器端做同样的事情,但我知道节点需要什么模块或如何从它的 base 64 加载图像。

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

npm i @tensorflow-models/mobilenet

npm i @tensorflow-models/coco-ssd

然后我尝试为节点安装 tensorflow js:

npm i @tensorflow/tfjs-node

但是当我这样做时:

npm 我张量流

我收到此错误:

npm 错误!代码EBADPLATFORM

npm 错误! notsup 不支持 tensorflow@0.7.0 的平台:想要 {"os":"linux,darwin","arch":"any"}(当前:{"os":"win32","arch":"x64"} )

npm 错误! notsup 有效操作系统:linux,darwin

npm 错误! notsup 有效拱门:任何

npm 错误! notsup 实际操作系统:win32

npm 错误! notsup 实际拱门:x64

npm 错误!可以在以下位置找到此运行的完整日志:

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

请有人帮助我吗???? 谢谢

【问题讨论】:

    标签: javascript node.js image tensorflow artificial-intelligence


    【解决方案1】:

    当我执行“npm i @tensorflow-models/mobilenet”时,我也遇到了不同的问题。
    这是屏幕截图。
    看来包裹有问题。

    您可以尝试这样做。

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

    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.7.1/dist/tf.min.js"> </script> //
    <!-- Load the MobileNet model. -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet@2.0.4/dist/mobilenet.min.js"> </script>
    

    以下是步骤:
    1. 使用 npm init 创建一个简单的节点项目。这将创建一个 package.json 文件。这是软件包所在或列出的位置。
    2. 请注意,您需要在命令行中点击“npm install express --save”,以便将 express 包添加到 packages.json
    3. 使用以下代码创建一个 index.html 文件。在 UI 方面,系统会要求您上传一张图片,该图片将在控制台上进行评估或显示为警报消息。

    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.7.1/dist/tf.min.js"> </script> //
    <!-- Load the MobileNet model. -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet@2.0.4/dist/mobilenet.min.js"> </script>
    <input type='file' />
    <br><img id="myImg" src="#" alt="your image will be displayed here" >
    
    <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]); // set src to blob url
              img.onload = imageIsLoaded;
          }
      });
    });
    
    
    
    async function run() {
        const img = document.getElementById('myImg');
        print(img)
        const version = 2;
        const alpha = 0.5;
        // Load the model.
        const model = await mobilenet.load({version, alpha});
    
        // Classify the image.
        const predictions = await model.classify(img);
        console.log('Predictions');
        console.log(predictions);
    
        // Get the logits.
        const logits = model.infer(img);
        console.log('Logits');
        logits.print(true);
    
        // Get the embedding.
        const embedding = model.infer(img, true);
        console.log('Embedding');
        embedding.print(true);
      }
    
    function imageIsLoaded() { 
      run();
    }
    
    </script>
    

    第 3 步:创建 server.js。该文件将用于使用 express npm 包在本地服务器上呈现索引文件。 下面是代码:

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

    第 4 步:转到浏览器并点击 localhost:3000
    下面是该项目的工作截图。

    更新:在 NODEJS 上加载
    问题似乎出在安装顺序上
    第 1 步:安装以下软件包

    npm install @tensorflow/tfjs @tensorflow/tfjs-node --save
    // or...
    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')
    // Load the binding (CPU computation)
    const mobilenet = require('@tensorflow-models/mobilenet');
    
    // for getting the data images
    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){
        // Load the model.
        const model = await mobilenet.load();
    
        // Classify the image.
        const predictions = await model.classify(img);
    
        console.log('Predictions: ');
        console.log(predictions);
    }
    

    预测的屏幕截图

    【讨论】:

    • 是的。谢谢。实际上我正在这样做,但是当我们提交表单时,我们希望它快。但是在客户端,张量流真的很慢,有时甚至会导致计算机崩溃。所以这就是为什么我想在 nodejs 服务器端异步执行它。
    • 嗨@YoyoBu,我添加了一个使用nodejs的示例实现。问题似乎是,您错过了我上面更新中的一个步骤。让我知道这是否适合您。谢谢
    • 好的。我会尝试。但是 tfjs-node-gpu 和 tfjs-node 有什么区别呢?
    • 是的,这些包只是依赖项。与此同时,你可以忽略它。关于 tfjs-node-gpu,你会在你的服务器有 GPU 时安装它。
    【解决方案2】:

    我使用@tensorflow-models/coco-ssd 和@tensorflow/tfjs-node 完成了这项工作。

    我发布答案的原因是为了展示我是如何获得图像数据的。 TF_Support's answer 有这个代码:

    // for getting the data images
    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)
    });
    

    而我刚刚做了这个,它似乎工作:

    const image = await tf.node.decodeImage(resp.body, 3);
    const catObjects = await catModel.detect(image);
    image.dispose();
    

    catObjects 在哪里

    catModel = await cocoSsd.load();
    
    

    在我的代码中,我有:

    const tf = require("@tensorflow/tfjs-node");
    const cocoSsd = require("@tensorflow-models/coco-ssd");
    

    我不确定您是否需要使用 get-image-data 包。此处的结果是相同的——两种方法最终都会输出 3d 张量。
    引用the tfjs-node docs:

    给定图像的编码字节,它返回解码图像的 3D 或 4D 张量。支持 BMP、GIF、JPEG 和 PNG 格式。

    注意事项:

    我仍然收到说它很慢的警告:

    “您好 wave 看起来您正在 Node.js 中运行 Tensorflow.js....”
    等等,(见 TF_Support 的回答),但它的工作原理。

    请注意,我提出了一个关于如何摆脱该消息并正确使用资源来加快处理速度的问题:

    Tensorflow-node not recognized with cocoSsd on node.js

    【讨论】:

    • RE:“上面的答案”:直接回复另一个答案的唯一方法是在该帖子的评论部分。如果你想引用一个特定的帖子,你需要包含链接。(点击过去下方的share复制它)。任何页面上显示的订单答案取决于访问者设置(日期、赞成票等),并且随着答案的添加、删除和投票也会随着时间的推移而变化。
    • 谢谢!我是新来的。我确实想链接到帖子,但我不知道该怎么做,所以很高兴知道分享按钮信息。我现在就编辑这个。
    • 太棒了。我修复了这个...对于以后的帖子,请查看 markdown 的格式,而不是使用 html。另外,欢迎来到 SO!
    猜你喜欢
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 2019-01-04
    • 2017-06-08
    相关资源
    最近更新 更多