两个2级张量的TensorFlow外部乘积

时间:2018-10-19 06:52:43

标签: python tensorflow machine-learning

假设我有一个二阶张量[[a,b],[c,d]](通常是一个m×n矩阵)。

我想通过2-2单位矩阵(外部乘积)扩展每个元素,并得出

[[a, 0, b, 0],[0,a,0,b],[c,0,d,0],[0,c,0,d]]. 

在张量流中实现它的最有效方法是什么?

此操作在框架中显得很多。

1 个答案:

答案 0 :(得分:0)

我想分两步进行。 如果我有一个m×n矩阵和一个2-2单位矩阵。 首先,我将矩阵放大(重复)为“ 2m-2n矩阵”
然后乘以扩大的单位矩阵(2m-2n矩阵)。如下所示。

import tensorflow as tf
#Process 1  repeat the tensor in 2D.
#e.g. [1,2,3,4]  --> [[1,1,2,2],[1,1,2,2],[3,3,4,4],[3,3,4,4]]

# assuming  m x n idenity matrix e.g. [1,2,3],[4,5,6]] , m=2,n=3
id_matrix_size=2  # size of identity matrix (e.g. 2x2 3x3 ...)
m=2
n=3
mytensor=tf.constant([[1,2,3],[4,5,6] ],dtype = tf.float32)

# similar to np.repeat in x-dimension.
flatten_mytensor=tf.reshape(mytensor,[-1,1])  
a=tf.tile(flatten_mytensor,  [1, id_matrix_size])
b=tf.reshape( a, [m,-1])

# tile in y-dimension
c=tf.tile(b,[1,id_matrix_size])
d=tf.reshape(c,[id_matrix_size*m,id_matrix_size*n])

#Process 2  tile identity matrix in 2D. 
identity_matrix=tf.eye(id_matrix_size) # identity matrix 
identity_matrix_2D= tf.tile(identity_matrix,[m,n])

#Process 3  elementwise multiply
output = tf.multiply(d,identity_matrix_2D )

with tf.Session() as sess:
    print(sess.run(output) )
#output :
#[[1. 0. 2. 0. 3. 0.]
# [0. 1. 0. 2. 0. 3.]
# [4. 0. 5. 0. 6. 0.]
# [0. 4. 0. 5. 0. 6.]]

而且,如果需要大量工具,使用def更方便。

def Expand_tensor(mytensor,id_matrix_size):
    m=mytensor.shape[0]    
    n=mytensor.shape[1]
    # similar to np.repeat in x-dimension.
    flatten_mytensor=tf.reshape(mytensor,[-1,1])  
    a=tf.tile(flatten_mytensor,  [1, id_matrix_size])
    b=tf.reshape( a, [m,-1])

    # tile in y-dimension
    c=tf.tile(b,[1,id_matrix_size])
    d=tf.reshape(c,[id_matrix_size*m,id_matrix_size*n])


    # tile identity matrix in 2D. 
    identity_matrix=tf.eye(id_matrix_size) # identity matrix 
    identity_matrix_2D= tf.tile(identity_matrix,[m,n])

    #elementwise multiply
    output = tf.multiply(d,identity_matrix_2D )
    return output

mytensor=tf.constant([[1,2,3],[4,5,6] ],dtype = tf.float32)
with tf.Session() as sess:
    print(sess.run(Expand_tensor(mytensor,2)) )