Keras【极简】CNN

Keras上实现卷积神经网络CNN 一、概述及完整代码 本例的代码主要来自Keras自带的example里的mnist_cnn模块,主要用到keras.layers中的Dense, Dropout, Activation, Flatten模块和keras.layers中的Convolution2D,MaxPooling2D。构建一个两层卷积层两层全连接层的简单卷积神经网络,12次循环后可以达到99.25%的准确率,课件CNN的预测 阅读详情

1、极简示例

from keras.datasets import cifar10  # 小图像10分类
from keras.utils import to_categorical  # 独热码
from keras.models import Sequential  # 顺序模型
from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D

"""数据读取、预处理"""
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train, x_test = x_train / 255, x_test / 255  # 像素值→[0,1]
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)

"""创建顺序模型"""
model = Sequential()
# 卷积层:30个3x3的卷积滤波器、ReLU激活
model.add(Conv2D(30, (3, 3), padding='same', activation='relu'))
# 池化层
model.add(MaxPooling2D(pool_size=(2, 2)))
# 平坦化
model.add(Flatten())
# 全连接层:神经元个数、ReLU激活
model.add(Dense(100, activation='relu'))
# 输出层(10分类)
model.add(Dense(10, activation='softmax'))

"""模型编译"""
# 优化器【随机梯度下降】;损失函数【分类交叉熵】;添加度量【精准度】
model.compile('sgd', 'categorical_crossentropy', ['accuracy'])

"""训练"""
model.fit(x_train, y_train, 1000, 2)  # 批量、训练次数

"""模型评估"""
loss, acc = model.evaluate(x_test, y_test, 1000)
print('loss %g  acc %g' % (loss, acc))

2、详细示例

from keras.datasets import cifar10
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
from keras.utils import plot_model  # conda install pydot
from keras.optimizers import RMSprop  # 优化器
from keras.preprocessing.image import ImageDataGenerator  # 图像生成器
import matplotlib.pyplot as mp

"""数据读取、预处理"""
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
input_shape = x_train.shape[1:]
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# 数据增强
batch_size = 100
steps_per_epoch = len(y_train) / batch_size
epochs = 2
idg_train = ImageDataGenerator(
    horizontal_flip=True,
    rescale=1/255).flow(x_train, y_train, batch_size)
idg_test = ImageDataGenerator(
    rescale=1/255).flow(x_test, y_test, batch_size)
del x_train, y_train, x_test, y_test  # 释放内存

"""建模"""
model = Sequential()
model.add(Conv2D(30, (3, 3), activation='relu',
                 input_shape=input_shape))  # 输入尺寸使编译成功))
model.add(MaxPooling2D(pool_size=(2, 2), name='MaxPooling2D'))
model.add(Flatten())
model.add(Dense(100, activation='relu'))
model.add(Dense(10, activation='softmax'))
optimizer = RMSprop(lr=1e-3, decay=1e-6)
model.compile(optimizer, 'categorical_crossentropy', ['acc'])

"""训练"""
history = model.fit_generator(
    idg_train, steps_per_epoch, epochs,
    validation_data=idg_test,
    validation_steps=batch_size)

"""模型可视化"""
model.summary()  # 网络维度
plot_model(model, 'model.png', show_shapes=True,
           show_layer_names=False)  # 网络结构(存图片)

"""损失曲线和精度曲线"""
ls = ['loss', 'val_loss', 'acc', 'val_acc']
hs = [history.history[i] for i in ls]
for i in (0, 1):
    mp.subplot(1, 2, i + 1)
    mp.plot(range(1, epochs + 1), hs[i * 2], 'g', label=ls[i * 2])
    mp.plot(range(1, epochs + 1), hs[i * 2 + 1], label=ls[i * 2 + 1])
    mp.legend()
mp.show()

2.1、内置数据集

from keras.datasets import cifar10  # 10分类小图像
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
print(x_train.shape)  # (50000, 32, 32, 3)
print(y_train.shape)  # (50000, 1)
print(x_test.shape)  # (10000, 32, 32, 3)
print(y_test.shape)  # (10000, 1)
import matplotlib.pyplot as mp, numpy as np
images = np.concatenate([x_train[i] for i in range(9)], axis=1)
mp.imshow(images)
mp.show()

在这里插入图片描述

2.2、图像生成器

from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as mp, numpy as np
# 数据读取
(x_train, y_train), _ = cifar10.load_data()
imgs = x_train[:3]
# 图像生成器
idg = ImageDataGenerator(
    rescale=1./255,  # 像素值→[0,1]
    rotation_range=30,  # 旋转角度
    horizontal_flip=True,  # 水平翻转
    width_shift_range=.3,  # 水平偏移
    height_shift_range=.3)  # 垂直偏移
# 可视化
for e, i in enumerate(idg.flow(imgs, shuffle=False), 1):
    if e > 9: break  # 打断死循环
    mp.subplot(1, 9, e)
    mp.axis('off')
    img = np.concatenate(i)
    mp.imshow(img)
mp.show()

在这里插入图片描述

2.3、模型可视化

.summary

Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 30, 30, 30)        840       
_________________________________________________________________
MaxPooling2D (MaxPooling2D)  (None, 15, 15, 30)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 6750)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 100)               675100    
_________________________________________________________________
dense_2 (Dense)              (None, 10)                1010      
=================================================================
Total params: 676,950
Trainable params: 676,950
Non-trainable params: 0

plot_model(model, show_shapes=True, show_layer_names=False)
在这里插入图片描述

2.4、损失曲线和精度曲线

在这里插入图片描述

3、EarlyStopping设置自动结束

from keras.datasets import cifar10
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout
from keras import optimizers
from keras.callbacks import EarlyStopping  # 提早停止训练
import matplotlib.pyplot as mp

"""训练批量和轮数"""
batch_size = 500
epochs = 50  # 总训练轮数
min_delta = .01  # 最小进步,低于该值将被认为没有进步
patience = 5  # 没有进步的训练轮数

"""读数据、预处理"""
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train, x_test = x_train / 255, x_test / 255
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)

"""建模"""
model = Sequential()
for i in (32, 64, 128):
    model.add(Conv2D(i, (3, 3), padding='same', activation='relu'))
    model.add(Conv2D(i, (3, 3), padding='same', activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(.25))
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dropout(.5))
model.add(Dense(10, activation='softmax'))
optimizer = optimizers.RMSprop(lr=1e-3, decay=1e-6)
# 模型编译
model.compile(optimizer, 'categorical_crossentropy', ['acc'])
# 拟合(取1%样本用于验证)、自动结束
callback = EarlyStopping('val_acc', min_delta, patience)
history = model.fit(x_train, y_train, batch_size, epochs, verbose=2,
                    callbacks=[callback], validation_split=.01)

"""评估"""
loss, acc = model.evaluate(x_test, y_test, batch_size, verbose=2)
print('loss %g  acc %g' % (loss, acc))
acc = history.history['acc']
val_acc = history.history['val_acc']
mp.plot(range(len(acc)), acc, 'g', label='acc')
mp.plot(range(len(val_acc)), val_acc, label='val_acc')
mp.legend()
mp.show()
encnencn
convolution卷积;盘旋Conv2D二维卷积
util跑龙套;工具regularizer正则化矩阵
dense稠密的flatten铲平vt;变平vi
optimize优化epoch新纪元;时间上的一点
categorical绝对的;分类的sequential连续的
pooling[贸易]联营;池化drop out退学;脱离
validation确认;批准;生效summary摘要
rotation旋转flip筋斗
rescale重新调节shift移动
patience耐性monitor监视器;显示屏;监测
Keras 搭建图片分类 CNN (卷积神经网络) 1. 导入keras from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense 2. Conv2D 构建卷积层。用于从输入的高维数组中提取特征。卷积层的每个过滤器就是一个特征映射,用于提取某一个特征,过滤器的数量决定了卷积层输出特征个数,或者输出深度。因此,图... 阅读详情

相关推荐

用keras搭建CNN卷积神经网络

CNN的架构 卷积神经网络CNN的结构一般包含这几个层: 1)输入层:用于数据的输入 2)卷积层:使用卷积核进行特征提取和特征映射------>可以多次重复使用 3)激励层:由于卷积也是一种线性运算,因此需要增加非线性映射(也就是激活函数) 4)池化层:进行下采样,对特征图稀疏处理,减少数据运算量----->可以多次重复使用 5)Flatten操作:将二维的向量,拉直为一维的向量,从而可以放入下一层的神经网络中 6)全连接层:通常在CNN的尾部进行重新拟合,减少特征信息的损失----->D

罐罐罐子的博客 4305

深度学习mindspore --- rescale(rescale, shift)

class mindspore.dataset.transforms.vision.c_transforms.Rescale(rescale,shift)[source] Tensor operation torescalethe input image. Parameters rescale(float) –Rescalefactor. shift(float) – Shift factor. 这个函数的意思很多种: 1, rescale是尺度...

my_share的专栏 4080

深度学习:Keras实现卷积神经网络CNN

写在前面 刚刚开始学习keras,就在这里记录一下学习过程啦。 本文为使用卷积神经网络CNN进行mnist手写字符的识别,希望自己就此走进deep learning的大门吧。 keras文档:https://keras.io/zh/ 莫烦python bilibili链接:https://space.bilibili.com/243821484/video 一、代码 keras相关导入 impo...

慢慢慢慢曼 3328

吴恩达团队 Tensorflow课程学习笔记 2-----图像增强

图像增强 train_datagen = ImageDataGenerator(rescale=1./255) 之前学的图像生成器就有图像增强的功能,上面代码中已经完成了一点图像增强的功能----图像加载的时候就可以完成重新缩放 train_datagen = ImageDataGenerator( rescale=1./255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2

Doreenqiuyue的博客 656

基于keras建立简单的CNN

开发环境: Win10 Anaconda3 Python3.6 处理器:AMD A8-7100 Radeon R5,8 Compute Cores 4C+4G 数据集: mnist 准备工作: 安装theano  pip install theano (此处注意最好安装>0.8版本的,不然后面可能出bug) 安装keras pip install keras

Miracle_guy的博客 5231

[Python人工智能] 十八.Keras搭建卷积神经网络及CNN原理详解

从本专栏开始,作者正式研究Python深度学习、神经网络及人工智能相关知识。前一篇文章详细讲解了Keras实现分类学习,以MNIST数字图片为例进行讲解。本篇文章详细讲解了卷积神经网络CNN原理,并通过Keras编写CNN实现了MNIST分类学习案例。基础性文章,希望对您有所帮助!

杨秀璋的专栏 1万+

深度学习中的正则化(一)

深度学习中的正则化方法

myDarling_的博客 376

卷积神经网络 (CNN) 原理详解与 Keras 实践

卷积神经网络 (Convolutional Neural Network, CNN) 的提出是为了解决传统神经网络的缺陷。即使对象位于图片中的不同位置或其在图像中具有不同占比,CNN 依旧能够正确的处理这些图像,因此在对象分类/检测任务中更加有效。在本节中,我们将使用 Keras 构建卷积神经网络模型进行图像分类,介绍 CNN 的基础知识,并构建 CNN 模型。

盼小辉丶的博客 4243

一文解决图片数据集太少的问题:详解KerasImageDataAugmentation各参数

作者 |Professor ho 本文转自Professor ho的知乎专栏 图像深度学习任务中,面对小数据集,我们往往需要利用Image Data Augmentation图像增广技术来扩充我们的数据集,而keras的内置ImageDataGenerator很好地帮我们实现图像增广。但是面对ImageDataGenerator中众多的参数,每个参数

AI科技大本营 9313

卷积神经网络CNN基本原理详解

卷积神经网络(Convolutional Neural Network,简称CNN),是一种前馈神经网络,人工神经元可以响应周围单元,可以进行大型图像处理。卷积神经网络包括卷积层和池化层。

GoppViper的博客 9万+

keras 学习 CNN LSTM

文章目录第一章 keras简介1 简介2 搭建神经网络步骤3 数据格式(data_format)4 模型5 keras源码分析第二章 多层感知器 DNN1、单个神经元2、多层感知机3、怎么训练MLP(BP算法)4、反思5、使用keras构建MLP第二章 CNN卷积神经网络1、CNN理解2、LeNet3、keras构建CNN第三章 RNN循环神经网络1、RNN简介2、...

q742971636的博客 5298

Keras数据增强

数据增强生成器: train_datagen = ImageDataGenerator(rescale=1. / 255, #归一化 rotation_range=10, #旋转角度 width_shift_range=0....

Harrison509的博客 4914

3D医学影像分割新突破:手把手教你用MedSAM2快速标注CT/MRI数据(附3D Slicer插件配置)

本文详细介绍了如何利用MedSAM2模型进行3D医学影像分割,包括从环境准备到3D Slicer插件配置的全流程。通过实战案例和技巧分享,帮助医疗从业者快速掌握CT/MRI数据的高效标注方法,提升医学影像分析的准确性和效率。

ujm5678901的博客 306

NVIDIA-Nemotron-3-Nano-30B-A3B-MLX-5bit 许可证与社区指南:可商用吗?常见问题与求助渠道清单

**NVIDIA-Nemotron-3-Nano-30B-A3B-MLX-5bit** 是 NVIDIA Nemotron 3 Nano(30B 总参数 / 约 3B 激活参数 MoE 模型)的 5-bit MLX 量化版,专为 Apple Silicon 优化。本文直接回答新手最关心的问题:**这个模型能商用吗?** 它的许可证是 NVIDIA 自有的 `nvidia-open-model-li

gitblog_00833的博客 380

基于STM32的智能停车场管理系统

随着城市车辆数量激增,传统停车场管理效率低下。本文设计了一款基于STM32的智能停车场管理系统,支持车牌识别、车位引导、自动计费等功能,可显著提升停车场运营效率。系统适用于商场、小区等场景,支持多终端协同管理。本系统实现了停车场智能化管理,显著提升了运营效率。:STM32F746(高性能Cortex-M7)问题讨论,stm32的资料领取可以私信!:OV7725摄像头(30fps):ESP32(Wi-Fi+蓝牙)红外对射传感器(车辆进出检测)支持蓝牌、黄牌、新能源车牌。⬇帮大家整理了单片机的资料。

stm32d1219的博客 879

Vue3实战:企业级应用集成钉钉扫码登录全流程解析

本文详细解析了在Vue3企业级应用中集成钉钉扫码登录的全流程。从钉钉开放平台应用创建与配置,到Vue3前端如何优雅地嵌入并管理扫码组件,再到后端如何安全地处理OAuth 2.0授权码以换取用户信息并完成登录,提供了完整的实战代码与避坑指南。该方案能有效实现安全便捷的单点登录,统一企业身份认证。

weixin_29019241的博客 303

Keras之00-入门介绍

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34268169的博客 103

ad23新版Geber导出-官方教程(22.11版本后)

AD23新版本geber文件导出(含官方教程)-22.11之后的版本均可用此教程

安和的博客 3万+

深度学习极简实战:200行代码跑通端到端图像分类

深度学习入门常陷于理论堆砌与环境崩坏的双重困境,而真正可落地的实践需回归‘最小可行认知闭环’——从张量形状理解、数据加载调试到模型轻量部署。本文聚焦图像分类这一基础任务,以NumPy+TensorFlow/Keras极简工具链(仅4个核心包)为载体,详解真实场景中必遇的维度陷阱、HEIC格式报错、梯度消失诊断及TFLite量化部署等关键环节。通过自制噪声数据集、手写数据生成器与三图监控法,将抽象原理锚定在具体报错和可视化反馈上,让转行者、产线工程师与自学学生能在单卡12分钟内亲手训练并部署一个有呼吸的AI模

weixin_30561425的博客 586

别再手动算了!用Excel函数一键搞定AQI和首要污染物分析(附完整公式模板)

本文介绍如何利用Excel函数自动化计算AQI和首要污染物分析,大幅提升数据处理效率。通过构建标准化输入模板、智能计算IAQI、自动判定AQI与首要污染物,并生成可视化仪表盘,帮助环保工作者快速完成每日监测报告。

weixin_30443075的博客 349

Java 开发 修改【冒险岛 079 私服】完整学习流程

第 1-2 天:环境搭建 + 运行原版 079 服务端,能正常登录游戏;第 3-4 天:纯配置文件修改,掌握倍率、属性、怪物、道具的修改,改出第一个「百倍经验私服」;第 5-10 天:Java 代码基础修改,掌握 Player/Skill/Monster 核心类的修改,实现技能无冷却、一刀秒怪、升级满属性;第 11-20 天:Java 代码进阶修改,掌握业务逻辑修改,实现死亡不掉经验、自动捡物、装备强化无失败;第 21-30 天。

萧曳丶 3955

Keras构建CNN讲解及代码

Keras构建CNN 摘要:keras能够极其简单的构造出CNN网络 使用TensorFlow创建卷积神经网络(CNN)来对MNIST手写数字数据集进行分类的方法很经典。TensorFlow是一款精湛的工具,具有强大的功能和灵活性。然而,对于快速原型制作工作,可能显得有些麻烦。Keras是一个运行在TensorFlow或者Theano的更高级别的库,旨在流线化构建深度学习网络的过程。事实上,在Te...

NotPerfect的博客 1万+

【STK】手把手教你利用STK进行光电红外仿真04-STK/EOIR模块的实战操作1航天器星载相机对LEO卫星成像

今天引入一个实际的场景,帮助大家完成对于这个模块的理解与运用。

weixin_44184852的博客 2421

深度学习 | CNN原理及Keras实现

CNN原理及Keras实现1 前言2 什么叫卷积神经网络?2.1 应用场景2.2 CNN的网络结构2.2.1 卷积层2.2.2 池化层2.2.3 Flatten层 & Fully Connected Layer2.3 其余的问题3 keras简单介绍及实现简单三层神经网络3.1 导入相关的库3.2 读入数据3.3 搭建网络3.4 编译3.5 拟合模型3.6 绘制损失函数曲线图3.7 预测4...

RUC_Lee的博客 9453

Quartus II编译时出现Error (119013): Current license file does not support the EP4CE6E22C6 device

Quartus II编译时出现Error (119013): Current license file does not support the EP4CE6E22C6 device, Quartus的安装过程不同于ISE/vivado的安装。“Current license file does not support”这种情况多出现在高版本的quartus中综合很久以前的代码,使用很早型号的FPGA或是CPLD。对于这种情况,就得在官网或是其他网站上下载包含所需Device的库文件。

夜半少年的博客 1万+

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

基于Tensorflow和Keras实现卷积神经网络CNN

文章目录一、环境的配置二、神经网络CNN的介绍三、数据集的准备四、猫狗分类的实例五、参考资料 一、环境的配置 安装Anaconda 详细步骤请参考下面链接: 配置TensorFlow、Keras ①创建一个新的 二、神经网络CNN的介绍 三、数据集的准备 四、猫狗分类的实例 五、参考资料 ...

Harriet的博客 6542

深度学习工具包 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")

上一篇: TensorFlow【极简】CNN
下一篇: Keras【极简】RNN
小基基o_O
博客等级 码龄9年 4414粉丝 467原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

打赏作者

小基基o_O

您的鼓励是我创作的巨大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值
⌂ 换网址