生活随笔
收集整理的這篇文章主要介紹了
深度学习(十)keras学习笔记
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
keras學(xué)習(xí)筆記
原文地址:http://blog.csdn.net/hjimce/article/details/49095199
作者:hjimce
keras與torch7的使用非常相似,是最近才火起來的深度學(xué)習(xí)開源庫,底層是用了theano。keras可以說是python版的torch7,對于快速構(gòu)建CNN模型非常方便。同時(shí)也包含了一些最新文獻(xiàn)的算法,比如Batch Noramlize,文檔教程也很全,在官網(wǎng)上作者都是直接給例子淺顯易懂,個(gè)人感覺非常容易上手。keras也支持保存訓(xùn)練好的參數(shù),然后加載已經(jīng)訓(xùn)練好的參數(shù),進(jìn)行繼續(xù)訓(xùn)練。
一、安裝教程。
因?yàn)閗eras是在theano的基礎(chǔ)上進(jìn)行封裝的,所以我們需要先安裝好theano后,再繼續(xù)安裝keras。theano的安裝可以參考我的另外一篇博文,因?yàn)槲以诹硗庖黄┪闹?#xff0c;是在windows環(huán)境下搭建theano的,所以這里所講的keras的安裝也是在windows下。
其實(shí)如果在ubuntu中,theano沒有安裝也沒關(guān)系,只要使用命令:pip install keras。如果順利的話,系統(tǒng)會(huì)幫你把keras所有所需的庫都給安裝了,包括theano。
windows安裝步驟:
1、參考我的另外一篇博文,安裝theano,并測試沒有問題。
2、使用Anaconda,然后在命令anaconda的命令窗口中輸入:pip install keras
這個(gè)時(shí)候有可能出現(xiàn)h5py安裝失敗:
那么請到網(wǎng)站:http://www.lfd.uci.edu/~gohlke/pythonlibs/? 下載h5py。
打開上面的網(wǎng)站,找到h5py:
根據(jù)根據(jù)自己的電腦選擇相應(yīng)的版本,我的電腦是64為系統(tǒng),python為2.7,所以選擇了:h5py-2.5.0-cp27-none-win_amd64.whl。
然后把下載到的h5py文件,放到Anaconda所在的安裝目錄下:
最后我們在anaconda的命令窗口中輸入命令:pip install??h5py-2.5.0-cp27-none-win_amd64.whl 。等h5py安裝完后。在重新安裝keras輸入命令:pip install keras。
上面如果還是安裝失敗,那么試試升級(jí)pip版本,輸入:python-m pip install --upgrade pip,把pip的版本升級(jí)一下。
二、keras 使用教程
下面貼個(gè)簡單的例子、更多的例子可以自己到官網(wǎng)的文檔教程上看,官網(wǎng)給了很詳細(xì)的教程,不像caffe的文檔那么少。看一下下面例子,松松構(gòu)建CNN模型。keras為我們提供了兩種網(wǎng)絡(luò)模型.
1、一種是CNN比較常用到的sequential網(wǎng)絡(luò)結(jié)構(gòu),調(diào)用方法如下:
[python]?view plaincopy
?? ?? import?numpy?as?np?? ?? ?? ?? from?keras.optimizers?import?SGD?? ?? import?os?? import??matplotlib.pyplot?as?plt?? ?? import?h5py?? from?keras.models?import?Sequential?? from?keras.layers.convolutional?import?Convolution2D,?MaxPooling2D,?ZeroPadding2D?? from?keras.layers.core?import?Dense,Dropout,Activation,Flatten?? from?keras.layers.normalization?import??BatchNormalization?? from?keras.optimizers?import?SGD,?Adadelta,?Adagrad,RMSprop?? from?keras.layers.advanced_activations?import?PReLU?? ?? from??keras.callbacks?import?ModelCheckpoint,Callback?? ?? ?? class?LossHistory(Callback):?? ????def?on_train_begin(self,?logs={}):?? ????????self.losses?=?[]?? ?? ????def?on_batch_end(self,?batch,?logs={}):?? ????????self.losses.append(logs.get('loss'))?? ?? def?Net_Mouth():?? ????keras_model=Sequential()?? ?????? ????keras_model.add(Convolution2D(20,?5,?5,input_shape=(3,?60,?60)))?? ?????? ????keras_model.add(Activation('relu'))?? ?????? ????keras_model.add(MaxPooling2D(pool_size=(2,?2)))?? ?? ?????? ????keras_model.add(Convolution2D(40,?5,?5))?? ????keras_model.add(Activation('relu'))?? ?? ????keras_model.add(MaxPooling2D(pool_size=(2,?2)))?? ?? ?? ????keras_model.add(Convolution2D(60,?3,?3))?? ????keras_model.add(Activation('relu'))?? ?? ????keras_model.add(MaxPooling2D(pool_size=(2,?2)))?? ?? ?? ????keras_model.add(Convolution2D(80,?3,?3))?? ????keras_model.add(Activation('relu'))?? ?? ?????? ????keras_model.add(Flatten())?? ?????? ????keras_model.add(Dense(1000))?? ????keras_model.add(Activation('relu'))?? ?? ????keras_model.add(Dense(500))?? ????keras_model.add(Activation('relu'))?? ?? ?? ????keras_model.add(Dense(38))?? ????keras_model.add(Activation('tanh'))?? ?? ?????? ????keras_model.compile(loss='mean_squared_error',?optimizer='adam')?? ????return?keras_model?? ?? keras_model=Net_Mouth()?? ?? checkpointer?=ModelCheckpoint(filepath="mouth.hdf5",?verbose=1,?save_best_only=True)?? history?=?LossHistory()?? ?? ?? keras_model.fit(x,?y,?batch_size=128,?nb_epoch=100,shuffle=True,verbose=2,show_accuracy=True,validation_split=0.1,callbacks=[checkpointer,history])??
2、圖模型,根據(jù)節(jié)點(diǎn)進(jìn)行命名連接的一種網(wǎng)絡(luò)結(jié)構(gòu)
[python]?view plaincopy
?? import??numpy?as?np?? from??keras.models?import?Graph?? import?numpy?as?np?? ?? np.random.seed(100)?? import?os?? import??matplotlib.pyplot?as?plt?? ?? import?h5py?? from?keras.models?import?Graph?? from?keras.layers.convolutional?import?Convolution2D,?MaxPooling2D?? from?keras.layers.core?import?Dense,Activation,Flatten,?Dropout?? import??keras.optimizers?? ?? from??keras.callbacks?import?ModelCheckpoint,Callback?? ?? class?LossHistory(Callback):?? ????def?on_train_begin(self,?logs={}):?? ????????self.losses?=?[]?? ?? ????def?on_batch_end(self,?batch,?logs={}):?? ????????self.losses.append(logs.get('loss'))?? ?? ?? ?? def?Second_Net_Graph():?? ????keras_model=Graph()?? ?????? ????keras_model.add_input(name='input',input_shape=(3,60,60))?? ?????? ????keras_model.add_node(layer=Convolution2D(20,?5,?5),name='conv1',input='input')?? ?????? ????keras_model.add_node(layer=Activation('relu'),name='relul',input='conv1')?? ????keras_model.add_node(layer=MaxPooling2D(pool_size=(2,?2)),name='pool1',input='relul')?? ?? ?? ????keras_model.add_node(layer=Convolution2D(40,?5,?5),name='conv2',input='pool1')?? ????keras_model.add_node(layer=Activation('relu'),name='relu2',input='conv2')?? ????keras_model.add_node(layer=MaxPooling2D(pool_size=(2,?2)),name='pool2',input='relu2')?? ?? ?? ????keras_model.add_node(layer=Convolution2D(60,?3,?3),name='conv3',input='pool2')?? ????keras_model.add_node(layer=Activation('relu'),name='relu3',input='conv3')?? ????keras_model.add_node(layer=MaxPooling2D(pool_size=(2,?2)),name='pool3',input='relu3')?? ?? ?????? ?? ?????? ????keras_model.add_node(layer=Convolution2D(80,?3,?3,activation='relu'),name='brow_input',input='pool3')?? ?????? ????keras_model.add_node(layer=Convolution2D(80,?3,?3,activation='relu'),name='eye_input',input='pool3')?? ?????? ????keras_model.add_node(layer=Convolution2D(80,?3,?3,activation='relu'),name='nose_input',input='pool3')?? ?????? ????keras_model.add_node(layer=Convolution2D(80,?3,?3,activation='relu'),name='mouth_input',input='pool3')?? ?? ?????? ????keras_model.add_node(layer=Flatten(),name='brow_flatten',input='brow_input')?? ????keras_model.add_node(layer=Flatten(),name='eye_flatten',input='eye_input')?? ????keras_model.add_node(layer=Flatten(),name='nose_flatten',input='nose_input')?? ????keras_model.add_node(layer=Flatten(),name='mouth_flatten',input='mouth_input')?? ?? ?? ?????? ????keras_model.add_node(layer=Dense(500,activation='relu'),name='brow_dense1',input='brow_flatten')?? ????keras_model.add_node(layer=Dense(500,activation='relu'),name='eye_dense1',input='eye_flatten')?? ????keras_model.add_node(layer=Dense(500,activation='relu'),name='nose_dense1',input='nose_flatten')?? ????keras_model.add_node(layer=Dense(500,activation='relu'),name='mouth_dense1',input='mouth_flatten')?? ?? ?? ?? ?????? ????keras_model.add_node(layer=Dense(20,activation='tanh'),name='brow_dense2',input='brow_dense1')?? ????keras_model.add_node(layer=Dense(24,activation='tanh'),name='eye_dense2',input='eye_dense1')?? ????keras_model.add_node(layer=Dense(18,activation='tanh'),name='nose_dense2',input='nose_dense1')?? ????keras_model.add_node(layer=Dense(38,activation='tanh'),name='mouth_dense2',input='mouth_dense1')?? ?? ?????? ????keras_model.add_output(name='output',inputs=['brow_dense2','nose_dense2','eye_dense2',?? ??????????????????????????????????????????????????????'mouth_dense2'])?? ?? ?????? ????keras_model.compile(optimizer='adam',loss={'output':'mse'})?? ????return??keras_model?? ?? def?train(data_file='../../h5py/train.h5'):?? ????print?'readdata'?? ????f=h5py.File(data_file,'r')?? ????x=f['data'][:]?? ????x=np.asarray(x,dtype='float32')?? ????y=f['label'][:]?? ????y=np.asarray(y,dtype='float32')?? ????print?x.shape?? ????print?y.shape?? ????print?'train'?? ????keras_model=Second_Net_Graph()?? ?? ????checkpointer?=ModelCheckpoint(filepath="graph51point.hdf5",?verbose=1,?save_best_only=True)?? ????history?=?LossHistory()?? ????history?=?keras_model.fit({'input':x,?'output':y},?shuffle=True,verbose=2,validation_split=0.1,callbacks=[checkpointer,history])?? train()??
個(gè)人心得:感覺keras使用很方便,同時(shí)底層的源碼很很容易讀懂,我們要修改算法,可以去讀一讀底層的源碼,學(xué)習(xí)起來不會(huì)像caffe的底層那么麻煩,個(gè)人感覺caffe的唯一好處就是有很多公開的model、源碼,用起來相當(dāng)麻煩,keras就不一樣了,用python,搞深度學(xué)習(xí),輕松許多,可惜cvpr上的一些文獻(xiàn)的源碼都是用caffe寫的。期待keras像torch一樣,支持caffe模型導(dǎo)入功能。
**********************作者:hjimce ? 時(shí)間:2015.10.1 ?聯(lián)系QQ:1393852684 ? 地址:http://blog.csdn.net/hjimce? ?原創(chuàng)文章,版權(quán)所有,轉(zhuǎn)載請保留本行信息(不允許刪除)
總結(jié)
以上是生活随笔為你收集整理的深度学习(十)keras学习笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。