整理寫程序時對keras疑問。
keras代碼流程:
1.讀取dataset
tips:文件夾里有許多文件州泊,可能有隱藏文件什么的丧蘸,要設(shè)置ignore the hidden
dirlist = []
files = os.listdir(Dir+'/Detection')
print('crop pic for detection...')
# ignore the hidden documents
for f in files:
if (os.path.isdir(Dir + '/')):
if (f[0] == '.'):
pass
else:
dirlist.append(f)
作為需要切patch的dataset,讀了以后就順手切圖好了遥皂。 注意四周切到外圍用mirror的細(xì)節(jié)力喷,現(xiàn)在寫的代碼這一塊太low了刽漂,以后要改,提高切圖效率弟孟。切完了以后改code要加保存一下下一步贝咙。
做好了data和label后,記得shuffle拂募。 (自己load的數(shù)據(jù)集庭猩,不是用它給的load函數(shù)的話。keras官方里說shuffle有坑陈症,注意蔼水。)
shuffle和validation_split的順序
模型的fit函數(shù)有兩個參數(shù),shuffle用于將數(shù)據(jù)打亂录肯,validation_split用于在沒有提供驗證集的時候徙缴,按一定比例從訓(xùn)練集中取出一部分作為驗證集
這里有個陷阱是,程序是先執(zhí)行validation_split嘁信,再執(zhí)行shuffle的,所以會出現(xiàn)這種情況:
假如你的訓(xùn)練集是有序的疏叨,比方說正樣本在前負(fù)樣本在后潘靖,又設(shè)置了validation_split,那么你的驗證集中很可能將全部是負(fù)樣本
同樣的蚤蔓,這個東西不會有任何錯誤報出來卦溢,因為Keras不可能知道你的數(shù)據(jù)有沒有經(jīng)過shuffle,保險起見如果你的數(shù)據(jù)是沒shuffle過的秀又,最好手動shuffle一下
np.random.seed(1024)
random.shuffle(index)
data = data[index]
label = label[index]
splitpoint = int(round(num * 0.8))
(X_train, X_val) = (data[0:splitpoint], data[splitpoint:])
(Y_train, Y_val) = (label[0:splitpoint], label[splitpoint:])
X_train=X_train/255
X_val=X_val/255
- 寫個model
我寫在 model.py里了单寂,感覺這樣train程序簡潔一些。
注意用tf 和th 的維度順序不同吐辙。 tensorflow是 num x H x W x Channel - 編譯 需要設(shè)置 loss 等
如果自己寫的label形如[0宣决,0,1昏苏,2尊沸,3,4贤惯,洼专、、孵构、屁商、]
from keras.utils.np_utils import to_categorical
categorical_labels = to_categorical(int_labels, nb_classes=None)
- 將模型存入json
model_json = model.to_json()
with open("model.json", 'w') as json_file:
json_file.write(model_json)
- model.summary 運(yùn)行時查看model
- 用data_augmentation進(jìn)行實時數(shù)據(jù)擴(kuò)充:
搜索時找到了應(yīng)用sklearn網(wǎng)格調(diào)參的文章 http://geek.csdn.net/news/detail/95494
設(shè)置callback可用來做一些動作: 存儲最佳weight,調(diào)整學(xué)習(xí)率颈墅,tensorboard可視化蜡镶。
best_weights_filepath = './best_we
earlyStopping=kcallbacks.EarlyStopping(monitor='val_loss',
patience=20, verbose=1, mode='auto')
saveBestModel = kcallbacks.ModelCheckpoint(best_weights_filepath,
monitor='val_loss', verbose=1, save_best_only=True, mode='auto')
reduce_lr = kcallbacks.ReduceLROnPlateau(monitor='val_loss',
factor=1/math.e,verbose=1, patience=10, min_lr=0.0001)
tensorboard = kcallbacks.TensorBoard(log_dir='/home/amanda/anaconda2/
envs/tensorflow/lib/python2.7/site-packages/keras/examples/log/softmax/epoch')
callback放到這用:
# Fit the model on the batches generated by datagen.flow().
model.fit_generator(datagen.flow(X_train, Ytrain_cate,
batch_size=batch_size),
steps_per_epoch=X_train.shape[0] // batch_size,
epochs=epochs,
validation_data=(X_val, Yval_cate),
verbose=2,
callbacks=[earlyStopping,saveBestModel,reduce_lr,tensorboard])