【Keras】Keras入門指南

參考資料

Keras框架介紹

在用了一段時(shí)間的Keras后感覺真的很爽,所以特意祭出此文與我們公眾號(hào)的粉絲分享。
Keras是一個(gè)非常方便的深度學(xué)習(xí)框架,它以TensorFlow或Theano為后端。用它可以快速地搭建深度網(wǎng)絡(luò),靈活地選取訓(xùn)練參數(shù)來進(jìn)行網(wǎng)路訓(xùn)練。總之就是:靈活+快速!

安裝Keras

首先你需要有一個(gè)Python開發(fā)環(huán)境,直接點(diǎn)就用Anaconda,然后在CMD命令行中安裝:

# GPU 版本
>>> pip install --upgrade tensorflow-gpu

# CPU 版本
>>> pip install --upgrade tensorflow

# Keras 安裝
>>> pip install keras -U --pre

第一個(gè)例子:回歸模型

首先我們?cè)贙eras中定義一個(gè)單層全連接網(wǎng)絡(luò),進(jìn)行線性回歸模型的訓(xùn)練:

# Regressor example
# Code: https://github.com/keloli/KerasPractise/edit/master/Regressor.py

import numpy as np
np.random.seed(1337)  
from keras.models import Sequential 
from keras.layers import Dense
import matplotlib.pyplot as plt

# 創(chuàng)建數(shù)據(jù)集
X = np.linspace(-1, 1, 200)
np.random.shuffle(X)    # 將數(shù)據(jù)集隨機(jī)化
Y = 0.5 * X + 2 + np.random.normal(0, 0.05, (200, )) # 假設(shè)我們真實(shí)模型為:Y=0.5X+2
# 繪制數(shù)據(jù)集plt.scatter(X, Y)
plt.show()

X_train, Y_train = X[:160], Y[:160]     # 把前160個(gè)數(shù)據(jù)放到訓(xùn)練集
X_test, Y_test = X[160:], Y[160:]       # 把后40個(gè)點(diǎn)放到測(cè)試集

# 定義一個(gè)model,
model = Sequential () # Keras有兩種類型的模型,序貫?zāi)P停⊿equential)和函數(shù)式模型
                      # 比較常用的是Sequential,它是單輸入單輸出的
model.add(Dense(output_dim=1, input_dim=1)) # 通過add()方法一層層添加模型
                                            # Dense是全連接層,第一層需要定義輸入,
                                            # 第二層無(wú)需指定輸入,一般第二層把第一層的輸出作為輸入

# 定義完模型就需要訓(xùn)練了,不過訓(xùn)練之前我們需要指定一些訓(xùn)練參數(shù)
# 通過compile()方法選擇損失函數(shù)和優(yōu)化器
# 這里我們用均方誤差作為損失函數(shù),隨機(jī)梯度下降作為優(yōu)化方法
model.compile(loss='mse', optimizer='sgd')

# 開始訓(xùn)練
print('Training -----------')
for step in range(301):
    cost = model.train_on_batch(X_train, Y_train) # Keras有很多開始訓(xùn)練的函數(shù),這里用train_on_batch()
    if step % 100 == 0:
        print('train cost: ', cost)

# 測(cè)試訓(xùn)練好的模型
print('\nTesting ------------')
cost = model.evaluate(X_test, Y_test, batch_size=40)
print('test cost:', cost)
W, b = model.layers[0].get_weights()    # 查看訓(xùn)練出的網(wǎng)絡(luò)參數(shù)
                                        # 由于我們網(wǎng)絡(luò)只有一層,且每次訓(xùn)練的輸入只有一個(gè),輸出只有一個(gè)
                                        # 因此第一層訓(xùn)練出Y=WX+B這個(gè)模型,其中W,b為訓(xùn)練出的參數(shù)
print('Weights=', W, '\nbiases=', b)

# plotting the prediction
Y_pred = model.predict(X_test)
plt.scatter(X_test, Y_test)
plt.plot(X_test, Y_pred)
plt.show()

訓(xùn)練結(jié)果:
最終的測(cè)試cost為:0.00313670327887,可視化結(jié)果如下圖:


回歸模型訓(xùn)練結(jié)果

第二個(gè)例子:手寫數(shù)字識(shí)別

MNIST數(shù)據(jù)集可以說是在業(yè)內(nèi)被搞過次數(shù)最多的數(shù)據(jù)集了,畢竟各個(gè)框架的“hello world”都用它。這里我們也簡(jiǎn)單說一下在Keras下如何訓(xùn)練這個(gè)數(shù)據(jù)集:

# _*_ coding: utf-8 _*_
# Classifier mnist

import numpy as np
np.random.seed(1337)  
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import RMSprop

# 下載數(shù)據(jù)集
(X_train, y_train), (X_test, y_test) = mnist.load_data()

# 數(shù)據(jù)預(yù)處處理
X_train = X_train.reshape(X_train.shape[0], -1) / 255. 
X_test = X_test.reshape(X_test.shape[0], -1) / 255.  
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)

# 不使用model.add(),用以下方式也可以構(gòu)建網(wǎng)絡(luò)
model = Sequential([
    Dense(400, input_dim=784),
    Activation('relu'),
    Dense(10),
    Activation('softmax'),
])

# 定義優(yōu)化器
rmsprop = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)
model.compile(optimizer=rmsprop,
              loss='categorical_crossentropy',
              metrics=['accuracy']) # metrics賦值為'accuracy',會(huì)在訓(xùn)練過程中輸出正確率

# 這次我們用fit()來訓(xùn)練網(wǎng)路
print('Training ------------')
model.fit(X_train, y_train, epochs=4, batch_size=32)

print('\nTesting ------------')
# 評(píng)價(jià)訓(xùn)練出的網(wǎng)絡(luò)
loss, accuracy = model.evaluate(X_test, y_test)

print('test loss: ', loss)
print('test accuracy: ', accuracy)
    

簡(jiǎn)單訓(xùn)練后得到:test loss: 0.0970609934615,test accuracy: 0.9743

第三個(gè)例子:加經(jīng)典網(wǎng)絡(luò)的預(yù)訓(xùn)練模型(以VGG16為例)

預(yù)訓(xùn)練模型Application
https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3
https://github.com/keras-team/keras/issues/4465
https://stackoverflow.com/questions/43386463/keras-vgg16-fine-tuning
1.當(dāng)服務(wù)器不能聯(lián)網(wǎng)時(shí),需要把模型*.h5文件下載到用戶目錄下的~/.keras/model,模型的預(yù)訓(xùn)練權(quán)重在載入模型時(shí)自動(dòng)載入

  1. 通過以下代碼加載VGG16:
# 使用VGG16模型
from keras.applications.vgg16 import VGG16
print('Start build VGG16 -------')

# 獲取vgg16的卷積部分,如果要獲取整個(gè)vgg16網(wǎng)絡(luò)需要設(shè)置:include_top=True
model_vgg16_conv = VGG16(weights='imagenet', include_top=False)
model_vgg16_conv.summary()

# 創(chuàng)建自己的輸入格式
# if K.image_data_format() == 'channels_first':
#   input_shape = (3, img_width, img_height)
# else:
#   input_shape = (img_width, img_height, 3)

input = Input(input_shape, name = 'image_input') # 注意,Keras有個(gè)層就是Input層

# 將vgg16模型原始輸入轉(zhuǎn)換成自己的輸入
output_vgg16_conv = model_vgg16_conv(input)

# output_vgg16_conv是包含了vgg16的卷積層,下面我需要做二分類任務(wù),所以需要添加自己的全連接層
x = Flatten(name='flatten')(output_vgg16_conv)
x = Dense(4096, activation='relu', name='fc1')(x)
x = Dense(512, activation='relu', name='fc2')(x)
x = Dense(128, activation='relu', name='fc3')(x)
x = Dense(1, activation='softmax', name='predictions')(x)

# 最終創(chuàng)建出自己的vgg16模型
my_model = Model(input=input, output=x)

# 下面的模型輸出中,vgg16的層和參數(shù)不會(huì)顯示出,但是這些參數(shù)在訓(xùn)練的時(shí)候會(huì)更改
print('\nThis is my vgg16 model for the task')
my_model.summary()

其他Keras使用細(xì)節(jié)

指定占用的GPU以及多GPU并行

參考:

from model import unet
G = 3 # 同時(shí)使用3個(gè)GPU
with tf.device("/cpu:0"):
        M = unet(input_rows, input_cols, 1)
model = keras.utils.training_utils.multi_gpu_model(M, gpus=G)
model.compile(optimizer=Adam(lr=1e-5), loss='binary_crossentropy', metrics = ['accuracy'])

model.fit(X_train, y_train,
              batch_size=batch_size*G, epochs=nb_epoch, verbose=0, shuffle=True,
              validation_data=(X_valid, y_valid))

model.save_weights('/path/to/save/model.h5')

查看網(wǎng)絡(luò)結(jié)構(gòu)的命令

  • 查看搭建的網(wǎng)絡(luò)
    print (model.summary())
    

效果如圖:
查看搭建的網(wǎng)絡(luò)
  • 保存網(wǎng)絡(luò)結(jié)構(gòu)圖
    # 你還可以用plot_model()來講網(wǎng)絡(luò)保存為圖片
    plot_model(my_model, to_file='my_vgg16_model.png')
    

訓(xùn)練集與測(cè)試集圖像的處理:

from keras.preprocessing.image import ImageDataGenerator
print('Lodaing data -----------')
train_datagen=ImageDataGenerator()
test_datagen=ImageDataGenerator()

寫在最后

本文介紹了一個(gè)靈活快速的深度學(xué)習(xí)框架,并且通過三個(gè)例子講解了如何利用Keras搭建深度網(wǎng)絡(luò)進(jìn)行訓(xùn)練、如何使用預(yù)訓(xùn)練模型,還介紹了在使用Keras訓(xùn)練網(wǎng)絡(luò)中的一些tricks。
最后,祝各位煉丹師玩的愉快~

PS:
歡迎follow我的GitHub:https://github.com/keloli
還有我的博客:http://www.lxweimin.com/u/d055ee434e59

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。