在tensorflow中交叉连接两个矩阵

时间:2017-11-10 12:43:18

标签: python numpy tensorflow

给定两个矩阵,例如

[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]

2 个答案:

答案 0 :(得分:1)

基于NumPy的方法

from Cryptodome.PublicKey import DSA from Cryptodome.Signature import DSS from Cryptodome.Hash import SHA256 # Create a new DSA key key = DSA.generate(2048) print(key.exportKey()) # Sign a message message = b"Hello" hash_obj = SHA256.new(message) signer = DSS.new(key, 'fips-186-3') signature = signer.sign(hash_obj) # Load the public key pub_key = DSA.import_key(key.publickey().exportKey()) verifyer = DSS.new(pub_key, 'fips-186-3') hash_obj = SHA256.new(message) # Verify the authenticity of the message if verifyer.verify(hash_obj, signature): print("OK") else: print("Incorrect signature") broadcasted-assignment -

一起使用
array-initialization

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

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)

示例运行

案例#1(问题样本):

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

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

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]])

答案 1 :(得分:1)

>>> a = [[1,2],[3,4]]
>>> b = [[5,6],[7,8]]
>>> np.r_[np.kron([1,1],a),np.kron(b, [1,1])]
array([[1, 2, 1, 2],
       [3, 4, 3, 4],
       [5, 5, 6, 6],
       [7, 7, 8, 8]])