从here跟进,我得到的代码如下:
@jit(float_[:,:,:](float_[:,:], int_[:], int_))
def train_function(X, y, H):
# do lots of stuff, including setting the arrays g and g_per_round like this:
g = np.zeros((no_features, no_classes))
g_per_round = np.zeros((H, no_features, no_classes))
# do more stuff, then:
g_h = None
j = 0
print "Calculating regression coefficients per class. .."
# building the parameters per j class
for y1_w in zip(z.T, weights.T):
y1, w = y1_w
temp_g = sm.WLS(y1, X, w).fit() # Step 2(a)(ii)
if g_h is None: # sometimes g *is* None, and that's fine
g_h = temp_g.params # this is an array of floats
else:
g_h = np.c_[g_h, temp_g.params]
j = j + 1
if np.allclose(g,0) or g is None:
g = g_h
else:
g = g + g_h
# do lots more stuff, then finally:
return g_per_round
class GentleBoostC(object):
# init functions and stuff
def train(self, X, y, H):
self.g_per_round = train_function(X, y, H)
现在我收到以下错误:
@jit(float_[:,:,:](float_[:,:], int_[:], int_))
more lines, etc etc etc, last few lines:
unresolved_types, var_name)
File "C:\Users\app\Anaconda\lib\site-packages\numba\typesystem\ssatypes.py", line 767, in promote_arrays
assert_equal(non_array_types[0])
File "C:\Users\app\Anaconda\lib\site-packages\numba\typesystem\ssatypes.py", line 764, in assert_equal
var_name, result_type, other_type))
TypeError: Arrays must have consistent types in assignment for variable 'g': 'float64[:, :]' and 'none'
在尝试添加@jit
以加快我的代码之前,我确实没有遇到任何问题。
答案 0 :(得分:2)
问题在于Numba推断g_h
为NoneType
;将它初始化为一个向量,它将正确编译它:
g_h = np.zeroes((H, no_features, no_classes))
答案 1 :(得分:2)
问题是当最终将g_h
分配给None
时,numba无法知道g
不会g_h
,因为g_h
的类型取决于运行时流控制。换句话说,如果@jit def incompatible_types(arg):
if arg > 10:
x = "hello"
else:
x = 1
return x # ERROR! Inconsistent type for x!
不能一个float64,那么它必须假定有时不是。
这是一个documented limitation of numba和一般类型推理系统的限制:
但是,有一些限制,即变量必须有 控制流合并点的一个统一类型。例如, 以下代码将无法编译:
g_h
解决方案是将= None
初始化为兼容类型,而不是{{1}}。
Numba的类型推断实际上非常聪明,所以你可以在特定的局部变量上混合类型,在很多情况下只要在返回之前统一类型就可以。请阅读Numba documentation on types了解详情。