天天看點

keras, 建構GRU傳值 Units時,報錯,TypeError: object of type ‘numpy.int32‘ has no len()

keras,建構GRU模型時,在需要進行随機搜尋對units進行傳值時,回出現TypeError: object of type 'numpy.int32' has no len()錯誤。

舉例說明:

p = {'neurons': np.random.choice([10,20])}

model = Sequential()

model.add(GRU(units=params['gru1_neurons'], input_shape=(12, 12), return_sequences=False,dropout = 0., recurrent_dropout = 0.)

這個時候運作代碼時,會報錯TypeError: object of type 'numpy.int32' has no len()

檢視API得知:units: Positive integer, dimensionality of the output space

而type(p['gru1_neurons']) 為:numpy.int32.

int 和 numpy.int32 具體有什麼不同,請查閱[1]

那麼答案就有了,隻需要将numpy.int32 轉換為int類型就可以了。

[2]中給出了具體做法。那麼最終修改為:

model.add(GRU(units=params['gru1_neurons'].item(), input_shape=(12, 12), return_sequences=False,dropout = 0., recurrent_dropout = 0.)

[1]https://stackoverrun.com/cn/q/10516538

[2]https://stackoverflow.com/questions/9452775/converting-numpy-dtypes-to-native-python-types

繼續閱讀