I want to pad and size sets of matrices of different sizes

Asked 1 years ago, Updated 1 years ago, 58 views

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.

python chainer

2022-09-30 21:28

1 Answers

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


2022-09-30 21:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.