Tensorflow JS transform 1d tensor into 2d tensor structured as square diagonal matrix

Viewed 66

Let's see an easy example, I have a tensor [1,2]. The position of 1 is [0], the position of 2 is [1]. I want to transform this 1d tensor into 2d, where the position of

  • 1 would turn from [0] to [0, 0]
  • 2 would turn from [1] to [1, 1] to make the new tensor look like this:
[
  [1, 0],
  [0, 2],
]

Is there a method for that?

1 Answers

Assuming you need to transform the list of items into square diagonal matrix, you may use 2 nested Array.prototype.map() to build up 2d-structure:

const arr = [1,2,3,4,5],

      listToMatrix = a =>
        a.map((_,i) => 
          a.map((e, j) => 
            i == j ? e : 0))
          
console.log(listToMatrix(arr))
.as-console-wrapper{min-height:100%;}

Related