在fine tune Keras Applications中給出的分類CNN Model的時候驱显,如果在Model的top層之上加入Flatten層就會出現錯誤》沤樱可能的報錯信息類似下面的內容:
$ python3 ./train.py
Using TensorFlow backend.
Found 60000 images belonging to 200 classes.
Found 20000 images belonging to 200 classes.
# 略過一些信息...
Creating TensorFlow device (/device:GPU:0) ->
(device: 0, name: GeForce GTX 1080, pci bus id: 0000:02:00.0, compute capability: 6.1)
# ↓↓↓ 錯誤出現 ↓↓↓
Traceback (most recent call last):
File "./train.py", line 51, in <module>
x = Flatten()(x)
File "/usr/local/lib/python3.5/dist-packages/keras/engine/topology.py", line 636, in __call__
output_shape = self.compute_output_shape(input_shape)
File "/usr/local/lib/python3.5/dist-packages/keras/layers/core.py", line 490, in
compute_output_shape
'(got ' + str(input_shape[1:]) + '. '
ValueError: The shape of the input to "Flatten" is not fully defined (got (None, None, 1536).
Make sure to pass a complete "input_shape" or "batch_input_shape" argument
to the first layer in your model.
# ↑↑↑ 錯誤結束 ↑↑↑
出錯的代碼行是x = Flatten()(x)
刺啦,錯誤提示為ValueError: The shape of the input to "Flatten" is not fully defined (got (None, None, 1536). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.
Flatten()(x)
希望參數擁有確定的shape
屬性,實際得到的參數x
的shape
屬性是(None, None, 1536)
透乾,很明顯不符合要求洪燥。同時磕秤,錯誤提示信息中也給出了修正錯誤的方法Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model
。即捧韵,在Model的第一層給出確定的input_shape
或batch_input_shape
市咆。那么,如何在Keras中解決該問題呢再来?
以Keras Applications中的VGG16為例蒙兰,我們只需要在其初始化的時候,給出具體的input_shape
就可以了芒篷。例如搜变,Keras給出的VGG16模型輸入層圖像尺寸是(224, 224)的,所以如果使用TensorFlow的channels_last
數據格式针炉,則初始化代碼為:
vgg16 = keras.applications.vgg16.VGG16(include_top=False, weights='imagenet', input_shape=(224, 224, 3))
x = vgg16.output
x = Flatten()(x)
...
注意挠他,因為要fine tune模型,對模型分類的種類和類別數進行重新定義篡帕,所以include_top=False
殖侵,這樣返回的模型不包括VGG16的全連接層和輸出層。
參考: