Vimlan.G
Vimlan.G

Reputation: 193

Multiply matrix with vector(element wise) Tensorflow

I am not sure on a way to put this question into a title. But will show an example on the thing that I need help in using Tensorflow.

For an example:

matrix_1 shape = [4,2]
matrix_2 shape  = [4,1]

matrix_1 * matrix 2
[[1,2],
 [3,4],
 [5,6],
 [7,8]]

 *

[[0.1],
 [0.2],
 [0.3],
 [0.4]]

 = [[0.1,0.2],
    [0.6,0.8],
    [1.5,1.8],
    [2.8,3.2]]

Is there any algorithm to achieve this?

Thank you

This is the error that I am getting from the simplified problem example above:

ValueError: Dimensions must be equal, but are 784 and 100 for 'mul_13' (op: 'Mul') with input shapes: [100,784], [100]

Upvotes: 1

Views: 2048

Answers (1)

mrry
mrry

Reputation: 126154

The standard tf.multiply(matrix_1, matrix_2) operation (or the shorthand syntax matrix_1 * matrix_2) will perform exactly the computation that you want on matrix_1 and matrix_2.

However, it looks like the error message you are seeing is because matrix_2 has shape [100], whereas it must be [100, 1] to get the elementwise broadcasting behavior. Use tf.reshape(matrix_2, [100, 1]) or tf.expand_dims(matrix_2, 1) to convert it to the correct shape.

Upvotes: 2

Related Questions