简体   繁体   English

如何从列沿垂直方向从2D矩阵切片并在Tensorflow中创建3D?

[英]How to slice matrices from a 2D matrix along column (vertically) and create a 3D in tensorflow?

I have a tensor , which is an intermediate result produced during a set of operation . 我有一个张量,这是一组操作期间产生的中间结果。 It is a 2D matrix ( tensor ) , I want to reshape it into 3d but in a specific way . 它是一个2D矩阵(张量),我想将其重塑为3d,但要采用特定的方式。 How could I do that . 我该怎么做。

This is an example. 这是一个例子。 The shape of K = [ 10 , 12 ]. K的形状= [10,12]。 I want to convert it into ( 3 x 10 x 4 ) matrix , Here my batch_size = 3 , sequence_length = 4 . 我想将其转换为(3 x 10 x 4)矩阵,这里我的batch_size = 3,sequence_length = 4。 In nutshell, the essence is splitting a 2D matrix along the column ( vertically ) at positions after ( 3 (before 4) , 7 ( before 8), because my sequence_length = 4 ), so that we finally have 3 matrix of size 10 X 4 each , which when packed together becomes 3D matrix ( 3 x 10 x 4). 简而言之,本质是在(3(在4之前),7(在8之前)之后的位置沿列(垂直)拆分2D矩阵,因为我的sequence_length = 4),所以我们最终有了3个大小为10 X的矩阵每个4,当打包在一起成为3D矩阵(3 x 10 x 4)。 Any suggestions will be appreciated. 任何建议将不胜感激。

K = array([[1, 9, 5, 9, 9, 2, 0, 9, 1, 9, 0, 6],
   [0, 4, 8, 4, 3, 3, 8, 8, 7, 0, 3, 8],
   [7, 7, 1, 8, 4, 7, 0, 4, 9, 0, 6, 4],
   [2, 4, 6, 3, 3, 7, 8, 5, 0, 8, 5, 4],
   [7, 4, 1, 3, 3, 9, 2, 5, 2, 3, 5, 7],
   [2, 7, 1, 6, 5, 0, 0, 3, 1, 9, 9, 6],
   [6, 7, 8, 8, 7, 0, 8, 6, 8, 9, 8, 3],
   [6, 1, 7, 4, 9, 2, 0, 8, 2, 7, 8, 4],
   [4, 1, 7, 6, 9, 4, 1, 5, 9, 7, 1, 3],
   [5, 7, 3, 6, 6, 7, 9, 1, 9, 6, 0, 3]])

#### I am expecting it to reshaped as follows

 K_new = [ 1, 9, 5, 9, 
         0, 4, 8, 4, 
         7, 7, 1, 8, 
         2, 4, 6, 3, 
         7, 4, 1, 3, 
         2, 7, 1, 6, 
         6, 7, 8, 8, 
         6, 1, 7, 4, 
         4, 1, 7, 6, 
         5, 7, 3, 6, 

         9, 2, 0, 9, 
         3, 3, 8, 8, 
         4, 7, 0, 4, 
         3, 7, 8, 5, 
         3, 9, 2, 5,
         5, 0, 0, 3,
         7, 0, 8, 6, 
         9, 2, 0, 8,
         9, 4, 1, 5, 
         6, 7, 9, 1, 

         1, 9, 0, 6
         7, 0, 3, 8
         9, 0, 6, 4
         0, 8, 5, 4 
         2, 3, 5, 7
         1, 9, 9, 6
         8, 9, 8, 3
         2, 7, 8, 4
         9, 7, 1, 3
         9, 6, 0, 3 ]

We can use tf.split for this . 我们可以为此使用tf.split。 This can be achieved by 这可以通过

tf.stack(tf.split(k, batch_size , axis=1)) #### Note here batch_size=3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM