機器學習十講第九講

深度學習

深度學習應用領域

  • 圖像識別:IMAGENET
  • 機器翻譯:Google神經機器翻譯系統
  • 玩遊戲: DeepMind團隊開發的自我學習玩遊戲的系統
  • 語音識別

深度學習發展原因

1624633911945

神經元與感知機

1624633975234

多層感知機(MLP)

1624634007532

  • 誤差函數

1624634076153

  • MLP面臨的困境

1624634158462

後向傳播BP

1624634241287

機器學習 vs 深度學習

  • 機器學習需要人工選取特徵;深度學習會自動學習有用的特徵
  • 可以將深度學習視爲非線性函數逼近器:深度學習通過一種深層網絡結構,實現複雜函數逼近。
  • 萬能逼近原理:當隱層節點數目足夠多時,具有一個隱層的神經網絡,可以以任意精度逼近任意具有有限間斷點的函數。
  • 網絡層數越多,需要的隱含節點數目指數減小。

CNN卷積神經網絡

1624634494505

  • 卷積操作

1624634529483

  • CNN 完整結構

1624634562000

AlexNet

1624634627644

VGG

1624634674666

GoogleNet

1624634723520

ResNet

1624634799506

RNN 和 GAN

  • RNN 適合處理訓練型數據:自然語言處理等領域
  • GAN

1624634857772

基於卷積神經網絡的人臉識別

#使用sklearn的datasets模塊在線獲取Olivetti Faces數據集。
from sklearn.datasets import fetch_olivetti_faces
faces = fetch_olivetti_faces()
#打印
faces

#數據結構與類型
print("The shape of data:",faces.data.shape, "The data type of data:",type(faces.data))
print("The shape of images:",faces.images.shape, "The data type of images:",type(faces.images))
print("The shape of target:",faces.target.shape, "The data type of target:",type(faces.target))

#使用matshow輸出部分人臉圖片
import numpy as np
rndperm = np.random.permutation(len(faces.images)) #將數據的索引隨機打亂
import matplotlib.pyplot as plt
%matplotlib inline
plt.gray()
fig = plt.figure(figsize=(9,4) )
for i in range(0,18):
    ax = fig.add_subplot(3,6,i+1 )
    plt.title(str(faces.target[rndperm[i]])) #類標
    ax.matshow(faces.images[rndperm[i],:]) #圖片內容
    plt.box(False) #去掉邊框
    plt.axis("off")#不顯示座標軸
plt.tight_layout()

1624635040705

#查看同一個人的不同人臉特點
labels = [2,11,6] #選取三個人
%matplotlib inline
plt.gray()
fig = plt.figure(figsize=(12,4) )
for i in range(0,3):
    faces_labeli = faces.images[faces.target == labels[i]]
    for j in range(0,10):    
        ax = fig.add_subplot(3,10,10*i + j+1 )
        ax.matshow(faces_labeli[j])
        plt.box(False) #去掉邊框
        plt.axis("off")#不顯示座標軸
plt.tight_layout()

1624635083998

#將數據集劃分爲訓練集和測試集兩部分,注意要按照圖像標籤進行分層採樣
# 定義特徵和標籤
X,y = faces.images,faces.target
# 以5:5比例隨機地劃分訓練集和測試集
from sklearn.model_selection import train_test_split
train_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.5,stratify = y,random_state=0)
# 記錄測試集中出現的類別,後期模型評價畫混淆矩陣時需要
#index = set(test_y)

# 轉換數據維度,模型訓練時要用
train_x = train_x.reshape(train_x.shape[0], 64, 64, 1)
test_x = test_x.reshape(test_x.shape[0], 64, 64, 1)


1624635145567

#從keras的相應模塊引入需要的對象。
import warnings
warnings.filterwarnings('ignore') #該行代碼的作用是隱藏警告信息
import tensorflow as tf
import tensorflow.keras.layers as layers
import tensorflow.keras.backend as K
K.clear_session()
#逐層搭建卷積神經網絡模型。此處使用了函數式api
inputs = layers.Input(shape=(64,64,1), name='inputs')
conv1 = layers.Conv2D(32,3,3,padding="same",activation="relu",name="conv1")(inputs) #卷積層32
maxpool1 = layers.MaxPool2D(pool_size=(2,2),name="maxpool1")(conv1) #池化層1
conv2 = layers.Conv2D(64,3,3,padding="same",activation="relu",name="conv2")(maxpool1) #卷積層64
maxpool2 = layers.MaxPool2D(pool_size=(2,2),name="maxpool2")(conv2) #池化層2
flatten1 = layers.Flatten(name="flatten1")(maxpool2) #拉成一維
dense1 = layers.Dense(512,activation="tanh",name="dense1")(flatten1)
dense2 = layers.Dense(40,activation="softmax",name="dense2")(dense1) #40個分類
model = tf.keras.Model(inputs,dense2)
#網絡結構打印。
model.summary()

#模型編譯,指定誤差函數、優化方法和評價指標。使用訓練集進行模型訓練。
model.compile(loss='sparse_categorical_crossentropy', optimizer="Adam", metrics=['accuracy'])
model.fit(train_x,train_y, batch_size=20, epochs=30, validation_data=(test_x,test_y),verbose=2)


#評價
score = model.evaluate(test_x, test_y)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

#數據增強——ImageDataGenerator
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# 定義隨機變換的類別及程度
datagen = ImageDataGenerator(
        rotation_range=0,            # 圖像隨機轉動的角度
        width_shift_range=0.01,      # 圖像水平偏移的幅度
        height_shift_range=0.01,     # 圖像豎直偏移的幅度
        shear_range=0.01,            # 逆時針方向的剪切變換角度
        zoom_range=0.01,             # 隨機縮放的幅度
        horizontal_flip=True,
        fill_mode='nearest')



#使用增強後的數據進行模型訓練與評價
inputs = layers.Input(shape=(64,64,1), name='inputs')
conv1 = layers.Conv2D(32,3,3,padding="same",activation="relu",name="conv1")(inputs)
maxpool1 = layers.MaxPool2D(pool_size=(2,2),name="maxpool1")(conv1)
conv2 = layers.Conv2D(64,3,3,padding="same",activation="relu",name="conv2")(maxpool1)
maxpool2 = layers.MaxPool2D(pool_size=(2,2),name="maxpool2")(conv2)
flatten1 = layers.Flatten(name="flatten1")(maxpool2)
dense1 = layers.Dense(512,activation="tanh",name="dense1")(flatten1)
dense2 = layers.Dense(40,activation="softmax",name="dense2")(dense1)
model2 = tf.keras.Model(inputs,dense2)
model2.compile(loss='sparse_categorical_crossentropy', optimizer="Adam", metrics=['accuracy'])
# 訓練模型
model2.fit_generator(datagen.flow(train_x, train_y, batch_size=200),epochs=30,steps_per_epoch=16, verbose = 2,validation_data=(test_x,test_y))
# 模型評價
score = model2.evaluate(test_x, test_y)
print('Test score:', score[0])
print('Test accuracy:', score[1])

1624635233290

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章