Search code examples
tensorflow.js

How to check if two tensors are equal


Given two tensors of any rank, how can I tell if they both are the same, have I to set my propre solution of there is any kind of implementation of this comparaison


Solution

  • To check if two tensors are equal, one can use tf.equal. But it returns a tensor, a result of a bitwise operation. This tensor elements are whether 1 or 0. Therefore computing the sum of the later tensor should give the number of elements of the tensor if both tensors are equal.

        const a = tf.tensor([1, 2, 3, 4], [2, 2]);
        const b = tf.tensor([1, 2, 3, 4], [2, 2]);
        const c = a.equal(b).sum().dataSync()[0]
        
        console.log(c)
        
        c === a.shape.reduce((a,b) => a *= b) ? console.log("true") : console.log("false")
    <html>
      <head>
        <!-- Load TensorFlow.js -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/tensorflow/0.12.4/tf.js"> </script>
      </head>
    
      <body>
      </body>
    </html>