[英]cython / numpy type of an array
我正在嘗試構造python類型int(64位帶符號整數)的矩陣。
cdef matrix33():
return np.zeros((3,3),dtype=int)
cdef do_stuf(np.ndarray[int, ndim=2] matrix):
...
return some_value
def start():
print do_stuf(matrix33())
它編譯正確,但是當我運行它時,我不斷收到此錯誤:
ValueError: Buffer dtype mismatch, expected 'int' but got 'long'
我無法使用python long的,但我不知道如何正確轉換為64 int。
更新
好。 我確信我正確使用了Cython。 我編寫的代碼是用於Capture Go / Atari Go游戲中的minmax搜索。
到目前為止,最常用的功能是:
cdef isThere_greedy_move(np.ndarray[np.int64_t, ndim=2]board, int player):
cdef int i, j
for i in xrange(len(board)):
for j in xrange(len(board)):
if board[i,j] == 0:
board[i,j] = player
if player in score(board):
board[i,j] = 0
return True
board[i,j] = 0
return False
# main function of the scoring system.
# returns list of players that eat a stone
cdef score(np.ndarray[np.int64_t, ndim=2] board):
scores = []
cdef int i,j
cdef np.ndarray[np.int64_t, ndim = 2] checked
checked = np.zeros((board.shape[0], board.shape[1]), dtype = int)
for i in xrange(len(board)):
for j in xrange(len(board)):
if checked[i,j] == 0 and board[i,j] !=0:
life, newly_checked = check_life(i,j,board,[])
if not life:
if -board[i,j] not in scores:
scores.append(-board[i,j])
if len(scores) == 2:
return scores
checked = update_checked(checked, newly_checked)
return scores
# helper functions of score/1
cdef check_life(int i, int j, np.ndarray[np.int64_t, ndim=2] board, checked):
checked.append((i,j))
if liberty(i,j,board):
return True, checked
for pos in [[1,0],[0,1],[-1,0],[0,-1]]:
pos = np.array([i,j]) + np.array(pos)
if check_index(pos[0],pos[1],len(board)) and board[pos[0],pos[1]] == board[i,j] and (pos[0],pos[1]) not in checked:
life, newly_checked = check_life(pos[0],pos[1],board,checked)
if life:
checked = checked + newly_checked
return life, checked
return False, [] # [] is a dummy.
cdef liberty(int i,int j, np.ndarray[np.int64_t, ndim=2] board):
for pos in [np.array([1,0]),np.array([0,1]),np.array([-1,0]),np.array([0,-1])]:
pos = np.array([i,j]) - pos
if check_index(pos[0],pos[1],len(board)) and board[pos[0],pos[1]] == 0:
return True
return False
我真的以為這將是一個為賽昂大放異彩的機會。 要解決3x3捕獲,請執行以下操作:
Python 2.7的一致性為2.28秒,而cython的一致性為2.03秒兩者均在python time模塊和低於60°C的i7處理器上進行了測試
現在對我來說,問題是我是否要為此項目切換到Haskell或C ++ ...
Cython的int
類型與C int
相同,即通常(但不一定)為32位。 你應該申報dtype
在matrix33
作為np.int64
和do_stuf
為相應的C, np.int64_t
:
cimport numpy as np
import numpy as np
cdef do_stuff(np.ndarray[np.int64_t, ndim=2] matrix):
pass
cdef matrix33():
return np.zeros((3,3), dtype=int)
def start():
print do_stuff(matrix33())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.