类型错误:数组必须具有一致类型的分配
从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
以加速我的代码之前,实际上没有任何问题。
问题是Numba推断g_h
为NoneType
;它初始化为载体,将正确编译:
g_h = np.zeroes((H, no_features, no_classes))
的问题是,numba无法知道g_h
不会None
当它最终分配到g
因为g_h
类型取决于运行时的流量控制。换句话说,如果g_h
可能永远不是一个float64,那么它必须假定有时不是。
这是一个documented limitation of numba和类型推断系统的一般的限制:
However, there are some restrictions, namely that variables must have a unifyable type at control flow merge points. For example, the following code will not compile:
@jit def incompatible_types(arg): if arg > 10: x = "hello" else: x = 1 return x # ERROR! Inconsistent type for x!
的解决方案是初始化g_h
到兼容类型,而不是= None
。
Numba的类型推断其实是相当聪明,所以你可以不用在很多情况下问题,只要类型可以返回之前被统一混合在一个特定的局部变量的类型。阅读Numba documentation on types了解更多信息。
谢谢!如果您有任何Numba经验,你有这个后续问题的任何想法:http://www.stackoverflow.com/questions/25685916/cannot-coerce-to-or-from-object-in-nopython-上下文错误后,蟒蛇 – user961627 2014-09-05 15:06:44
看起来'g_h'是'None'。如果你的'for'循环没有被输入,那么'g_h'不会被设置成任何东西。 – robbrit 2014-09-05 14:40:49
为什么不输出'z'或'权重'?如果其中任何一个都是空的,那么你的'for'循环将永远不会被输入。 – robbrit 2014-09-05 14:46:52
我刚刚编辑代码,以便在没有任何值时分配g值。另外 - 我曾尝试输出权重和Z,但事情是 - 这些不是运行时错误。我认为这些是来自numba包的编译错误,甚至在代码开始运行之前。我认为这个问题是将一个变量分配给一个不是None的变量。反正在Numba附近呢? – user961627 2014-09-05 14:49:18