LoginSignup
1
2

More than 3 years have passed since last update.

小ネタ:numpyのflattenのメカニズム

Posted at

numpyのndarrayをflattenすることがよくあるのですが、データがどのような順番で並ぶのかをきちんと理解してみます。

(3, 3, 3)のndarrayを作成。どの位置にどの値が割り当てられているかわかるように、値に連番で付与する。

import numpy as np

x = np.array([[[ 0,  1,  2], [ 3,  4,  5], [ 6,  7,  8]], 
              [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], 
              [[18, 19, 20], [21, 22, 23], [24, 25, 26]],])
print(x.shape)
out
(3, 3, 3)

これをnp.flatten()すると、どのように一次元に配置されるかを見てみます。

x.flatten()

もっともネストが深いところを順番に取って、1次元に並べていることがわかりました!割と直感的ですね。

out
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26])

短いですが以上です!

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2