预训练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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈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;家庭矛盾调…