Help: General problem comparing numpy to TF.js functionality

I love this library a lot, but finally found a close road.

Using NumPy I can do:

myArray[ :, :4] = myArray[:,:4]*2

And in this case all the rows and all the columns 0,1,2,3 are multiplied by 2.

I know I can do this in javascript:

const slice0 = myTensor.slice([[0,4], [0, -1]])
const slice1 = myTensor.slice([[0,0], [0,4]]).mul(2)

but then using concatenations creates a lot of garbage as far as I know.

Is there any recommended why to do it?

Maybe I am misunderstanding as I am not a Python dev but in TFJS to multiply all values in a tensor by 2 you would just call something like:

let a = tf.scalar(2);
let myTensor = tf.tensor([[1,2,3,4,5], [6,7,8,9,10]]);

Would log to the console:

    [[2 , 4 , 6 , 8 , 10],
     [12, 14, 16, 18, 20]]

Not quite. I explain better here. Take this rank 2 tensor:

// tensor A

// expected result, column 1 by 2
// still tensor A 

In numpy, you just mutate the column

In numpy you’d do:

myArray[ :, 1:2] = myArray[:,1:2]*2

What you suggest is creating a new Tensor as far as I am aware, and will waste memory.

Ah I see sorry I understand now (sorry got a cold this week so head not quite with it today).
I assume the 5 in your example is an error and you just want to manipulate the middle column and multiply those by 2.

Yes AFAIK you would have to grab the subset you want and call .mul(2) on that and then concat result back in as you hinted at in your original post.

Also Tensorflow Tensors (both Python and TFJS) are immutable so you can not change a tensor without creating a new version of it in memory anyhow. So I think to do something like this you would need to be working at the array level in your language of choice.

1 Like

I see. It is a shame that we can not “edit” or “mutate” the tensors, but thank you for the comment and yes the 5 is a typo