2014-09-05 39 views
1

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

看起來'g_h'是'None'。如果你的'for'循環沒有被輸入,那麼'g_h'不會被設置成任何東西。 – robbrit 2014-09-05 14:40:49

+0

爲什麼不輸出'z'或'權重'?如果其中任何一個都是空的,那麼你的'for'循環將永遠不會被輸入。 – robbrit 2014-09-05 14:46:52

+0

我剛剛編輯代碼,以便在沒有任何值時分配g值。另外 - 我曾嘗試輸出權重和Z,但事情是 - 這些不是運行時錯誤。我認爲這些是來自numba包的編譯錯誤,甚至在代碼開始運行之前。我認爲這個問題是將一個變量分配給一個不是None的變量。反正在Numba附近呢? – user961627 2014-09-05 14:49:18

回答

2

問題是Numba推斷g_hNoneType;它初始化爲載體,將正確編譯:

g_h = np.zeroes((H, no_features, no_classes)) 
2

的問題是,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瞭解更多信息。

+0

謝謝!如果您有任何Numba經驗,你有這個後續問題的任何想法:http://www.stackoverflow.com/questions/25685916/cannot-coerce-to-or-from-object-in-nopython-上下文錯誤後,蟒蛇 – user961627 2014-09-05 15:06:44

相關問題