5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Cythonでbool型のNumPyに型指定する方法

Last updated at Posted at 2019-08-27

CythonでNumPyに型指定する方法のおさらい

import numpy as np
cimport numpy as np # npがかぶっているが公式によれば大丈夫。こちらは型指定用。
# from numpy cimport ndarray as ndar # np.ndarrayが長ければこう書いてもOK
cdef np.ndarray[np.int_t, ndim=2] array

などとする。NumPyに関しては型指定でかなり高速化されるようなのでやったほうがいいだろう。

bool型の配列では...?

NumPyを使っていれば、dtype=boolで使うことも少なくないだろう。
これを型指定しようとすると、結構つまずく。公式ドキュメントで明記されてない気がするので...

思いつくような方法で

cdef np.ndarray[bint, ndim=2] bool_array # bintはcythonでのbool型
cdef np.ndarray[np.bool, ndim=2] bool_array2

としても、コンパイルは成功するが、実行時に

ValueError: Item size of buffer (1 byte) does not match size of 'bint' (4 bytes)

ValueError: Does not understand character buffer dtype format string ('?')

などとエラーが出てしまう。

正しくは、

cdef np.ndarray[np.uint8_t, cast=True, ndim=2] bool_array
# または
cdef np.ndarray[np.npy_bool, cast=True, ndim=2] bool_array

とする。おそらくcast=Trueで適切に型変換してくれるのだろう。

(比べてみたが、どちらでもパフォーマンスはほとんど変わらないようだ。)

参考リンク

http://omake.accense.com/static/doc-ja/cython/src/tutorial/numpy.html
https://stackoverflow.com/questions/18058744/passing-a-numpy-pointer-dtype-np-bool-to-c
https://github.com/cython/cython/pull/2676

5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?