Skip to main content
 首页 » 编程设计

python之在 tensorflow 中交叉连接两个矩阵

2024年10月01日30lidabo

例如给定两个矩阵

[1 2] and [5 6] 
[3 4]     [7 8], 

有没有办法将它们连接起来得到下面的矩阵?

[1 2 1 2] 
[3 4 3 4] 
[5 5 6 6] 
[7 7 8 8] 

请您参考如下方法:

基于 NumPy 的方法

使用数组初始化 broadcasted-assignment -

def assign_as_blocks(a,b): 
    m1,n1 = a.shape 
    m2,n2 = b.shape 
    out = np.empty((m1+m2,n2,n1),dtype=int) 
    out[:m1] = a[:,None,:] 
    out[m1:] = b[:,:,None] 
    return out.reshape(m1+m2,-1) 

要使用 tensorflow 工具,修改后的版本为:

def assign_as_blocks_v2(a,b): 
      shape1 = tf.shape(a) 
      shape2 = tf.shape(b) 
      m1 = shape1[0] 
      n1 = shape1[1] 
      m2 = shape2[0] 
      n2 = shape2[1] 
      p1 = tf.tile(a,[1,n2]) 
      p2 = tf.reshape(tf.tile(tf.expand_dims(b, 1),[1,1,n1]), [m2,-1]) 
      out = tf.concat((p1,p2),axis=0) 
      return out 

样本运行

案例#1(问题样本):

In [95]: a 
Out[95]:  
array([[1, 2], 
       [3, 4]]) 
 
In [96]: b 
Out[96]:  
array([[5, 6], 
       [7, 8]]) 
 
In [97]: assign_as_blocks(a, b) 
Out[97]:  
array([[1, 2, 1, 2], 
       [3, 4, 3, 4], 
       [5, 5, 6, 6], 
       [7, 7, 8, 8]]) 

案例 #2(通用形状随机数组):

In [106]: np.random.seed(0) 
     ...: a = np.random.randint(0,9,(2,3)) 
     ...: b = np.random.randint(0,9,(4,5)) 
 
In [107]: a 
Out[107]:  
array([[5, 0, 3], 
       [3, 7, 3]]) 
 
In [108]: b 
Out[108]:  
array([[5, 2, 4, 7, 6], 
       [8, 8, 1, 6, 7], 
       [7, 8, 1, 5, 8], 
       [4, 3, 0, 3, 5]]) 
 
In [109]: assign_as_blocks(a, b) 
Out[109]:  
array([[5, 0, 3, 5, 0, 3, 5, 0, 3, 5, 0, 3, 5, 0, 3], 
       [3, 7, 3, 3, 7, 3, 3, 7, 3, 3, 7, 3, 3, 7, 3], 
       [5, 5, 5, 2, 2, 2, 4, 4, 4, 7, 7, 7, 6, 6, 6], 
       [8, 8, 8, 8, 8, 8, 1, 1, 1, 6, 6, 6, 7, 7, 7], 
       [7, 7, 7, 8, 8, 8, 1, 1, 1, 5, 5, 5, 8, 8, 8], 
       [4, 4, 4, 3, 3, 3, 0, 0, 0, 3, 3, 3, 5, 5, 5]])