When given a set A of matrices of different sizes,
A=
[[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]],
[[1, 2],
[1, 2],
[1, 2],
[1, 2]],
[[1, 2, 3, 4],
[1, 2, 3, 4]]]
I'd like to pad with 0 and combine the whole thing into a single matrix as shown below.
B=
[[1, 2, 3, 0],
[1, 2, 3, 0],
[1, 2, 3, 0],
[1, 2, 0, 0],
[1, 2, 0, 0],
[1, 2, 0, 0],
[1, 2, 0, 0],
[1, 2, 3, 4],
[1, 2, 3, 4]]
To achieve the above input and output on the Chainer, use the
What kind of code should I write?
A and B are numpy array types.
Convert it to a list.
import numpy as np
A = np.array([
[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]],
[[1, 2],
[1, 2],
[1, 2],
[1, 2]],
[[1, 2, 3, 4],
[1, 2, 3, 4]]])
## Flatten
X = sum (A.tolist(), [ ])
## Max size
l=max(map(len,X))
## padding
B = np.array (map(lambdax:x+[0]*(l-len(x))), X))
B
=>
array([1,2,3,0],
[1, 2, 3, 0],
[1, 2, 3, 0],
[1, 2, 0, 0],
[1, 2, 0, 0],
[1, 2, 0, 0],
[1, 2, 0, 0],
[1, 2, 3, 4],
[1, 2, 3, 4]])
© 2024 OneMinuteCode. All rights reserved.