How to verify if an object is a tf tensor in javascript?

Using typeof() on a tf tensor only returns object.

Using isinstancof object, or isinstanceof tf.tensor, will generate syntax error of missing ) after argument list

So, how to verify an object is a tf tensor on which we can apply tensor related operations?

import * as tf from "@tensorflow/tfjs";    
const a = tf.tensor([[1, 2], [3, 4]]);
console.log('type:', typeof(a));
// returns "object"

You can simply print in the console the variable assigned to console and that would print Tensor if the object is tf object.
For Example
import * as tf from "@tensorflow/tfjs";
console.log(tf.tensor([1, 2, 3]))
Output:
1

Thanks for the suggestion, @Aseem_Mangla

However, I wonder if there is a direct way to get a response that a given object is a “tensorflow tensor” in particular, or not.

E.g. we will get class torch.Tensor when we ask the type of a PyTorch tensor as shown below:

import torch 
import numpy as np 

data = [[1, 2], [3, 4], [5, 6]]

t1 = torch.tensor(data)

print(type(t1))

# output is: 
# <class 'torch.Tensor'>

Doesn’t instanceof work?

1 Like

Allow me to reply myself.

This question is actually about how to get an instance object’s class name.

The solutions are shown in the code below:

import * as tf from "@tensorflow/tfjs";

const a = tf.randomNormal([3, 4, 5]);
a.print();

console.log('type of a \t\t:', typeof(a));                      // returns a string     "object"
console.log('a is an instance of \t:', a instanceof tf.Tensor); // returns a boolean    "true"
console.log('constructor of a \t:', a.constructor);             // returns a function   "Tensor(){}"
console.log('constructor name of a \t:', a.constructor.name);   // returns a string     "Tensor"

// reference link : 
// https://stackoverflow.com/questions/1249531/how-to-get-a-javascript-objects-class?rq=1

function getNativeClass(obj) {
  if (typeof obj === "undefined") return "undefined";
  if (obj === null) return "null";
  return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
}

function getAnyClass(obj) {
  if (typeof obj === "undefined") return "undefined";
  if (obj === null) return "null";
  return obj.constructor.name;
}

console.log('getAnyClass of a \t:', getAnyClass(a));        // returns a string   "Tensor"
console.log('getNativeClass of a \t:', getNativeClass(a));  // returns a string   "object"

[codeSandBox link]

[stackoverflow reference link]

1 Like