踩坑:
一直都不知其問題出在哪,如報錯:
ValueError: Error when checking target: expected sequential_1 to have shape (2,) but got array with shape (1,)
源代碼中:
進行fine-tune,原本是
#top_model.add(Dense(1, activation='sigmoid')) # 二分類,我修改成多分類:softmax
top_model = Sequential()
top_model.add(Flatten(input_shape=model.output_shape[1:]))
top_model.add(Dense(256, activation='relu'))
top_model.add(Dropout(0.5))
top_model.add(Dense(2, activation='softmax'))
top_model.summary()
然後報錯如上,於是最後在數據增強中的代碼下手:
發現
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='binary')
應將class_mode = 'binary' 修改成‘categorical’
如下:
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical')
在百思不得其解之後去查了一下ImageDataGenerator生成器的flow,flow_from_directory用法,對裏面的參數好好研究了一下,來解決自己的錯誤
flow:
flow(self, X, y, batch_size=32, shuffle=True, seed=None, save_to_dir=None, save_prefix='', save_format='png'):
接收numpy數組和標籤爲參數,生成經過數據提升或標準化後的batch數據,並在一個無限循環中不斷的返回batch數據
- x:樣本數據,秩應爲4.在黑白圖像的情況下channel軸的值爲1,在彩色圖像情況下值爲3
- y:標籤
- batch_size:整數,默認32
- shuffle:布爾值,是否隨機打亂數據,默認爲True
- save_to_dir:None或字符串,該參數能讓你將提升後的圖片保存起來,用以可視化
- save_prefix:字符串,保存提升後圖片時使用的前綴, 僅當設置了save_to_dir時生效
- save_format:"png"或"jpeg"之一,指定保存圖片的數據格式,默認"jpeg"
- yields:形如(x,y)的tuple,x是代表圖像數據的numpy數組.y是代表標籤的numpy數組.該迭代器無限循環.
- seed: 整數,隨機數種子
flow_from_directory :
flow_from_directory(directory):
以文件夾路徑爲參數,生成經過數據提升/歸一化後的數據,在一個無限循環中無限產生batch數據
directory: 目標文件夾路徑,對於每一個類,該文件夾都要包含一個子文件夾.子文件夾中任何JPG、PNG、BNP、PPM的圖片都會被生成器使用.詳情請查看此腳本
target_size: 整數tuple,默認爲(256, 256). 圖像將被resize成該尺寸
color_mode: 顏色模式,爲"grayscale","rgb"之一,默認爲"rgb".代表這些圖片是否會被轉換爲單通道或三通道的圖片.
classes: 可選參數,爲子文件夾的列表,如['dogs','cats']默認爲None. 若未提供,則該類別列表將從directory下的子文件夾名稱/結構自動推斷。每一個子文件夾都會被認爲是一個新的類。(類別的順序將按照字母表順序映射到標籤值)。通過屬性class_indices可獲得文件夾名與類的序號的對應字典。
class_mode: "categorical", "binary", "sparse"或None之一. 默認爲"categorical. 該參數決定了返回的標籤數組的形式, "categorical"會返回2D的one-hot編碼標籤,"binary"返回1D的二值標籤."sparse"返回1D的整數標籤,如果爲None則不返回任何標籤, 生成器將僅僅生成batch數據, 這種情況在使用model.predict_generator()和model.evaluate_generator()等函數時會用到.
batch_size: batch數據的大小,默認32
shuffle: 是否打亂數據,默認爲True
seed: 可選參數,打亂數據和進行變換時的隨機數種子
save_to_dir: None或字符串,該參數能讓你將提升後的圖片保存起來,用以可視化
save_prefix:字符串,保存提升後圖片時使用的前綴, 僅當設置了save_to_dir時生效
save_format:"png"或"jpeg"之一,指定保存圖片的數據格式,默認"jpeg"
flollow_links: 是否訪問子文件夾中的軟鏈接