【问题标题】:TensorFlow outer product of two 2-rank tensors两个 2 秩张量的 TensorFlow 外积
【发布时间】:2018-10-19 06:52:43
【问题描述】:

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

我想用 2-2 单位矩阵(外积)扩展每个元素并得到 ​​p>

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

在 tensorflow 中实现它的最有效方法是什么?

这个操作在框架中出现了很多。

【问题讨论】:

    标签: python tensorflow machine-learning


    【解决方案1】:

    我想分两步进行。 如果我有一个 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)) )
    

    【讨论】:

      猜你喜欢
      • 2018-11-21
      • 2019-11-20
      • 2017-02-13
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      相关资源
      最近更新 更多