学習初期の試行錯誤でバカになる話(NumPy の「空チェック」と hstack/vstack のはなし)

ずーっと気持ち悪いなぁと思いながらも「一つ憶える」ことの弊害についての考察。

なんて、な。

ワタシのこれまでの投稿であげたスニペット中にも出てきてるんだけど、これがね:

 1 import numpy as np
 2 
 3 # ...
 4 
 5 a = None
 6 cond = True
 7 while cond:
 8     d = some_func_which_returns_ndarray()
 9     if a is None:
10         a = d
11     else:
12         a = np.hstack((a, d))
13     cond = some_func_returns_some_cond()

なんか馬鹿っぽく見えるでしょ? 実際馬鹿だし、本人ももちろん自覚しておった。

なんでこんなモッサリしたコードになったかというのが、タイトルにもした通りの、「学習初期の試行錯誤」で、そのときからあんまし進化しないまんまきとったのね。具体的にはこれだわ:

1 >>> import numpy as np
2 >>> b = np.arange(5)
3 >>> if b: pass
4 ...
5 Traceback (most recent call last):
6   File "<stdin>", line 1, in <module>
7 ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
8 >>> 

これともう1つ。空の ndarray を作ることを最初の試行錯誤で思いつかなかった。この2つの合わせ業で、こんな間の抜けたコードを書いておった。後者で既に十分に馬鹿確定したわけだが、前者のせいで None で初期化し、is None でチェックした、という物語である。

実際にはこれでいいのだ:

 1 import numpy as np
 2 
 3 # ...
 4 
 5 a = np.array([])  # あるいは np.ndarray(0)
 6 cond = True
 7 while cond:
 8     d = some_func_which_returns_ndarray()
 9     a = np.hstack((a, d))
10     cond = some_func_returns_some_cond()

たまにこうやって「知ってるはず」のことを見返さにゃダメね。