SlideShare a Scribd company logo
Keras
詳細介紹
張保榮 教授
國立高雄大學資訊工程學系
目錄
官網----------------------------------------------------------------------------------------P.3
Introduction of Keras----------------------------------------------------------------P.4
環境建置----------------------------------------------------------------------------------P.6
Keras實做手寫辨識-------------------------------------------------------------------P.8
Keras https://keras.io/
關於Keras
Keras是由純python編寫的基於theano/tensorflow的深度學習框架。
Keras是一個高層神經網絡API,支持快速實驗,能夠把你的idea迅速轉換為
結果,如果有如下需求,可以優先選擇Keras:
a)簡易和快速的原型設計(keras具有高度模塊化,極簡,和可擴充特性)
b)支持CNN和RNN,或二者的結合
c)無縫CPU和GPU切換
Keras的主要概念
Keras內建了非常多常用的深度學習的類神經網路元件,包括卷積層、遞歸
層(Recurrent layer)等等,讓開發者可以用最少的程式碼就可以建構出龐大
又複雜的深度學習網路架構,比起Theano及TensorFlow可以用更簡潔、更
具可讀性的方式來撰寫程式。
Keras的訓練流程也十分簡潔,設定好深度學習的網路架構後,只要呼叫
compile函式進行編譯,再接著呼叫fit函式並傳入mini batch的數量等參數,
就可以開始訓練了。
Keras環境建置
安裝完Anaconda之後
它自帶所有這些Python, NumPy, SciPy
打開Anaconda的小黑窗
輸入”pip insatll --upgeade keras ”即可
成功後 輸入“pip list”看有沒有
2017 9-14 Keras example
使用Keras做手寫辨識
與CNN和RNN一樣,我們從下載並讀取 mnist 資料
Keras實作練習
建置一個手寫辨識
首先匯入 Keras 及相關模組:
Code[ part 1]:
import numpy as np
import pandas as pd
import sys, os
from keras.utils import np_utils
from keras.datasets import mnist
np.random.seed(10)
Keras實作練習
建置一個手寫辨識
讀取與查看 mnist 資料
可知道 training data 共有 60,000 筆; testing data 共有 10,000 筆
Code[ part 2]:
(X_train_image, y_train_label), (X_test_image, y_test_label) = mnist.load_data()
print("t[Info] train data={:7,}".format(len(X_train_image)))
print("t[Info] test data={:7,}".format(len(X_test_image)))
print("t[Info] Shape of train data=%s" % (str(X_train_image.shape)))
print("t[Info] Shape of train label=%s" % (str(y_train_label.shape)))
Keras實作練習
建置一個手寫辨識
定應 plot_image 函數顯示數字影像
Code[ part 3]:
def isDisplayAvl():
return 'DISPLAY' in os.environ.keys()
import matplotlib.pyplot as plt
def plot_image(image):
fig = plt.gcf()
fig.set_size_inches(2,2)
plt.imshow(image, cmap='binary')
plt.show()
建立 plot_images_labels_predict() 函數
後續我們希望能很方便查看數字圖形, 所以我們建立了以下函數:
Code[ part 4]:
def plot_images_labels_predict(images, labels, prediction, idx, num=10):
fig = plt.gcf()
fig.set_size_inches(12, 14)
if num > 25: num = 25
for i in range(0, num):
ax=plt.subplot(5,5, 1+i)
ax.imshow(images[idx], cmap='binary')
title = "l=" + str(labels[idx])
if len(prediction) > 0:
title = "l={},p={}".format(str(labels[idx]), str(prediction[idx]))
else:
title = "l={}".format(str(labels[idx]))
ax.set_title(title, fontsize=10)
ax.set_xticks([]); ax.set_yticks([])
idx+=1
plt.show()
Keras實作練習
建置一個手寫辨識
顯示訓練結果
Code[ part 5]:
def show_train_history(train_history, train, validation):
plt.plot(train_history.history[train])
plt.plot(train_history.history[validation])
plt.title('Train History')
plt.ylabel(train)
plt.xlabel('Epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
Keras實作練習
建置一個手寫辨識
首先將 image 以 reshape轉換為二維 ndarray並進行 normalization
Code[ part 6]:
x_Train = X_train_image.reshape(60000, 28*28).astype('float32')
x_Test = X_test_image.reshape(10000, 28*28).astype('float32')
print("t[Info] xTrain: %s" % (str(x_Train.shape)))
print("t[Info] xTest: %s" % (str(x_Test.shape)))
x_Train_norm = x_Train/255
x_Test_norm = x_Test/255
Keras實作練習
建置一個手寫辨識
建立模型
Code[ part 7]:
from keras.models import Sequential
from keras.layers import Dense
model = Sequential() # Build Linear Model
model.add(Dense(units=256, input_dim=784, kernel_initializer='normal', activation='relu')) #
Add Input/hidden layer
model.add(Dense(units=10, kernel_initializer='normal', activation='softmax')) # Add
Hidden/output layer
print("t[Info] Model summary:")
model.summary()
print("")
Keras實作練習
建置一個手寫辨識
定義訓練方式(compile)、開始訓練 、顯示出對與錯
Code[ part 8]:
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
train_history = model.fit(x=x_Train_norm, y=y_TrainOneHot, validation_split=0.2,
epochs=10, batch_size=200, verbose=2)
if isDisplayAvl():
print("t[Info] Display accuracy pic")
show_train_history(train_history, 'acc', 'val_acc')
print("t[Info] Display loss pic")
show_train_history(train_history, 'loss', 'val_loss')
Keras實作練習
建置一個手寫辨識
評估模型準確率
Code[ part 9]:
scores = model.evaluate(x_Test_norm, y_TestOneHot)
print()
print("t[Info] Accuracy of testing data = {:2.1f}%".format(scores[1]*100.0))
Keras實作練習
建置一個手寫辨識
評估模型準確率 、進行預測
Code[ part 10]:
print("t[Info] Making prediction to x_Test_norm")
prediction = model.predict_classes(x_Test_norm) # Making prediction and save result to prediction
print()
print("t[Info] Show 10 prediction result (From 240):")
print("%sn" % (prediction[240:250]))
if isDisplayAvl():
plot_images_labels_predict(X_test_image, y_test_label, prediction, idx=240)
print("t[Info] Error analysis:")
for i in range(len(prediction)):
if prediction[i] != y_test_label[i]:
print("tAt %d'th: %d is with wrong prediction as %d!" % (i, y_test_label[i], prediction[i]))
print()
Keras實作練習
建置一個手寫辨識
使用 pandas crosstab 建立混淆矩陣 (Confusion matrix)
Code[ part 11]:
print("t[Info] Display Confusion Matrix:")
print("%sn" % pd.crosstab(y_test_label, prediction, rownames=['label'],
colnames=['predict']))
開始編譯!開始訓練!
2017 9-14 Keras example
準確率持續提高
參考資料:
http://ial.eecs.ucf.edu/Reading/Papers/TensorFlow_Tutorial.pdf
——UNIVERSITY OF CENTRAL FLORIDA
https://morvanzhou.github.io
——莫煩Python
http://www.cc.ntu.edu.tw/chinese/epaper/0041/20170620_4105.html
——NTU計算機及網路運算中心
https://brohrer.mcknote.com/zh-
Hant/how_machine_learning_works/how_convolutional_neural_networks_work.html
——卷積神經網路的運作原理
http://darren1231.pixnet.net/blog/post/332753859-
tensorflow%E6%95%99%E5%AD%B8----
%E5%BB%BA%E7%BD%AE%E4%B8%80%E5%80%8Bcnn%E7%B6%B2%E8%
B7%AF%E5%88%86%E8%BE%A8%E6%89%8B%E5%AF%AB%E8%BE%A8%E
8%AD%98
——建置一個CNN網路分辨手寫辨識字
https://zh.wikipedia.org/wiki/%E9%95%B7%E7%9F%AD%E6%9C%9F%E8%A8%9
8%E6%86%B6
——維基百科
https://www.youtube.com/watch?v=xCGidAeyS4M
——ML Lecture 25: Recurrent Neural Network
http://www.cnblogs.com/sandy-t/p/6930608.html
——用tensorflow搭建RNN(LSTM)進行MNIST手寫數字辨識
https://puremonkey2010.blogspot.tw/2017/06/toolkit-keras-mnist.html
https://kknews.cc/zh-tw/news/yy84r8j.html

More Related Content

PPTX
Mysql 高级优化之 逻辑处理
PDF
用 Keras 玩 Machine Learning
PPTX
2017 9-12 Deep Learning / Tensorflow
PDF
Tensorflow and keras
PDF
如何讓Keras能在R語言中運作_安裝教學
PDF
人工智慧01_安裝機器學習開發環境
PDF
人工智慧09_神經網路(TensorFlow+Keras)
PPTX
[Python - Deep Learning] Data generator
Mysql 高级优化之 逻辑处理
用 Keras 玩 Machine Learning
2017 9-12 Deep Learning / Tensorflow
Tensorflow and keras
如何讓Keras能在R語言中運作_安裝教學
人工智慧01_安裝機器學習開發環境
人工智慧09_神經網路(TensorFlow+Keras)
[Python - Deep Learning] Data generator
Ad

2017 9-14 Keras example