Tensorflow.js for Node.js错误:传递给'slice'的参数'x'必须是Tensor,但有对象

时间:2018-06-21 16:20:07

标签: javascript node.js tensorflow tensorflow.js

我正在尝试将- name: Convert hostnames to IPs command: "dig +short {{ item }}" register: command_output with_items: "{{list_of_hosts}}" when: ansible_default_ipv4.address in list_of_hosts - name: Store IPs set_fact: ip_list: "{{ item.stdout }}" with_items: "{{ command_output }}" (即Tensorflow.js包)模型示例转换为tfjs版本(即Node.js包)。

我的导入内容如下:

tfjs-node

这足以加载以const tf = require('@tensorflow/tfjs'); require('@tensorflow/tfjs-node'); tf.setBackend('tensorflow'); 作为默认后端的tfjstfjs-node绑定。

代码加载了一个以分片(tfjs模型格式)构建的预训练模型,它很简单:

tensorflow

我在运行时遇到此错误:

var fs = require('fs');
var performance = require('perf_hooks').performance;

const model_path = 'file://' + __dirname + '/model/model.json';
const model_metadata = __dirname + '/model/metadata.json';

var text = 'this is a bad day';

tf.loadModel(model_path)
    .then(model => {

        let sentimentMetadata = JSON.parse(fs.readFileSync(model_metadata));
        //console.log(sentimentMetadata);

        let indexFrom = sentimentMetadata['index_from'];
        let maxLen = sentimentMetadata['max_len'];
        let wordIndex = sentimentMetadata['word_index'];

        console.log('indexFrom = ' + indexFrom);
        console.log('maxLen = ' + maxLen);

        console.log('model_type', sentimentMetadata['model_type']);
        console.log('vocabulary_size', sentimentMetadata['vocabulary_size']);
        console.log('max_len', sentimentMetadata['max_len']);

        const inputText =
            text.trim().toLowerCase().replace(/(\.|\,|\!)/g, '').split(/\s+/g); // tokenized

        console.log(inputText);

        // Look up word indices.
        const inputBuffer = tf.buffer([1, maxLen], 'float32');
        for (let i = 0; i < inputText.length; ++i) {
            const word = inputText[i];
            if (typeof wordIndex[word] == 'undefined') { // TODO(cais): Deal with OOV words.
                console.log(word, wordIndex[word]);
            }
            inputBuffer.set(wordIndex[word] + indexFrom, 0, i);
        }
        const input = inputBuffer.toTensor();

        console.log(text, "\n", input);

        const beginMs = performance.now();
        const predictOut = model.predict(inputBuffer);
        const score = predictOut.dataSync()[0];
        predictOut.dispose();
        const endMs = performance.now();
        console.log({ score: score, elapsed: (endMs - beginMs) });

    })
    .catch(error => {
        console.error(error)
    })

这意味着我的Error: Argument 'x' passed to 'slice' must be a Tensor, but got object. 对象不是input对象实例,即使我可以在日志中清楚地看到

Tensor

从输入缓冲区获取张量时的Tensor { isDisposedInternal: false, size: 100, shape: [ 1, 100 ], dtype: 'float32', strides: [ 100 ], dataId: {}, id: 22, rankType: '2' } 对象实例:

Tensor

我问过TF.js group,有人建议这可能是由于导入错误造成的,而实际上可能是。

我的const input = inputBuffer.toTensor(); 就像

package.json

完整的示例和模型可用here

0 个答案:

没有答案