參考資料
- keras中文文檔(官方)
- keras中文文檔(非官方)
- 莫煩keras教程代碼
- 莫煩keras視頻教程
- 一些keras的例子
- Keras開發者的github
- keras在
imagenet
以及VGG19
上的應用 - 一個不負責任的Keras介紹(上)
- 一個不負責任的Keras介紹(中)
- 一個不負責任的Keras介紹(下)
- 使用keras構建流行的深度學習模型
- Keras FAQ: Frequently Asked Keras Questions
- GPU并行訓練
- 常見CNN結構的keras實現
Keras框架介紹
在用了一段時間的Keras后感覺真的很爽,所以特意祭出此文與我們公眾號的粉絲分享。
Keras是一個非常方便的深度學習框架,它以TensorFlow或Theano為后端。用它可以快速地搭建深度網絡,靈活地選取訓練參數來進行網路訓練。總之就是:靈活+快速!
安裝Keras
首先你需要有一個Python開發環境,直接點就用Anaconda,然后在CMD命令行中安裝:
# GPU 版本
>>> pip install --upgrade tensorflow-gpu
# CPU 版本
>>> pip install --upgrade tensorflow
# Keras 安裝
>>> pip install keras -U --pre
第一個例子:回歸模型
首先我們在Keras中定義一個單層全連接網絡,進行線性回歸模型的訓練:
# 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
# 創建數據集
X = np.linspace(-1, 1, 200)
np.random.shuffle(X) # 將數據集隨機化
Y = 0.5 * X + 2 + np.random.normal(0, 0.05, (200, )) # 假設我們真實模型為:Y=0.5X+2
# 繪制數據集plt.scatter(X, Y)
plt.show()
X_train, Y_train = X[:160], Y[:160] # 把前160個數據放到訓練集
X_test, Y_test = X[160:], Y[160:] # 把后40個點放到測試集
# 定義一個model,
model = Sequential () # Keras有兩種類型的模型,序貫模型(Sequential)和函數式模型
# 比較常用的是Sequential,它是單輸入單輸出的
model.add(Dense(output_dim=1, input_dim=1)) # 通過add()方法一層層添加模型
# Dense是全連接層,第一層需要定義輸入,
# 第二層無需指定輸入,一般第二層把第一層的輸出作為輸入
# 定義完模型就需要訓練了,不過訓練之前我們需要指定一些訓練參數
# 通過compile()方法選擇損失函數和優化器
# 這里我們用均方誤差作為損失函數,隨機梯度下降作為優化方法
model.compile(loss='mse', optimizer='sgd')
# 開始訓練
print('Training -----------')
for step in range(301):
cost = model.train_on_batch(X_train, Y_train) # Keras有很多開始訓練的函數,這里用train_on_batch()
if step % 100 == 0:
print('train cost: ', cost)
# 測試訓練好的模型
print('\nTesting ------------')
cost = model.evaluate(X_test, Y_test, batch_size=40)
print('test cost:', cost)
W, b = model.layers[0].get_weights() # 查看訓練出的網絡參數
# 由于我們網絡只有一層,且每次訓練的輸入只有一個,輸出只有一個
# 因此第一層訓練出Y=WX+B這個模型,其中W,b為訓練出的參數
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()
訓練結果:
最終的測試cost為:0.00313670327887,可視化結果如下圖:
第二個例子:手寫數字識別
MNIST數據集可以說是在業內被搞過次數最多的數據集了,畢竟各個框架的“hello world”都用它。這里我們也簡單說一下在Keras下如何訓練這個數據集:
# _*_ 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
# 下載數據集
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 數據預處處理
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(),用以下方式也可以構建網絡
model = Sequential([
Dense(400, input_dim=784),
Activation('relu'),
Dense(10),
Activation('softmax'),
])
# 定義優化器
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',會在訓練過程中輸出正確率
# 這次我們用fit()來訓練網路
print('Training ------------')
model.fit(X_train, y_train, epochs=4, batch_size=32)
print('\nTesting ------------')
# 評價訓練出的網絡
loss, accuracy = model.evaluate(X_test, y_test)
print('test loss: ', loss)
print('test accuracy: ', accuracy)
簡單訓練后得到:test loss: 0.0970609934615,test accuracy: 0.9743
第三個例子:加經典網絡的預訓練模型(以VGG16為例)
預訓練模型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.當服務器不能聯網時,需要把模型*.h5
文件下載到用戶目錄下的~/.keras/model
,模型的預訓練權重在載入模型時自動載入
- 通過以下代碼加載VGG16:
# 使用VGG16模型
from keras.applications.vgg16 import VGG16
print('Start build VGG16 -------')
# 獲取vgg16的卷積部分,如果要獲取整個vgg16網絡需要設置:include_top=True
model_vgg16_conv = VGG16(weights='imagenet', include_top=False)
model_vgg16_conv.summary()
# 創建自己的輸入格式
# 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有個層就是Input層
# 將vgg16模型原始輸入轉換成自己的輸入
output_vgg16_conv = model_vgg16_conv(input)
# output_vgg16_conv是包含了vgg16的卷積層,下面我需要做二分類任務,所以需要添加自己的全連接層
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)
# 最終創建出自己的vgg16模型
my_model = Model(input=input, output=x)
# 下面的模型輸出中,vgg16的層和參數不會顯示出,但是這些參數在訓練的時候會更改
print('\nThis is my vgg16 model for the task')
my_model.summary()
其他Keras使用細節
指定占用的GPU以及多GPU并行
參考:
-
查看GPU使用情況語句(Linux)
# 1秒鐘刷新一次 watch -n 1 nvidia-smi
-
指定顯卡
import os os.environ["CUDA_VISIBLE_DEVICES"] = "2"
這里指定了使用編號為2的GPU,大家可以根據需要和實際情況來指定使用的GPU
from model import unet
G = 3 # 同時使用3個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')
查看網絡結構的命令
- 查看搭建的網絡
print (model.summary())
- 保存網絡結構圖
# 你還可以用plot_model()來講網絡保存為圖片 plot_model(my_model, to_file='my_vgg16_model.png')
訓練集與測試集圖像的處理:
from keras.preprocessing.image import ImageDataGenerator
print('Lodaing data -----------')
train_datagen=ImageDataGenerator()
test_datagen=ImageDataGenerator()
寫在最后
本文介紹了一個靈活快速的深度學習框架,并且通過三個例子講解了如何利用Keras搭建深度網絡進行訓練、如何使用預訓練模型,還介紹了在使用Keras訓練網絡中的一些tricks。
最后,祝各位煉丹師玩的愉快~
PS:
歡迎follow我的GitHub:https://github.com/keloli
還有我的博客:http://www.lxweimin.com/u/d055ee434e59