python - tensorflow: multiply certain rows of a matrix with certain columns in another -
suppose have matrix a
, matrix b
. know tf.matmul(a,b)
can calculate multiplication of 2 matrices. have task requires multiplying rows of a
columns of b
.
for example, have list of row ids of a
, ls_a=[0,1,2]
, , list of column ids of b
, ls_b=[4,2,6]
. want result list, denoted ls
, such that:
ls[0] = a[0,:] * b[:,4] ls[1] = a[1,:] * b[:,2] ls[2] = a[2,:] * b[:,6]
how can achieve this?
thank helping me!
you can tf.gather
follows:
import tensorflow tf a=tf.constant([[1,2,3],[4,5,6],[7,8,9]]) b=tf.constant([[1,0,1],[1,0,2],[3,3,-1]]) #taking rows 0,1 a, , columns 0,2 b ind_a=tf.constant([0,1]) ind_b=tf.constant([0,2]) r_a=tf.gather(a,ind_a) #tf.gather access rows, use tf.transpose access columns r_b=tf.transpose(tf.gather(tf.transpose(b),ind_b)) # diagonal elements of multiplication res=tf.diag_part(tf.matmul(r_a,r_b)) sess=tf.interactivesession() print(r_a.eval()) print(r_b.eval()) print(res.eval())
this prints
#r_a [[1 2 3] [4 5 6]] #r_b [[ 1 1] [ 1 2] [ 3 -1]] #result [12 8]
Comments
Post a Comment