Try   HackMD

Python Deep Learning

tags: python

  • 本文內容為“Tibame提升AI實作能力必備,深度學習TensorFlow基礎與應用”為主,版權為陳少君所有,本文僅做筆記用途,非商業用途

  • 本篇圖片部分出自“Tibame提升AI實作能力必備,深度學習TensorFlow基礎與應用”課程內容講義


Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
Introduction

What is Deep Learning

定義:一種利用人工神經網路為架構,對資料進行特徵學習與優化,進而能預測與分類的演算法
人工神經網路:一種仿神經網路結構與功能之模型
常見的深度學習框架:
深度神經網路(DNN)
卷積神經網路(CNN)
深度置信網路(DBN)
迴圈神經網路(RNN)

應用:電腦視覺、語音辨識、自然語音處理、音訊辨識、生物資訊學等領域

Deep Learning Development

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Deep Learning Advantage

Deep Learning可以省去人工取得特徵

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Deep Learning Type

與機器學習相同為:
監督式學習(Supervised)
非監督式學習(Unsupervised)
強化學習(Reinforcement)

Neuron & Neural Network

單一神經元運作:各個輸入訊號ai經過各個權重wi(訊號強度)加一常數後,經過線性或非線性Active Function(f)轉換後即可得出一輸出t,然後即可再做後續傳遞
單層神經網路運作:神經元後面會接隱藏層或是輸出層神經網路,一層神經網路會含有許多神經元

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

深度學習利用隱藏層中之隱藏式神經元來儲存更多不同階層之特徵,才能達到更多的辨識度與分類能力效果

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
Tensorflow

  • Tensorflow為一個開源軟體庫,用於各種感知和語言理解之機器學習
  • 最初由Google大腦團隊開發用於Googler,在Apache 2.0開源許可下發佈
  • 此套件可提供DNN, CNN, SVM等機器學習演算法開發程式
  • 可用Python or C++運行Tensorflow,目前較多開發者使用Python
  • 有CPU、GPU、TPU三種版本,可運行一個或多個CPU與GPU
  • Tensorflow除了提供Python API,還有C++, Haskell, Java, GO, Rust API,第三方包可用於C#, .NET Core, Julia, R, Scala
  • Tensorflow底層核心由C++實現,通過gRPC實現網路互訪、分散式執行
  • Tensorflow在Windows與Linux支援使用Bazel或Cmake去構建,在某些平台也支援使用GNU make進行編譯

應用:
廣泛的應用程式使用Tensorflow 作為基礎,其中它已成功實現自動化圖像字幕軟體,例如DeepDream
2015年10月26日,Google正式啟用了由Tensorflow 提供支援的RankBrain
RankBrain現在處理大量的搜尋查詢,替換和補充傳統的靜態演算法搜尋結果

Compare with other API

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Ref: (mygreatlearning.com)

Basic Calculate

  • Tensorflow使用Python大量的向量、列表與矩陣運算
  • TF2.0開始可以使用EAGER MODE並且整合了Keras API,使程式更容易編寫
  • TF1.0基本運算有Session, Placeholder
  • TF2.0經過簡化後在EAGER MODE就不用做了

Session
先建立session然後再run session
Placeholder
TensorFlow原理為先建構一個graph再去運算,因此當還沒有input data時需要用Placeholder在graph佔位置

import tensorflow as tf a = tf.placeholder(tf.int32) #佔位 b = tf.placeholder(tf.int32) #佔位 y = a + b with tf.Sesson() as sess: c = sess.run(y, {a:3, b:4}) print(c)

Variable
在訓練model時,variable可以放weights(w), bias(b)或是其他參數
必須在Session內設定, 將graph freeze後可將訓練好的參數儲存下來。

Function

TensorFlow Model Building APIs
High Level: tf.keras, ts.estimators
Low Level : tf.*

tf.Estimators

好處為將training, evalution, prediction與report一併打包在一起
Premade Estimators:
模型已預先訂製好,甚至不需要重新訓練,他們是tf.estimator.Estimator的子類
Ex: DNNClassifier, LinearClassifier, LinearRegressor等等

Custom Estimators:
需要自行客製模型,作法有三種:

  1. 從Keras API改
  2. 從Tensorflow Hub中的程式庫中修改
  3. 從tf.keras.layers中修改

tf.Keras

  1. Sequential API:可以用~10 lines of code定義並訓練影像分類的問題,適合變化不多的基本網路
  2. Functional API:結構清楚,程式好讀,而且容易寫出有創意的神經網路,如GAN
  3. Model subclassing:用子類來客製化原來的建模API

模型的建構:tf.keras.Model和tf.keras.layers
模型的損失函數:tf.keras.losses
模型的優化器:tf.keras.optimizer
模型的評估:tf.keras.metrics

建模步驟

  • 準備資料
  • 前處理
  • 建模
  • 驗證評估
  • 利用模型預測

Demo:MNIST dataset 0到9分類

Demo:用Keras + Tensorflow 做貓狗辨識

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
Neural Style Transfer

neural style transfer為圖像遷移,一般多是使用已訓練好的模型套用,而非自己訓練
圖像風格遷移是將兩個影像:內容影像(content image)和一個大師們的風格參考影像(style reference image)融合起來,最後輸出影像(output image)看來像是內容影像,但具有風格像是風格參考影像

這套優化技術媒合了內容影像的統計分佈和風格參考影像的統計分佈,統計分佈是由CNN網路的特徵萃取能力來取得

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Fundamental

原理:內容表示和風格表示在卷積神經網絡中是可分離的
我們可以獨立地操縱這兩種表示,來產生新的有感知意義上的圖片

VGG19:在VGG19這個CNN中將內容和風格從中間層(它有19 層)擷取出來,經過和目標風格的優化(梯度下降與損失函數),最後得到有目標風格的原內容圖形

詳細步驟:VGG19(16 Conv + 3 Pooling)CNN來完成

  1. 定義內容和風格的表達方式:選擇中間層當作內容和風格的特徵擷取層
  2. 建立模型:也就是VGG19,但是我們要擷取中間層的資訊來運算內容和風格
  3. 內容計算:內容可以用中間層的特徵圖(feature maps)來計算
  4. 風格計算:用特徵圖之間的均值(mean)和相關度(correlation)來表達,可使用計算Gram Matrix來達成
  5. 擷取風格與內容
  6. 執行梯度下降
  7. 計算整體損失函數(同時計算內容和風格損失),調整輸出影像矩陣值
  8. 不斷優化,最後輸出影像

CNN可以調整之參數:
• VGG19所有參數
• 擷取內容和風格的中間層
• 執行Epochs次數
• 計算整體梯度和損失的演算法
• 風格計算的定義

Demo:草地上的拉不拉多狗有康定斯基的風格

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
GAN

GAN(Generative Adversarial Network)為生成對抗網路
有兩個神經系統:Generator & Discriminator
Generator與Discriminator互相學習,Generator負責生出數據,Discriminator負責鑑別數據之好壞

演算法

Discriminator
分辨影像真假,是個二元分類器(Binary Classifier) (Yes or No)
訓練時接收真影像,label=1,假影像,label=0
Generator
訓練Generator要鎖住Discriminator(防止Discriminator訓練),也是二元分類器,假=0, 真=1
訓練時只產生假影像,但要欺騙Discriminator,label=1
一開始loss會很高,但經過不斷訓練自己壓低loss
輸入到生成器的內容只是從latent space隨機取樣的雜訊

Pseudocode:

#1 Load in the data x,y= get_mnist() #2 Create Networks d = model(image, prediction) d.comple(loss=‘binary_cross_entropy’…) g=model(noise, image) #3 combine d and g combined_model = model(noise, fake_prediction) combined_model.compile(loss=‘binary_cross_entropy’…) #4 Gradient descend loop for epoch in epochs #train discriminator real_images=sample(x) fake_images=g.predict(noise) d.train_on_batch(real_images, ones) d.train_on_batch(fake_images, zeros) #train generator combined_model.train_on_batch(noise, ones)

Demo:[Demo24_GAN.ipynb]

DCGAN

Deep Convolutional GAN(DCGAN)
判別網絡D (Convolutional) ,輸入的是一張圖片,輸出的是這張圖片是真實圖片的概率
生成網絡G(De-Convolutional),輸入的是一個100 維的噪聲向量,輸出的是一張圖片

GycleGAN

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
強化學習(RL)

強化學習(RL)與監督式學習(SL)的不同

SL只是一個靜態方程式,將loss最小化
RL是一個計畫與策略,將reward最大化

強化學習概要

代理Agent:你的電腦程式,RL學習者
環境Environment:你想教代理(agent)學如何贏的遊戲本身
局Episode:One round of game一局,一盤,一場
獎勵Reward:代理(agent)嘗試最大化的數字,可為正負或零
行動Action:在環境(environment)中代理(agent)所做的事
狀態States:從環境中觀察到的現象,可經由一或多次觀察得到
狀態空間State space and 行動空間action space:所有可能的狀態或行動的集合

價值函數

Maximizing Rewards
代理要將整個未來的獎勵總和最大化
我們不希望只將下一步得到的獎勵最大化,正因為如此,代理要有對未來計畫的能力

總回收(Return) = 所有未來獎勵(reward)的總合,有人稱作"utility",折現因子(Discount Factor)γ, 將未來獎勵折現的係數,一般很接近1,比方0.9, 0.99 etc.

強化學習的演進,經過了幾個階段,在不同的環境下的行動策略(Action Policies)和價值函數(value functions)也有不同的演繹方式。大致說來可分以下三種:

動態編程(Dynamic Programming)或MDP(馬可夫決策過程Markov Decision Process):必須有上帝視角,能看到所有的State和Environment
Monte Carlo演算法:Alpha Go 一戰成名的方法,沒有上帝視角,可以累計經驗,逐漸了解環境和狀態,但必續在下完每一盤棋(episode)之後才能重算價值函數和策略調整
時間差分(Temporal Difference(TD))演算法:適合episode 尚未結束就必須學習的情境,比方像自駕車或股市,永遠沒有結束必須繼續玩下去。價值參數要實時調整

以上的狀態(State)如果太多,Q-table變的無限大時,需要深度學習的協助

馬可夫決策過程

馬可夫決策過程(Markov Decision Process(MDP))可用來描述增強式學習(RL)的系統
馬可夫假設(Markov Assumption):時間點t的狀態(state),只是依賴時間點t-1的狀態決定
馬可夫假設本身預測能力相當薄弱,但我們可以把狀態定義為發生的3, 4 個字,那麼預測能力就相對強

Q-Learning

Q-學習是強化學習的一種方法。Q- 學習就是要記錄下學習過的政策,因而告訴Agent 什麼情況下採取什麼行動會有最大的獎勵值。Q- 學習不需要對環境進行建模,即使是對帶有隨機因素的轉移函數或者獎勵函數也不需要進行特別的改動就可以進行。

對於任何有限的馬可夫決策過程(FMDP),Q- 學習可以找到一個可以最大化所有步驟的獎勵期望的策略。在給定一個部分隨機的策略和無限的探索時間,Q- 學習可以給出一個最佳的動作選擇策略。

「Q」這個字母在強化學習中表示一個動作的品質(quality )。

DQN

Demo:Open AI Gym Suite 的CartPole 控制
Demo:Atari 經典遊戲BREAKOUT 的學習