Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do matrix-scalar multiplication in TensorFlow?

Tags:

tensorflow

What would be the best way to multiply a matrix by a scalar in TensorFlow? I simply want to scale up the matrix by some scalar value.

Thanks!

like image 531
Alex Wenxin Xu Avatar asked Mar 24 '16 15:03

Alex Wenxin Xu


People also ask

How do you multiply a scalar with a tensor?

You can use tf. math. scalar_mul which will take the scalar value as first parameter and the tensor as the second one. It is not recommended to use numpy operations within complicated operations in case you are using Tensorflow on Keras for models training.

How do you multiply a matrix by a scalar in Python?

Numpy multiply array by scalar In order to multiply array by scalar in python, you can use np. multiply() method.


2 Answers

You can multiply a matrix (or any other tensor) by a scalar using the element-wise tf.multiply() operation, which implicitly broadcasts its arguments to match sizes:

x = tf.constant([[1.0, 0.0], [0.0, 1.0]])
y = tf.multiply(x, 2.0)

sess = tf.Session()
print sess.run(y)
# ==> [[2.0, 0.0], [0.0, 2.0]]
like image 195
mrry Avatar answered Sep 30 '22 20:09

mrry


very simple:

scalar * matrix

TensorFlow converts that to tf.multiply and broadcasts everything.

like image 32
Mayou36 Avatar answered Sep 30 '22 20:09

Mayou36