PyTorch 入门与实践(五)卷积神经网络(CNN)

利用Torch搭建与数据集尺寸匹配的CNN,以AlexNet为例 [CNN基础] 搭建与数据集尺寸匹配的CNN,以pytorch实现AlexNet为例1 实践中的困扰:网络与输入尺寸不匹配2 pytorch搭建适应32x32尺寸输入的AlexNet2.1 搭建标准的AlexNet2.2 适当调整结构 1 实践中的困扰:网络与输入尺寸不匹配 BackBone网络往往是针对特定数据集提出的。我们在工程实践中利用这些网络训练自己的数据集时,很可能会遭遇数据集与网络提出所用数据集输入尺寸不一致的问题。在遇到这种情况时,有两种方案可供我们选择: -> (1)在数据输入网络之前 阅读详情

来自 B 站刘二大人的《PyTorch深度学习实践》P10 的学习笔记

之前的由线性层组成的全连接网络是深度学习常用的分类器,由于全连接的特性,网络提取的特征未免冗余或者抓不住重点,比如像素的相对空间位置会被忽略。

所以,在全连接层前面加入特征提取器是十分有必要的,卷积神经网络就是最好的特征提取器。

CNN

1
关于卷积神经网络的输入输出特征图,以及多通道多批量的特征处理,参考:卷积神经网络的输入输出特征图大小计算。

单输出通道的卷积核:输入图像的每个通道分别对应一片卷积核矩阵,一次卷积最后会把输入图像的通道个数的特征图相加,最终得到一个单通道的特征图。
2
所以,

  • 每个卷积核的通道数和输入图像的通道数量一致,一个卷积核只输出一个单通道的特征图:
    3

  • 卷积核的数量决定输出特征图的个数,最后通过堆叠来形成一个多通道的特征图:
    4
    4.5

  • 卷积核的大小和输入图像大小无关,只有需要不同卷积层之间的特征图相加的时候,才需要考虑卷积核的大小和步幅,因为此时要求相加的特征图大小一致

PyTorch 卷积层

需要注意的是 PyTorch 中所有的输入数据都要求是 mini-batch 的,所以我们构建一个随机的 Tensor 作为输入的时候,torch.randn(batch_size, in_channels, width, height) 中第一个就要设置 batch-size 参数。

  • torch.nn.Conv2d(in_channels, out_channels, kernel_size)

    这里的三个参数是必须设置的。
    5
    设置填充(padding)、步幅(stride)、池化(pooling)的目的是为了控制输出特征图的大小,计算公式如下:
    o u t 边 长 = i n 边 长 + 2 ⋅ padding − kernel-size 2 ⋅ stride + 1 out_{边长} = \frac{in_{边长} + 2 \cdot \text{padding} - \text{kernel-size}}{2 \cdot \text{stride}} + 1 out边长​=2⋅stridein边长​+2⋅padding−kernel-size​+1

一个简单的 CNN

6
7
完整代码:

import os
import copy

import numpy as np
import torch
from torch import nn, optim
from torch.nn import functional as F
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

import matplotlib.pyplot as plt


trans = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307,), (0.3081,))
])

train_set = datasets.MNIST(root="../datasets/mnist",
                           train=True,
                           transform=trans,  # 原始是 PIL Image 格式
                           download=True)
test_set = datasets.MNIST(root="../datasets/mnist",
                          train=False,
                          transform=trans,
                          download=True)

train_loader = DataLoader(train_set, batch_size=64, shuffle=True)
test_loader = DataLoader(test_set, batch_size=64, shuffle=True)


class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1 = nn.Conv2d(1, 10, 5)
        self.conv2 = nn.Conv2d(10, 20, 5)
        self.linear = nn.Linear(320, 10)
        self.mp = nn.MaxPool2d(2)
        self.activate = nn.ReLU()

    def forward(self, x):
        batch_size = x.size(0)  # batch-size 所在维度不变,其它维展开成320,输入线性层
        x = self.activate(self.mp(self.conv1(x)))  # out: N,10,12,12
        x = self.activate(self.mp(self.conv2(x)))  # out: N,20,4,4
        x = x.view(batch_size, -1)  # out: N,320
        x = self.linear(x)
        return x


model = Model()

def train(model, train_loader, save_dst="./models"):
    global acc

    criterion = nn.CrossEntropyLoss()  # 包含了 softmax 层
    optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)  # SGD 对 batch-size 很敏感,64 是最好的;lr=0.01, momentum=0.5
    optim_name = optimizer.__str__().split('(')[0].strip()
    print("optimizer name:", optim_name)

    acc_lst = []

    for epoch in range(6):
        TP = 0
        loss_lst = []
        for i, (imgs, labels) in enumerate(train_loader):
            y_pred = model(imgs)
            # print("x:", x.shape, "y:", labels.shape, "y_pred:", y_pred.shape)

            loss = criterion(y_pred, labels)
            loss_lst.append(loss.item())

            y_hat = copy.copy(y_pred)
            TP += torch.sum(labels.flatten() == torch.argmax(y_hat, dim=1))

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

        acc = TP.data.numpy() / len(train_set)
        acc_lst.append(acc)
        print("epoch:", epoch, "loss:", np.mean(loss_lst), "acc:", round(acc, 3), f"TP: {TP} / {len(train_set)}")

    # 保存模型
    torch.save(model.state_dict(), os.path.join(save_dst, f"{optim_name}_acc_{round(acc, 2)}.pth"))
    print(f"model saved in {save_dst}")

    # 绘制精度曲线
    plt.plot(np.arange(len(acc_lst)), acc_lst)
    plt.tight_layout()
    plt.show()


def test(model, test_loader, load_dst="./models/SGD_acc_0.99.pth"):
    TP = 0
    model.load_state_dict(torch.load(load_dst))

    for i, (imgs, labels) in enumerate(test_loader):
        with torch.no_grad():
            y_pred = model(imgs)
        # print("x:", x.shape, "y:", labels.shape, "y_pred:", y_pred.shape)

        y_hat = copy.copy(y_pred)
        TP += torch.sum(labels.flatten() == torch.argmax(y_hat, dim=1))  # .sum().item()
    acc = TP.data.numpy() / len(test_set)
    print("acc:", round(acc, 4), f"TP: {TP} / {len(test_set)}")


def draw(model, test_loader, load_dst="./models/SGD_acc_0.99.pth"):
    model.load_state_dict(torch.load(load_dst))

    examples = enumerate(test_loader)
    _, (imgs, labels) = next(examples)

    with torch.no_grad():
        y_pred = model(imgs)

    for i in range(30):
        plt.subplot(5, 6, i + 1)
        plt.tight_layout()
        plt.imshow(imgs[i][0], cmap='gray', interpolation='none')
        plt.title("p: {}".format(
            y_pred.data.max(1, keepdim=True)[1][i].item()))
        plt.xticks([])
        plt.yticks([])
    plt.show()


if __name__ == '__main__':
    train(model, train_loader)
    # test(model, test_loader, load_dst="./models/Adam_acc_0.99.pth")
    # draw(model, test_loader, load_dst="./models/Adam_acc_0.99.pth")

运行结果
  • 精度曲线:
    9
  • 测试结果:
    10
作业题

构建一个稍微复杂的 CNN
11

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1 = nn.Conv2d(1, 24, 1)
        self.conv2 = nn.Conv2d(24, 16, 3)
        self.conv3 = nn.Conv2d(16, 8, 3)
        self.linear1 = nn.Linear(32, 64)
        self.linear2 = nn.Linear(64, 128)
        self.linear3 = nn.Linear(128, 10)
        self.mp = nn.MaxPool2d(2)
        self.activate = nn.ReLU()

    def forward(self, x):
        batch_size = x.size(0)  # batch-size 所在维度不变,其它维展开成320,输入线性层
        x = self.activate(self.mp(self.conv1(x)))
        x = self.activate(self.mp(self.conv2(x)))
        x = self.activate(self.mp(self.conv3(x)))  # out: N, 8, 2, 2
        x = x.view(batch_size, -1)  # N, 32
        x = self.linear1(x)
        x = self.linear2(x)
        x = self.linear3(x)
        return x

可能网络更复杂之后需要更多的训练 epoch,现在的精度没有之前的网络高。
12

使用 GPU

只需要两步:

  • 把模型转到 CUDA Tensor
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")  # 有 cuda 则使用 GPU
    model.to(device)
    
    13
  • 把训练数据转到 CUDA Tensor
    for batch_idx, data in enumerate(train_loader, 0):
        inputs, target = data
        inputs, target = inputs.to(device), target.to(device)
        outputs = model(inputs)
    
    14
Pytorch实现CNN_含验证集 一、CNN的结构 输入层---->[卷积层---->池化层]*n----->全连接层 part1 输入层–>卷积层 输入层:我们从mnist中下载黑白的手写数字图片。它的维度是 1 * 28 * 28。 (若是RGB图片,维度为 3* 28 *28) TIP:像素的值需要从区间[0~255] 压缩到 [0,1]。 卷积层:从原始的输入上进行特征的提取。 卷积核 kernel (or filter):16个 5*5; 步长 stride =1; 填充 padding = (5-s 阅读详情

相关推荐

特征图拼接、相加和相乘

特征图拼接、相加和相乘是在神经网络中进行特征融合的不同方式,它们各自有不同的优缺点,适用于不同的场景。假设我们有两个特征图A和B,它们的尺寸为[H, W, C1]和[H, W, C2],其中C1和C2分别是通道数。特征图拼接的优点是能够保留两个特征图的所有信息,适用于需要同时考虑不同特征的任务。特征图拼接是将多个特征图在通道维度上进行堆叠,以增加特征图的深度。特征图相加是将多个特征图逐元素相加,以融合它们的信息。特征图相乘的优点是可以增强共同出现的特征并减弱不重要的特征,适用于需要突出共同特征的任务。

吃葡萄不吐葡萄皮 1万+

[机器学习] 基于torch的CNN图像分类

基于torch搭建一个cnn网络模型,并使用数据对其进行训练、验证和测试的实验过程。

好风凭借力 2607

卷积神经网络(CNN)与深度卷积神经网络(DCNN)

作为小白,看到DCNN,一直想知道与CNN的区别,也没找到明确的说法,以下是自己的一点想法,欢迎指正! 目录 一、CNN与DCNN 二、基于pytorch的实现 1.LeNet-5 2.AlexNet 一、CNN与DCNN 卷积神经网络,如:LeNet 深度卷积神经网络,如:AlexNet AlexNet与LeNet结构类似,但使用了更多的卷积层和更大的参数空间来拟合大规模数据集ImageNet。 卷积神经网络就是含卷积层的网络。AlexNet是浅层神经网络和深度神经网络的分界..

chenfang0529的博客 5万+

PyTorch深度学习中卷积神经网络(CNN)的讲解及图像处理实战(超详细 附源码)

PyTorch深度学习中卷积神经网络(CNN)的讲解及图像处理实战(超详细 附源码)

showswoller的博客 4598

基于Pytorch的卷积神经网络CNN实例应用及详解

基于Pytorch的卷积神经网络CNN实例应用及详解 一、卷积神经网络CNN定义 卷积神经网络(CNN,有时被称为 ConvNet)是很吸引人的。在短时间内,它们变成了一种颠覆性的技术,打破了从文本、视频到语音等多个领域所有最先进的算法,远远超出了其最初在图像处理的应用范围。CNN 由许多神经网络层组成。卷积和池化这两种不同类型的层通常是交替的。网络中每个滤波器的深度从左到右增加。最后通常由一个或多个全连接的层组成。 二、卷积神经网络的原理 ...

rothschild666的博客 5522

【Pytorch教程】:卷积神经网络 CNN

Pytorch教程目录 Torch and Numpy 变量 (Variable) 激励函数 关系拟合(回归) 区分类型 (分类) 快速搭建法 批训练 加速神经网络训练 Optimizer优化器 卷积神经网络 CNN 目录Pytorch教程目录什么是卷积神经网络 CNN卷积 和 神经网络池化(pooling)流行的 CNN 结构CNN 卷积神经网络MNIST手写数据CNN模型训练可视化训练全部代码 什么是卷积神经网络 CNN 卷积 和 神经网络 卷积神经网络是如何运作的呢, 举一个识别图片的例子, 我们知

nanke_4869的博客 8092

CNN卷积神经网络实例(基于pytorch)

CNN卷积神经网络1.关于卷积神经网络2.卷积神经网络实例(手写字母识别)2.1 代码示例2.2 运行过程及结果2.3 测试结果3.参考与致谢 1.关于卷积神经网络 卷积神经网络(Convolutional Neural Network,CNN) 是一种具有局部连接、权重共享等特征的深层前馈神经网络。 我们先来看一下比较直观的了解一下,对卷积神经网络有个感性的认识: 我们首先先对我们输入的图片进行一次卷积,而后加入Relu激活函数,再做一次卷积,再加入Relu激活函数,而后对其处理结果进行汇聚(此处为Po

weixin_38468077的博客 2万+

基于Pytorch的卷积神经网络CNN实例应用及详解2.0

基于Pytorch的卷积神经网络CNN实例应用**依旧是DTI也就是药物靶体交互预测**,**数据训练预测模型框架没有变化**,**只有数据集的读取&处理和重新构造及损失函数选择发生变化**,其余部分发生细微变化。

rothschild666的博客 3543

Python CNN卷积神经网络实例讲解,CNN实战,CNN代码实例,超实用

Python CNN卷积神经网络实例讲解,CNN实战,CNN代码实例,套用简单

L_goodboy的博客 5万+

C++笔试题整理

目录 1. 笔试题1 1.1 链表反转 1.2 String 2. 笔试题2 2.1 求下面函数的返回值(微软) 2.2 什么是“引用”?申明和使用“引用”要注意哪些问题? 2.3 将“引用”作为函数参数有哪些特点? 2.4 在什么时候需要使用“常引用”?  2.5 将“引用”作为函数返回值类型的格式、好处和需要遵守的规则? 2.6 “引用”与多态的关系? 2.7 “引用”与指针的区别是什么? 2.8 什么时候需要“引用”? 2.9 结构与联合有和区别? 2.10 下面关于.

星月相随的专栏 2484

AD5700 HART芯片实战笔记:从时钟检测到数据收发,一个STM32工程师的踩坑实录

本文详细记录了STM32工程师在AD5700 HART芯片开发中的实战经验,涵盖时钟信号检测、RTS切换时序优化及HART数据解析等关键问题。通过硬件设计检查、定时器配置优化和大小端转换方案对比,解决了工业级芯片开发中的典型挑战,为嵌入式开发者提供宝贵参考。

weixin_42715608的博客 164

Pytorch基于卷积神经网络的人脸表情识别(白话CNN+数据集+代码实战)

Pytorch基于卷积神经网络的人脸识别(保姆级教程:白话CNN+数据集+代码实战) 前言 提示:本篇文章主要是关于李宏毅教授授课视频中的作业进行介绍,小白博主所作工作只是将现有的知识内容结合网路上一些优秀作者的总结以博文的形式加上自己的理解复述一遍。本文主要还是我的学习总结,因为网上的一些知识分布比较零散故作整理叙述。如果有不对的地方,还请帮忙指正,如有出现禁止转载的图片,文字内容请联系我修改。   相关参考:     李宏毅2020机器学习深度学习(完整版)国语:链接: lin

qq_43815869的博客 2万+

揭秘 | 顶刊论文插图中的高级配色方案(附RGB/HEX码解析)

本文揭秘了顶级期刊如《Nature》《Science》插图的高级配色方案,详细解析了RGB/HEX码的应用技巧。从双色配色的黄金组合到复杂数据可视化的多色解决方案,提供了实用的配色法则和跨平台一致性建议,帮助科研人员提升图表专业度和视觉传达效果。

weixin_28523493的博客 987

pytorch搭建CNN卷积神经网络详解

个人觉得应该先写卷积操作的常见技术和公式操作,才能对卷积输入维度(结果),输出维度(结果)有更直观的了解吧。 简单介绍一下卷积的常用trick: Padding Striding 下方是输入输出公式(本人开始也很困惑,找到对应公式后,就十分明朗了): n:原始输入的维度 | f:卷积核的大小 | p:padding的大小| s:stride的大小 no padding: n - ...

Troublemaker丶的博客 3万+

5分钟搞懂基因组规模代谢网络(GSMM):从数据库选择到模型构建全流程

本文详细解析基因组规模代谢网络(GSMM)构建的全流程,从数据库选择到模型优化。重点介绍MetaCyc、BiGG等主流数据库的黄金三角评估法则,对比自上而下与自下而上两种建模方法,并提供模型修剪、仿真优化的实用技巧与避坑指南,帮助研究者高效构建精准代谢网络模型。

weixin_30872157的博客 138

NuPlayer 之 Renderer

触发postDrainAudioQueue_l()或postDrainVideoQueue()开始渲染。解码器输出数据 → NuPlayer::Decoder::onMessageReceived。音频数据存入mAudioQueue,视频数据存入mVideoQueue。• 每次写入后通过mNotifyConsumed通知解码器。• 通过AudioSink::write()写入音频设备。• 根据VSync信号和音频时钟调整渲染时机。• 通过Surface直接提交给显示系统。

aningxiaoxixi的博客 313

【深度学习基础】详解Pytorch搭建CNN卷积神经网络LeNet-5实现手写数字识别

本文相熟了卷积神经网络CNN的原理,并介绍了如何使用PyTorch框架搭建卷积神经网络模型CNN。实现了LeNet-5的模型的搭建、模型训练、测试、网络的复用、直观查看数据集的图片预测结果等,完成了机器学习领域的Hello world——手写数字识别。

Bossfrank的博客 1万+

FastAPI + Layui:打造企业级敏捷开发后台管理系统

本文详细介绍了如何使用FastAPI和Layui构建高效的企业级后台管理系统。FastAPI提供高性能的异步API支持,而Layui则简化了前端开发流程,两者结合可实现快速开发和部署。文章涵盖了从环境搭建、核心组件开发到性能优化的全流程,特别适合需要敏捷开发的企业项目。

weixin_29045585的博客 555

【Pytorch】计算机视觉项目——卷积神经网络CNN模型识别图像分类

介绍卷积神经网络CNN的可视化解释器,分步骤详解如何使用Pytorch搭建CNN模型完成图像分类任务。

WHYbeHERE的博客 1万+

电子电器架构 -- 汽车零部件DV试验与PV试验的定义及关键差异

电子电器架构 -- 汽车零部件DV试验与PV试验的定义及关键差异

Soly_kun的博客 733

卷积神经网络中的自注意力机制(Self-Attention Mechanism)

卷积神经网络中的机制表现为操作,其实现过程与Seq2Seq模型的自注意力机制类似。标准的卷积层是一种局部滤波操作,其输出特征上的任意位置是由对应输入特征的一个邻域构造的,只能捕捉局部特征之间的关系。而自注意力机制通过计算任意两个位置之间的关系直接捕捉远程依赖,而不用局限于相邻点,相当于构造了一个的卷积核,从而可以捕捉更多信息。在卷积网络的自注意力机制中,首先构造输入特征x的键特征fx, 查询特征gx和值特征hx;

AI天才研究院 1501

卷积神经网络CNN/Pytorch,如何理解特征图Feature map?

基础详解,卷积神经网络/Pytorch,如何理解特征图Feature map?

MengYa_Dream的博客 2万+

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

CNN卷积神经网络简单示例(PyTorch)

CNN卷积神经网络简单示例(PyTorch)

两点点点的博客 7936

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

【AI 学习】深入解析卷积神经网络(CNN):理论、实现与应用

卷积神经网络(CNN)是计算机视觉领域的核心模型,能够自动提取图像特征并实现高效分类。本文系统介绍了CNN的发展背景、理论基础及实践应用,重点解析了局部感受野、参数共享和池化等核心设计理念,详细阐述了卷积层、池化层、全连接层等组件的工作原理。通过PyTorch框架实现了MNIST手写数字识别的CNN模型,并探讨了经典模型演进与优化策略。文章从理论到实践全面讲解CNN,为读者提供了计算机视觉领域的重要参考。

CodeSuc 的技术博客 4541

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

搭建CNN卷积神经网络(用pytorch搭建)

手撕卷积神经网络—CNN 卷积:提取特征 池化:压缩特征 heigh X weigh X depth 长度 宽度。深度(也就是特征图个数) 例如输入32x32x3 hxwxc 卷积就是取某个小区域进行特征计算用此处的 特征值x权重特征 进而得到最终数据输出 filter相当于助手可以有一个 但是也可以有多个 可以定义f1 f2 f3…当然得到特征图越丰富越是我们想要的结果但是多个卷积核的容积必须是相同 否则则无法相加。 移动步长 可以大一点也可以小一点用1就可以 卷积核尺寸 可以大一点 也可以小一点 大的话

weixin_46900108的博客 9081

【Python · PyTorch】卷积神经网络 CNN(基础概念)

本文介绍卷积神经网络的基础概念,为博主自用笔记提纲。

茶色喵的博客 6012
上一篇: PyTorch 入门与实践(四)多分类问题(Softmax)
下一篇: PyTorch 入门与实践(六)卷积神经网络进阶(GoogLeNet、ResNet)
Skr.B
博客等级 码龄8年 1103粉丝 81原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Skr.B

WUHOOO~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值