MATLAB深度學(xué)習(xí)工具箱使用教程

一、introduction

深度學(xué)習(xí)對(duì)于圖像識(shí)別

二、using pretrained Networks

1、加載并顯示圖像

img1 = imread('file01.jpg');

imshow(img1)

2、預(yù)測(cè)

deepnet = alexnet; %獲取預(yù)訓(xùn)練模型

pred1 = classify(deepnet, img1); %預(yù)測(cè)img1

3栅盲、獲取其他預(yù)訓(xùn)練模型




4、examine network layers


deepnet = alexnet; ?%獲取預(yù)訓(xùn)練網(wǎng)絡(luò)

ly = deepnet.Layers废恋;%獲取網(wǎng)絡(luò)layers

inlayer = ly(1)谈秫; %獲取輸入層結(jié)構(gòu)

insz = inlayer.InputSize; %獲取輸入層size

outlayer = ly(end)鱼鼓; %獲取輸出層

categorynames = outlayer.Classes拟烫; %獲取最后一層的class

5、investigating predictions

分類函數(shù)返回輸入圖像的預(yù)測(cè)類迄本,但是有辦法知道網(wǎng)絡(luò)對(duì)這個(gè)分類有多“自信”嗎?在決定如何處理輸出時(shí)硕淑,考慮這種信心可能很重要。

為了將輸入分類為n個(gè)類中的一個(gè)嘉赎,神經(jīng)網(wǎng)絡(luò)有一個(gè)由n個(gè)神經(jīng)元組成的輸出層置媳,每個(gè)神經(jīng)元對(duì)應(yīng)一個(gè)類。通過網(wǎng)絡(luò)傳遞輸入結(jié)果是為每個(gè)神經(jīng)元計(jì)算一個(gè)數(shù)值公条。這些數(shù)值表示網(wǎng)絡(luò)對(duì)屬于每個(gè)類的輸入概率的預(yù)測(cè)拇囊。


img = imread('file01.jpg');

imshow(img)

net = alexnet;

categorynames = net.Layers(end).ClassNames;

[pred, scores] = classify(net, img); ?%獲得預(yù)測(cè)結(jié)果和自信分?jǐn)?shù)

bar(scores); %Display scores

highscores = scores > 0.01; %Threshold scores

bar(scores(highscores)); %Display thresholded scores

xticklabels(categorynames(highscores)); %Add tick labels

三、managing collections of data

1靶橱、creating a datastore

ls *.jpg

net = alexnet;

imds = imageDatastore('file*.jpg'); %創(chuàng)建datastore

fname = imds.Files; %提取文件名

img = readimage(imds, 7); ?%讀取圖像

preds = classify(net, imds)寥袭; %圖片分類


2、 Preparing Images to Use as Input: Adjust input images

Process Images for Classification

img = imread('file01.jpg');

imshow(img);

sz = size(img); ?%讀取圖像大小

net = alexnet;

insz = net.Layers(1).InputSize; ?%輸入層圖像大小

img = imresize(img, [227, 227]); ?

imshow(img);

3关霸、Processing Images in a Datastore: (2/3) Creating an augmented image datastore

Resize Images in a Datastore

ls *.jpg

net = alexnet传黄;

imds = imageDatastore('*.jpg');

auds = augmentedImageDatastore([227,227], imds); %Create augmentedImageDatastore

preds = classify(net, auds)

Processing Images in a Datastore: (3/3) Color preprocessing with augmented image datastores

augmentedImageDatastore可以對(duì)彩色圖片進(jìn)行處理

ls *.jpg

net = alexnet队寇;

imds = imageDatastore('file*.jpg')膘掰;

montage(imds); %Display images in imds

auds = augmentedImageDatastore([227,227], imds, 'ColorPreprocessing', 'gray2rgb') %Create augmentedImageDatastore

preds = classify(net, auds)

Create a Datastore Using Subfolders

net = alexnet;

flwrds = imageDatastore('Flowers', 'IncludeSubfolders',true);

preds = classify(net,flwrds)

四佳遣、transfer learn

1识埋、原因

(1)原有NET不能解決有效自己的問題

(2)自己訓(xùn)練一個(gè)全新的網(wǎng)絡(luò)--網(wǎng)絡(luò)結(jié)構(gòu)與隨機(jī)權(quán)重啤覆,需要具有網(wǎng)絡(luò)架構(gòu)方面的知識(shí)和經(jīng)驗(yàn)、大量的訓(xùn)練數(shù)據(jù)惭聂、大量的計(jì)算時(shí)間

2、Components Needed for Transfer Learning: (1/2) The components of transfer learning


3相恃、 Preparing Training Data: (1/3) Labeling images

Label Images in a Datastore

load pathToImages

flwrds = imageDatastore(pathToImages,'IncludeSubfolders',true); ?%This code creates a datastore of 960 flower images.

flowernames = flwrds.Labels

flwrds = imageDatastore(pathToImages,'IncludeSubfolders',true,'LabelSource','foldernames') ?%Create datastore with labels

flowernames = flwrds.Labels ?%Extract new labels

Preparing Training Data: (2/3) Split data for training and testing

Split Data for Training and Testing

Instructions are in the task pane to the left. Complete and submit each task one at a time.

This code creates a datastore of 960 flower images.

load pathToImages

flwrds = imageDatastore(pathToImages,'IncludeSubfolders',true,'LabelSource','foldernames')

Task 1

Split datastore

[flwrTrain, flwrTest] = splitEachLabel(flwrds, 0.6)

Task 2

Split datastore randomly

[flwrTrain, flwrTest] = splitEachLabel(flwrds, 0.8, 'randomized')

Task 3

Split datastore by number of images

[flwrTrain, flwrTest] = splitEachLabel(flwrds,50)


Preparing Training Data: (3/3) Augmented training data


4辜纲、微調(diào)思路
(1)Recall that a feed-forward network is represented in MATLAB as an array of layers. This makes it easy to index into the layers of a network and change them.

(2)To modify a preexisting network, you create a new layer

(3)then index into the layer array that represents the network and overwrite the chosen layer with the newly created layer.

(4)As with any indexed assignment in MATLAB, you can combine these steps into one line.

Modifying Network Layers: (2/2) Modify layers of a pretrained network

Modify Network Layers

Instructions are in the task pane to the left. Complete and submit each task one at a time.

This code imports AlexNet and extracts its layers.

anet = alexnet;

layers = anet.Layers

Task 1

Create new layer

fc = fullyConnectedLayer(12)

Task 2

Replace 23rd layer

layers(23) = fc

Task 3

Replace last layer

layers(end) = classificationLayer

Setting Training Options

Set Training Options

Instructions are in the task pane to the left. Complete and submit each task one at a time.

Task 1

Set default options

opts = trainingOptions('sgdm');

Task 2

Set initial learning rate

opts = trainingOptions('sgdm','InitialLearnRate',0.001);

Training the Network: (4/4) Summary example

Transfer Learning Example Script

The code below implements transfer learning for the flower species example in this chapter. It is available as the script?trainflowers.mlx?in the course example files. You can download the course example files from the help menu in the top-right corner. You can find more information on this dataset at the?17 Category Flower Dataset?page from the University of Oxford.?

Note that this example can take some time to run if you run it on a computer that does not have a?supported GPU.

Get training images

flower_ds = imageDatastore('Flowers','IncludeSubfolders',true,'LabelSource','foldernames');[trainImgs,testImgs] = splitEachLabel(flower_ds,0.6);numClasses = numel(categories(flower_ds.Labels));


Create a network by modifying AlexNet

net = alexnet;layers = net.Layers;layers(end-2) = fullyConnectedLayer(numClasses);layers(end) = classificationLayer;


Set training algorithm options

options = trainingOptions('sgdm','InitialLearnRate', 0.001);


Perform training

[flowernet,info] = trainNetwork(trainImgs, layers, options);


Use trained network to classify test images

testpreds = classify(flowernet,testImgs);

4.7 Evaluating Performance: (1/3) Evaluating training and test performance

Evaluate Performance

Instructions are in the task pane to the left. Complete and submit each task one at a time.

This code loads the training information of flowernet.

load pathToImages

load trainedFlowerNetwork flowernet info

Task 1

Plot training loss

plot(info.TrainingLoss)

This code creates a datastore of the flower images.

dsflowers = imageDatastore(pathToImages,'IncludeSubfolders',true,'LabelSource','foldernames');

[trainImgs,testImgs] = splitEachLabel(dsflowers,0.98);

Task 2

Classify images

flwrPreds = classify(flowernet,testImgs)

Evaluating Performance: (2/3) Investigating test performance

Investigate test performance

Instructions are in the task pane to the left. Complete and submit each task one at a time.

This code sets up the Workspace for this activity.

load pathToImages.mat

pathToImages

flwrds = imageDatastore(pathToImages,'IncludeSubfolders',true,'LabelSource','foldernames');

[trainImgs,testImgs] = splitEachLabel(flwrds,0.98);

load trainedFlowerNetwork flwrPreds

Task 1

Extract labels

flwrActual = testImgs.Labels

Task 2

Count correct

numCorrect = nnz(flwrPreds == flwrActual)

Task 3

Calculate fraction correct

fracCorrect = numCorrect/numel(flwrPreds)

Task 4

Display confusion matrix

confusionchart(testImgs.Labels,flwrPreds)

Evaluating Performance: (3/3) Improving performance

MATLAB Course

Transfer Learning Summary

Transfer Learning Function Summary

Create a network

FunctionDescription

alexnetLoad pretrained network “AlexNet”

supported networksView list of available pretrained networks

fullyConnectedLayerCreate new fully connected network layer

classificationLayerCreate new output layer for a classification network


Get training images

FunctionDescription

imageDatastoreCreate datastore reference to image files

augmentedImageDatastorePreprocess a collection of image files

splitEachLabelDivide datastore into multiple datastores


Set training algorithm options

FunctionDescription

trainingOptionsCreate variable containing training algorithm options


Perform training

FunctionDescription

trainNetworkPerform training


Use trained network to perform classifications

FunctionDescription

classifyObtain trained network's classifications of input images


Evaluate trained network

FunctionDescription

nnzCount non-zero elements in an array

confusionchartCalculate confusion matrix

heatmapVisualize confusion matrix as a heatmap

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市拦耐,隨后出現(xiàn)的幾起案子耕腾,更是在濱河造成了極大的恐慌,老刑警劉巖杀糯,帶你破解...
    沈念sama閱讀 212,454評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件扫俺,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡固翰,警方通過查閱死者的電腦和手機(jī)狼纬,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,553評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來骂际,“玉大人疗琉,你說我怎么就攤上這事∏嘎粒” “怎么了盈简?”我有些...
    開封第一講書人閱讀 157,921評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)太示。 經(jīng)常有香客問我柠贤,道長(zhǎng),這世上最難降的妖魔是什么类缤? 我笑而不...
    開封第一講書人閱讀 56,648評(píng)論 1 284
  • 正文 為了忘掉前任臼勉,我火速辦了婚禮,結(jié)果婚禮上呀非,老公的妹妹穿的比我還像新娘坚俗。我一直安慰自己,他們只是感情好岸裙,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,770評(píng)論 6 386
  • 文/花漫 我一把揭開白布猖败。 她就那樣靜靜地躺著,像睡著了一般降允。 火紅的嫁衣襯著肌膚如雪恩闻。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,950評(píng)論 1 291
  • 那天剧董,我揣著相機(jī)與錄音幢尚,去河邊找鬼破停。 笑死,一個(gè)胖子當(dāng)著我的面吹牛尉剩,可吹牛的內(nèi)容都是我干的真慢。 我是一名探鬼主播,決...
    沈念sama閱讀 39,090評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼理茎,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼黑界!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起皂林,我...
    開封第一講書人閱讀 37,817評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤朗鸠,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后础倍,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體烛占,經(jīng)...
    沈念sama閱讀 44,275評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,592評(píng)論 2 327
  • 正文 我和宋清朗相戀三年沟启,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了忆家。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,724評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡德迹,死狀恐怖弦赖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情浦辨,我是刑警寧澤蹬竖,帶...
    沈念sama閱讀 34,409評(píng)論 4 333
  • 正文 年R本政府宣布,位于F島的核電站流酬,受9級(jí)特大地震影響币厕,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜芽腾,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,052評(píng)論 3 316
  • 文/蒙蒙 一旦装、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧摊滔,春花似錦阴绢、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至腺兴,卻和暖如春左电,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評(píng)論 1 266
  • 我被黑心中介騙來泰國(guó)打工篓足, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留段誊,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,503評(píng)論 2 361
  • 正文 我出身青樓栈拖,卻偏偏與公主長(zhǎng)得像连舍,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子涩哟,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,627評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容

  • 有這樣傳說“夢(mèng)染簇,是另一個(gè)世界你的寫照,白天你在這個(gè)世界强岸,待到你睡著之時(shí)又在另一個(gè)世界生活著锻弓。沒有人知道是什么原因。...
    曲沙南風(fēng)閱讀 262評(píng)論 5 20
  • 早上9點(diǎn)半蝌箍,做了一小時(shí)的方案青灼,有點(diǎn)累有點(diǎn)困,這時(shí)電話打來妓盲, “您好杂拨,某東快遞,請(qǐng)您下樓來簽收一下悯衬,然后我們幫您送樓...
    橘阿撩閱讀 99評(píng)論 0 0