question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

TF.JS on Node.js Error: Argument 'x' passed to 'slice' must be a Tensor, but got object

See original GitHub issue

TensorFlow.js version

@tensorflow/tfjs”: “^0.11.6”, “@tensorflow/tfjs-node”: “^0.1.7”

Browser version

  • none

Node.js version

$ node --version
v8.11.2

Describe the problem or feature request

I’m trying to convert a Tensorflow.js (ie the tfjs package) model example to the Node.js version (ie. tfjs-node package).

My import are the following:

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

This should be enough to load tfjs and tfjs-node bindings having tensorflow as default backend. The code loads a pre-trained model built in shards (the tfjs model format), and it’s as simple as:

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
        // 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)
    })

I get this error while running:

Error: Argument 'x' passed to 'slice' must be a Tensor, but got object.

that means that my input object is not a Tensor object instance, even if I can clearly see in the logs that I have

Tensor {
  isDisposedInternal: false,
  size: 100,
  shape: [ 1, 100 ],
  dtype: 'float32',
  strides: [ 100 ],
  dataId: {},
  id: 22,
  rankType: '2' }

a Tensor object instance when getting the tensor from the input buffer const input = inputBuffer.toTensor(); that converts a TensorflowBuffer to a Tensor object. This seems to not work properly in Node.js, while in the browser it works / or the assertion type check does not work as expected when in Node.js.

Code to reproduce the bug / link to feature request

Full code to reproduce the error: https://github.com/loretoparisi/tensorflow-node-examples/blob/master/sentiment/sentiment.js

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:6

github_iconTop GitHub Comments

3reactions
nsthoratcommented, Jun 28, 2018

Yes, you can use @tensorflow/tfjs-node-gpu!

1reaction
pyu10055commented, Jun 22, 2018

cc @caisq

Read more comments on GitHub >

github_iconTop Results From Across the Web

Argument 'x' passed to 'slice' must be a Tensor, but got object.
The warning is just letting you know that you can use the full power of TensorFlow, if you install the @tensorflow/tfjs-node package. It's...
Read more >
Tensorflow.js for Node.js Error: Argument 'x' passed to 'slice ...
I get this error while running: Error: Argument 'x' passed to 'slice' must be a Tensor, but got object. that means that my...
Read more >
tf.keras.Sequential | TensorFlow v2.11.0
Sequential groups a linear stack of layers into a tf.keras.Model. ... and y_pred are the model's predictions. y_true should have shape (batch_size, d0,...
Read more >
@tensorflow/tfjs-node - npm
You only need to include @tensorflow/tfjs-node or @tensorflow/tfjs-node-gpu in the package.json file, since those packages ship with @tensorflow ...
Read more >
NVIDIA Deep Learning TensorRT Documentation
Abstract. This NVIDIA TensorRT Developer Guide demonstrates how to use the C++ and Python APIs for implementing the most common deep learning layers....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found