How to do matrix-scalar multiplication in TensorFlow?

Viewed 21509

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!

5 Answers

very simple:

scalar * matrix

TensorFlow converts that to tf.multiply and broadcasts everything.

Equivalent variants:

x = tf.constant([[1.0, 0.0], [0.0, 1.0]]
y1 = tf.scalar_mul(-1.0, x)
y2 = tf.multiply(-1.0, x)
y3 = -1.0 * x

Output:

sess.run(y1)
array([[-1., -0.],
       [-0., -1.]], dtype=float32)

sess.run(y2)
array([[-1., -0.],
       [-0., -1.]], dtype=float32)

sess.run(y3)
array([[-1., -0.],
       [-0., -1.]], dtype=float32)
scalar_mul(scalar, x)

Multiplies a scalar times a Tensor or IndexedSlices object.

Intended for use in gradient code which might deal with IndexedSlices objects, which are easy to multiply by a scalar but more expensive to multiply with arbitrary tensors.

Args: scalar: A 0-D scalar Tensor. Must have known shape. x: A Tensor or IndexedSlices to be scaled.

Returns: scalar * x of the same type (Tensor or IndexedSlices) as x.

According to the official documentation. You can use tf.math.scalar_mul which will take the scalar value as first parameter and the tensor as the second one.

That means your code will be

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

sess = tf.Session()
print sess.run(y)

It is not recommended to use numpy operations within complicated operations in case you are using Tensorflow on Keras for models training. It is imperative to use only tensor operators.

For more details and documentation about tensor operators. It is a best practice to check : Tensorflow math module official documentation it has sufficient functions that look like numpy operators.

Related