參考資料
- keras中文文檔(官方)
- keras中文文檔(非官方)
- 莫煩keras教程代碼
- 莫煩keras視頻教程
- 一些keras的例子
- Keras開(kāi)發(fā)者的github
- keras在
imagenet
以及VGG19
上的應(yīng)用 - 一個(gè)不負(fù)責(zé)任的Keras介紹(上)
- 一個(gè)不負(fù)責(zé)任的Keras介紹(中)
- 一個(gè)不負(fù)責(zé)任的Keras介紹(下)
- 使用keras構(gòu)建流行的深度學(xué)習(xí)模型
- Keras FAQ: Frequently Asked Keras Questions
- GPU并行訓(xùn)練
- 常見(jiàn)CNN結(jié)構(gòu)的keras實(shí)現(xiàn)
Keras框架介紹
在用了一段時(shí)間的Keras后感覺(jué)真的很爽,所以特意祭出此文與我們公眾號(hào)的粉絲分享再愈。
Keras是一個(gè)非常方便的深度學(xué)習(xí)框架禁添,它以TensorFlow或Theano為后端僚碎。用它可以快速地搭建深度網(wǎng)絡(luò)笔横,靈活地選取訓(xùn)練參數(shù)來(lái)進(jìn)行網(wǎng)路訓(xùn)練《允。總之就是:靈活+快速惑淳!
安裝Keras
首先你需要有一個(gè)Python開(kāi)發(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)) # 通過(guò)add()方法一層層添加模型
# Dense是全連接層,第一層需要定義輸入睡互,
# 第二層無(wú)需指定輸入根竿,一般第二層把第一層的輸出作為輸入
# 定義完模型就需要訓(xùn)練了,不過(guò)訓(xùn)練之前我們需要指定一些訓(xùn)練參數(shù)
# 通過(guò)compile()方法選擇損失函數(shù)和優(yōu)化器
# 這里我們用均方誤差作為損失函數(shù)就珠,隨機(jī)梯度下降作為優(yōu)化方法
model.compile(loss='mse', optimizer='sgd')
# 開(kāi)始訓(xùn)練
print('Training -----------')
for step in range(301):
cost = model.train_on_batch(X_train, Y_train) # Keras有很多開(kāi)始訓(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é)果如下圖:
第二個(gè)例子:手寫(xiě)數(shù)字識(shí)別
MNIST數(shù)據(jù)集可以說(shuō)是在業(yè)內(nèi)被搞過(guò)次數(shù)最多的數(shù)據(jù)集了蹂季,畢竟各個(gè)框架的“hello world”都用它冕广。這里我們也簡(jiǎn)單說(shuō)一下在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)練過(guò)程中輸出正確率
# 這次我們用fit()來(lái)訓(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)載入
- 通過(guò)以下代碼加載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并行
參考:
-
查看GPU使用情況語(yǔ)句(Linux)
# 1秒鐘刷新一次 watch -n 1 nvidia-smi
-
指定顯卡
import os os.environ["CUDA_VISIBLE_DEVICES"] = "2"
這里指定了使用編號(hào)為2的GPU丰刊,大家可以根據(jù)需要和實(shí)際情況來(lái)指定使用的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ò)結(jié)構(gòu)圖
# 你還可以用plot_model()來(lái)講網(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()
寫(xiě)在最后
本文介紹了一個(gè)靈活快速的深度學(xué)習(xí)框架,并且通過(guò)三個(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.reibang.com/u/d055ee434e59