預訓練CNN網絡的遷移學習(MATLAB例)

從基于大型數據集訓練的神經網絡中提取層,并基于新數據集進行微調。本例使用ImageNet中的子集進行微調。

This example retrains a SqueezeNet neural network using transfer learning. This network has been trained on over a million images, and can classify images into 1000 object categories (such as keyboard, coffee mug, pencil, and many animals). The network has learned rich feature representations for a wide range of images. The network takes an image as input and outputs a prediction score for each of these classes.

Performing transfer learning and fine-tuning of a pretrained neural network typically requires less data, is much faster, and is easier than training a neural network from scratch.

To adapt a pretrained neural network for a new task, replace the last few layers (the network head) so that it outputs prediction scores for each of the classes for the new task. This diagram outlines the architecture of a neural network that makes predictions for classes, and illustrates how to edit the network so that it outputs predictions for classes.

在這里插入圖片描述

ImageNet 使用 WordNet 的層級分類體系,每個類別有唯一的 ID。

  • 老虎(tiger)
    • WordNet ID: n02129604
    • 子類別: 包括孟加拉虎、西伯利亞虎(Indochinese tiger)等。
  • 兔子(rabbit)
    • WordNet ID: n02325366
    • 子類別: 如家兔(European rabbit)、野兔(hare)等。
  • 雞(chicken)
    • WordNet ID: n01514668
    • 子類別: 如母雞(hen)、公雞(rooster)、小雞(chick)等。

  • 老虎:1,300 張圖片(不同虎亞種)。
  • 兔子:1,300 張圖片(含家兔、野兔)。
  • :1,300 張圖片(含不同品種、年齡)。

在這里插入圖片描述


Load Training Data
Create an image datastore. An image datastore enables you to store large collections of image data, including data that does not fit in memory, and efficiently read batches of images when training a neural network. Specify the folder with the extracted images, and indicate that the subfolder names correspond to the image labels.

imds = imageDatastore(digitDatasetPath, ...IncludeSubfolders=true,LabelSource="foldernames");imds.Labels = renamecats(imds.Labels, {'n01514668', 'n02129604','n02325366'}, {'chicken', 'tiger','rabbit'});
numObsPerClass = countEachLabel(imds)
numObsPerClass = Label     Count_______    _____chicken    1300 tiger      1300 rabbit     1300 

Load Pretrained Network

To adapt a pretrained neural network for a new task, replace the last few layers (the network head) so that it outputs prediction scores for each of the classes for the new task. This diagram outlines the architecture of a neural network that makes predictions for classes, and illustrates how to edit the network so that it outputs predictions for classes.

Load a pretrained SqueezeNet neural network into the workspace by using the imagePretrainedNetwork function. To return a neural network ready for retraining for the new data, specify the number of classes. When you specify the number of classes, the imagePretrainedNetwork function adapts the neural network so that it outputs prediction scores for each of the specified number of classes.

You can try other pretrained networks. Deep Learning Toolbox? provides various pretrained networks that have different sizes, speeds, and accuracies. These additional networks usually require a support package. If the support package for a selected network is not installed, then the function provides a download link. For more information, see Pretrained Deep Neural Networks.

net = imagePretrainedNetwork("squeezenet",NumClasses=numClasses);
inputSize = networkInputSize(net)

The learnable layer in the network head (the last layer with learnable parameters) requires retraining. The layer is usually a fully connected layer, or a convolutional layer, with an output size that matches the number of classes.

The networkHead function, attached to this example as a supporting file, returns the layer and learnable parameter names of the learnable layer in the network head.

[layerName,learnableNames] = networkHead(net)

For transfer learning, you can freeze the weights of earlier layers in the network by setting the learning rates in those layers to 0. During training, the trainnet function does not update the parameters of these frozen layers. Because the function does not compute the gradients of the frozen layers, freezing the weights can significantly speed up network training. For small datasets, freezing the network layers prevents those layers from overfitting to the new dataset.
Freeze the weights of the network, keeping the last learnable layer unfrozen.

net = freezeNetwork(net,LayerNamesToIgnore=layerName);

Prepare Data for Training
The images in the datastore can have different sizes. To automatically resize the training images, use an augmented image datastore.

augImds = augmentedImageDatastore(inputSize(1:2),imds,ColorPreprocessing='gray2rgb');

Specify Training Options
Specify the training options. Choosing among the options requires empirical analysis. To explore different training option configurations by running experiments, you can use the Experiment Manager app.
For this example, use these options:
Train using the Adam optimizer.
Validate the network using the validation data every five iterations. For larger datasets, to prevent validation from slowing down training, increase this value.
Display the training progress in a plot, and monitor the accuracy metric.
Disable the verbose output.

opts = trainingOptions("adam", ...InitialLearnRate=1e-4, ...MaxEpochs=50, ...ValidationData=augImdsVal, ...Verbose=false,...Plots="training-progress", ...MiniBatchSize=128,...Metrics="accuracy");

Train Neural Network
Train the neural network using the trainnet function. For classification, use cross-entropy loss. By default, the trainnet function uses a GPU if one is available. Using a GPU requires a Parallel Computing Toolbox? license and a supported GPU device. For information on supported devices, see GPU Computing Requirements. Otherwise, the trainnet function uses the CPU. To specify the execution environment, use the ExecutionEnvironment training option.

rng default
net = trainnet(augImds,net,"crossentropy",opts);

沒有劃分數據集,因為這個例子本身的目的是為了觀察CNN的特征變換。
在這里插入圖片描述

>> summary(net)已初始化: true可學習參數的數量: 724k輸入:1   'data'   227×227×3 圖像

觀察在訓練集上的性能。

將預訓練的神經網絡直接應用于分類問題。要對新圖像進行分類,請使用 minibatchpredict。要將預測分類分數轉換為標簽,請使用scores2label 函數。有關如何使用預訓練神經網絡進行分類的示例,請參閱使用 GoogLeNet 對圖像進行分類。

在這里插入圖片描述

在這里插入圖片描述


Ambiguity of Classifications
You can use the softmax activations to calculate the image classifications that are most likely to be incorrect. Define the ambiguity of a classification as the ratio of the second-largest probability to the largest probability. The ambiguity of a classification is between zero (nearly certain classification) and 1 (nearly as likely to be classified to the most likely class as the second class). An ambiguity of near 1 means the network is unsure of the class in which a particular image belongs. This uncertainty might be caused by two classes whose observations appear so similar to the network that it cannot learn the differences between them. Or, a high ambiguity can occur because a particular observation contains elements of more than one class, so the network cannot decide which classification is correct. Note that low ambiguity does not necessarily imply correct classification; even if the network has a high probability for a class, the classification can still be incorrect.

[R,RI] = maxk(softmaxActivations,2,2);
ambiguity = R(:,2)./R(:,1);
Find the most ambiguous images.
[ambiguity,ambiguityIdx] = sort(ambiguity,"descend");
View the most probable classes of the ambiguous images and the true classes.
classList = unique(imds.Labels);
top10Idx = ambiguityIdx(1:10);
top10Ambiguity = ambiguity(1:10);
mostLikely = classList(RI(ambiguityIdx,1));
secondLikely = classList(RI(ambiguityIdx,2));
table(top10Idx,top10Ambiguity,mostLikely(1:10),secondLikely(1:10),imds.Labels(ambiguityIdx(1:10)),...VariableNames=["Image #","Ambiguity","Likeliest","Second","True Class"])
  10×5 tableImage #    Ambiguity    Likeliest    Second     True Class_______    _________    _________    _______    __________2268       0.99602      chicken     tiger       tiger    3330       0.99584      tiger       rabbit      rabbit   104       0.99187      chicken     tiger       chicken  304       0.98644      rabbit      chicken     chicken  1163       0.98466      tiger       chicken     chicken  3071       0.95684      chicken     rabbit      rabbit   1925       0.95373      rabbit      tiger       tiger    3006       0.95209      rabbit      chicken     rabbit   2772       0.93734      chicken     rabbit      rabbit   3461        0.9258      tiger       rabbit      rabbit  

容易錯分的地方就這三坨。原因是這些樣本都比較復雜,前景不突出,或者背景復雜,造成特征不明確。
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/83550.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/83550.shtml
英文地址,請注明出處:http://en.pswp.cn/web/83550.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

kali系統 windows Linux靶機入侵演練

Kali系統與Windows/Linux靶機入侵演練簡介 演練概述 Kali Linux是一款專為滲透測試和網絡安全評估設計的操作系統,常被安全專業人員用于合法的安全測試。入侵演練是網絡安全訓練的重要組成部分,旨在幫助安全人員了解攻擊手法并提升防御能力。 基本組件 1. **攻擊機**:通常…

手搓transformer

思路是這樣子的:從手搓代碼的角度去學習transformer,代碼會一個一個模塊地從頭到尾添加,以便學習者跟著敲,到最后再手搓一個基于tansformer的機器翻譯實戰項目。 transformer整體架構 一、輸入部分 詞向量 import torch import t…

網絡層協議:IP

目錄 1、概念 2、關鍵組成部分 2.1 IP地址 2.1.1 概念 2.1.2 主要版本 2.1.3 IP地址分類 2.2 IP數據報(IP協議傳輸的基本數據單元) 3、工作原理 3.1 路由 3.2 分片與重組 4、相關協議 1、概念 目的:負責在復雜的網絡環境中將數據…

Fastadmin報錯Unknown column ‘xxx.deletetime‘ in ‘where clause

報錯原因 在開啟軟刪除后,設置了表別名,軟刪除字段依舊使用原表名。 解決方法 原代碼 $list $this->model->with([admin, product])->where($where)->order($sort, $order)->paginate($limit);foreach ($list as $row) {$row->ge…

TCN+Transformer+SE注意力機制多分類模型 + SHAP特征重要性分析,pytorch框架

效果一覽 TCNTransformerSE注意力機制多分類模型 SHAP特征重要性分析 TCN(時序卷積網絡)的原理與應用 1. 核心機制 因果卷積:確保時刻 t t t 的輸出僅依賴 t ? 1 t-1 t?1 及之前的數據,避免未來信息泄露,嚴格保…

Elasticsearch的數據同步

elasticsearch中的數據多是來自數據庫,當數據庫發生改變時,elasticsearch也必須跟著改變,這個就叫做數據同步。 當我們是進行微服務的時候,同時兩個服務不能進行相互調用的時候。就會需要進行數據同步。 方法一:同步…

uniapp 時鐘

<template><view class"clock-view"><view class"clock-container u-m-b-66"><!-- 表盤背景 --><view class"clock-face"></view><!-- 時針 --><view class"hand hour-hand" :style&quo…

【大模型】實踐之1:macOS一鍵部署本地大模型

Ollama + Open WebUI 自動部署腳本解析說明文檔 先看下效果 一、腳本內容 #!/bin/bash set -eMODEL_NAME="qwen:1.8b" LOG_FILE="ollama_run.log" WEBUI_PORT=3000 WEBUI_CONTAINER_PORT=8080 WEBUI_URL="http://localhost:$WEBUI_PORT" DOC…

相機Camera日志實例分析之三:相機Camx【視頻光斑人像錄制】單幀流程日志詳解

【關注我&#xff0c;后續持續新增專題博文&#xff0c;謝謝&#xff01;&#xff01;&#xff01;】 上一篇我們講了&#xff1a; 這一篇我們開始講&#xff1a; 目錄 一、場景操作步驟 二、日志基礎關鍵字分級如下 三、場景日志如下&#xff1a; 一、場景操作步驟 操作步…

介紹一下 TCP方式程序的通訊,服務器機與客戶機

TCP通信方式&#xff1a;服務器與客戶機通信詳解 TCP(傳輸控制協議)是一種面向連接的、可靠的、基于字節流的傳輸層通信協議。下面我將詳細介紹TCP方式下服務器與客戶機的通信過程。 基本概念 TCP特點&#xff1a; 面向連接&#xff1a;通信前需建立連接可靠傳輸&#xff1a;…

Ubuntu系統復制(U盤-電腦硬盤)

所需環境 電腦自帶硬盤&#xff1a;1塊 (1T) U盤1&#xff1a;Ubuntu系統引導盤&#xff08;用于“U盤2”復制到“電腦自帶硬盤”&#xff09; U盤2&#xff1a;Ubuntu系統盤&#xff08;1T&#xff0c;用于被復制&#xff09; &#xff01;&#xff01;&#xff01;建議“電腦…

【PyTorch】2024保姆級安裝教程-Python-(CPU+GPU詳細完整版)-

一、準備工作 pytorch需要python3.6及以上的python版本 我是利用Anaconda來管理我的python。可自行安裝Anaconda。 Anaconda官網 Free Download | Anaconda 具體Anaconda安裝教程可參考 https://blog.csdn.net/weixin_43412762/article/details/129599741?fromshareblogdet…

Oracle RAC私網網卡冗余

第一步&#xff1a;添加網卡&#xff08;網絡部門實施&#xff09; 第二步&#xff1a;給新網卡配置ip地址&#xff08;如果網絡部門沒有配置&#xff0c;要自己動手配置&#xff09; 第三步&#xff1a;查看心跳網絡配置 –1 su - grid oifcfg getif enp0s3 192.168.1.0 glo…

c#,Powershell,mmsys.cpl,使用Win32 API展示音頻設備屬性對話框

常識&#xff08;基礎&#xff09; 眾所周知&#xff0c;mmsys.cpl使管理音頻設備的控制面板小工具&#xff0c; 其能產生一個對話框&#xff08;屬性表&#xff09;讓我們查看和修改各設備的詳細屬性&#xff1a; 在音量合成器中單擊音頻輸出設備的小圖標也能實現這個效果&a…

織夢dedecms內容頁調用seotitle標題的寫法

首先方法一&#xff0c;直接用織夢的sql實現&#xff1a; <title> {dede:field nametypeid runphpyes} $idme; global $dsql; $sql"select seotitle from dede_arctype where id$id"; $row$dsql->getOne($sql); me$row["seotitle"]; {/dede:fiel…

linux等保思路與例題

例題 最近在做玄機的靶場&#xff0c;對這方面沒怎么接觸過&#xff0c;于是決定做一下順便學習一下 這里可以用change更改命令來查看&#xff1a;change -l xiaoming 也可以用shadow中存儲的信息grep出來&#xff1a;cat /etc/shadow|grep xiaoming 其中&#xff1a; 第一個字…

AirSim中文文檔(2025-6-11)

文檔的git鏈接&#xff1a; https://github.com/yolo-hyl/airsim-zh-docs 目前可訪問的網站&#xff1a; https://airsim.huayezuishuai.site/

???????6板塊公共數據典型應用場景【政務服務|公共安全|公共衛生|環境保護|金融風控|教育科研]

1. 政務服務 1.1 城市規劃與管理 公共數據在城市規劃與管理中可發揮關鍵作用。通過匯聚自然資源、建筑物、人口分布等基礎數據,構建數字孿生城市模型,輔助城市總體規劃編制、決策仿真模擬。在城市基礎設施建設、安全運營、應急管理等方面,公共數據也是不可或缺的基礎支撐。例…

LevelDB介紹和內部機制

介紹 LevelDB 是 Google 開源的高性能鍵值對嵌入式數據庫&#xff0c;具有一系列設計上的優勢&#xff0c;特別適合寫多讀少、對存儲空間要求高效的場景。 核心優勢 1. 高寫入性能&#xff08;順序寫磁盤&#xff09; 基于 LSM-Tree&#xff08;Log Structured Merge Tree&am…

數據庫-數據查詢-Like

引言 &#xff1c;模糊溝通&#xff1e; 父親&#xff08;45歲&#xff0c;對外謙和&#xff0c;對內急躁&#xff0c;東北口音&#xff09; 兒子&#xff08;18歲&#xff0c;邏輯思維強&#xff0c;喜用生活化比喻&#xff09; 母親&#xff08;43歲&#xff0c;家庭矛盾調…