SML-Abridgelab

最佳路径搜索(二):启发式搜索(代价一致搜索(Dijkstra search),贪心搜索,A*搜索) 启发式搜索(heuristic search) 方法(Dijkstra search,Greedy Search,A* ) 性质(Admissible & Consistent & dominate) 总结 阅读详情

Abridgelab

实验背景

本实验主要研究了割边(桥)的寻找算法(Tarjan)以及A*启发式算法

实验细节

1 Bridges

假设有连通图G,e是其中一条边,如果G-e是不连通的,则边e是图G的一条割割边,即桥。此情形下,G-e必包含两个连通分支。

1.1 makeGraph

 makeGraph : edge seq -> ugraph

 type vertex = int
 type edge = vertex * vertex
 type edges = edge seq

 type ugraph = (vertex seq) seq

函数功能:

将所给的边集(Seq形式存储)转换成无向图(ugraph)

函数思路:

首先通过map将所给边集里的所有边映成无向边,然后通过collect整理即可

函数代码:

  fun cmp (x,y) =
  	if x>y then GREATER
  	else if x<y then LESS
  	else EQUAL

  fun makeGraph (E : edge seq) : ugraph = 
  	if length E = 0 then empty()
  	else 
  	let 
  		val firSeq = append (E,(map (fn (x,y) => (y,x)) E))
  		val secSeq = collect cmp firSeq
  		val res = map (fn (x,y) => y) secSeq
  	in 
  		res
  	end


渐进复杂度分析:

firSeq: W=W(append)+W(map)=O(|E|) S=O(1)

secSeq: W=W(collect)=O(|E|log|E|) S=O(log^2|E|)

res: W=O(|V|) S=O(1)

而|E|<=|V|^2

故W(makeGraph)=O(|E|log|V|) S(makeGraph)=O(log^2|V|)

1.2 findBridges

findBridges : ugraph -> edge seq

函数功能:

求出所给无向图中的桥,即割边

函数思路:

对无向图运用Tarjan算法。即:

声明一个长度为全部点的个数的STSeq,其中每个元素均为三元组(isVisited,dfn,low)

分别表示:

isVisted:该点是否被访问过

dfn:在深度优先搜索中该点被访问的次序

low:深度优先搜索中该点可以往回追溯到的最先被访问的点

例如:

1->2->3->4

那么1,2,3,4的dfn分别为0,1,2,3,low则均为0

而本身点由0~|V|-1的整数表示,所以可以一一对应每个点的信息

初始化STSeq之后从给定点开始深度优先搜索,根据搜索到的点的访问与否可分为如下两种情况(假设某次搜索的边为(u,v)):

(1)v未访问

首先v.dfn以及v.low均为v被访问的次序

其次v.low修改为min(v.low,w.low),w为边(v,w)的终点

(2)v已访问

u.low修改为min(u.low,v.dfn)

注意:由于用(u,v),(v,u)来表示一条无向边,所以需要防止访问过v之后接着访问回u

深搜并修改完每个点的信息之后,对于边(u,v),如果u.dfn<v.low,那么这条边就是一条割边

函数代码:

  fun findBridges (G : ugraph) : edges = 
  	if length G = 0 then empty() 
  	else
  	let
  		val preSTSeq = STSeq.fromSeq (tabulate (fn _ => (false,0,0)) (length G))
  		fun DFS (fp,p) ((X,pre,label),v) = 
  			case (STSeq.nth X v) of 
  				(true,dfn,low) => 
    				if v=fp then (X,pre,label)
    				else (STSeq.update (p,(true,#2 (STSeq.nth X p),min(#3 (STSeq.nth X p),dfn))) X ,pre,label) 
  				|(false,dfn,low) =>
    				let
    					val X' = STSeq.update (v,(true,label+1,label+1)) X
    					val neighbor = nth G v
    					val (X'',pre',label') = iter (DFS (p,v)) (X',pre,label+1) neighbor
    					val X''' = STSeq.update (p,(true,#2 (STSeq.nth X'' p),min(#3 (STSeq.nth X'' p),#3 (STSeq.nth X'' v)))) X''
    					val p' = STSeq.nth X''' p 
    					val v' = STSeq.nth X''' v
    					val pre'' = if #2 p' < #3 v' then append (pre',singleton (p,v)) else pre' 
    				in
    					(X''',pre'',label')
    				end
  			val res = #2 (DFS (0,0) ((preSTSeq,empty(),0),0))
  	in
  		res
  	end

渐进复杂度分析:

由于采用STSeq存储各点信息,故有对其修改的操作均为常数时间

而割边相对于|E|、|V|很小,故每次发现割边的append操作可忽略

那么该算法时间复杂度即为基于STSeq的深度优先搜索的时间复杂度

即W=S= O(|V| + |E|)


2 Paths “R” Us

2.1 Using Dijkstra’s

2.1.1 Give an example of a graph on ≤ 4 vertices with negative edge weights where Dijkstra’s
algorithm fails to find the shortest paths. List the priority queue operations (i.e. insertions and updates
of shortest path lengths) up to the point of failure. Clearly point out where the algorithm has failed and
what it should have done.

(1)0入队,<(0,0)> | <>

(2)0出队,1,2入队,<(2,3),(1,5)> | <(0,0)>

(3)2出队,<(1,5)> | <(0,0),(2,3)>

(4)1出队,<> | <(0,0),(1,5),(2,3)>

(5)所得0->2路径长为3,显然最短路径应为1,故错误

2.1.2 Assuming there are no negative-weight cycles in G, how would you modify Dijkstra’s
to accomodate negative edge weights and return the correct solution?

使用Bellman-ford算法

2.2 The A ∗ Heuristic

2.2.1 Briefly argue why the Euclidean distance heuristic is both admissible and consistent for
edge weights that represent distances between vertices in Euclidean space.

admissible:由于欧式距离即两点之间的直线距离(即最短距离),故满足admissible

consistent:对于两点u,v,h(u)<h(v)+E(u,v)<=h(v)+w(u,v)  故满足consistent

2.2.2 Give a heuristic that causes A ∗ to perform exactly as Dijkstra’s algorithm would.

h为常数即可,例如h(v)=0

2.2.3 Give an example of a weighted graph on ≤ 4 vertices with a heuristic that is admissible
but inconsistent, where the Dijkstra-based A ∗ algorithm fails to find the shortest path from a single source
s to a single target t. Label each vertex with its heuristic value, and clearly mark the vertices s and t. In
2-3 clear sentences, explain why the shortest path is not found (e.g., when does the algorithm fail, what
exactly does it do wrong.)

如图,首先(0,0)入队出队后,(2,8+1),(1,5+5)入队,然后(2,8+1)优先出队,使得0->2的最短路径是(0,2),事

实上最短路径为0->1->2

2.2.4 Give an example of a weighted graph on ≤ 4 vertices with heuristic values that are inadmissible, where

the A ∗ algorithm fails to find the shortest path from a single source to a single target.
Again, clearly label your vertices with heuristic values and explain why the shortest path is not found.

如图,首先(0,0)入队出队后,(2,8+9),(1,5+13)入队,然后(2,8+9)优先出队,使得0->2最短路径为0->2,矛盾。

2.2.5 makeGraph

makeGraph : edge seq -> graph

type graph = (weight Table.table) Table.table

函数功能:

将所给边集转换成邻接表形式

函数思路:

将有向边映成无向边后collect整理即可

函数代码:

  fun makeGraph (E : edge Seq.seq) : graph = 
    let
      val PreL = Seq.map (fn (u,v,w) => (u,Seq.singleton (v,w)) ) E
      val PreR = Seq.map (fn (u,v,w) => (v,Seq.empty ()) ) E
      val Res = Table.collect (Seq.append (PreL,PreR))
    in
      Table.map (fn x => (Table.fromSeq (Seq.flatten x))) Res
    end

渐进复杂度分析:

W= O(|E|log|V|) S=O(log 2 |V|)

2.2.6 findPath

findPath : heuristic -> graph -> (set * set)-> (vertex * real) option

函数功能:

返回所给图中A*启发式算法得出的最短路径

函数思路:

将每次入队的路径长度替换为d(v)+h(v),之后运用Dijkstra算法即可

函数代码:

  fun findPath h G (S, T) = 
    let
      fun AStar (G, u) =
      let
        fun N(v) =
            case Table.find G v
              of NONE => Table.empty ()
               | SOME nbr => nbr

        fun dijkstra' D Q =
            case PQ.deleteMin Q
              of (NONE, _) => D
               | (SOME (d, v), Q') =>
                 case Table.find D v
                   of SOME _ => dijkstra' D Q'
                    | NONE =>
                      let
                        val insert = Table.insert (fn _ => raise SegmentFault)
                        val D' = insert (v, d) D
                        fun relax (q, (u, w)) = PQ.insert (d+w+h(u)-h(v), u) q
                        val Q'' = Table.iter relax Q' (N v)
                      in dijkstra' D' Q''
                      end
      in
        dijkstra' (Table.empty ()) (PQ.singleton (0.0+h(u), u))
      end
      val pre = Seq.flatten (Seq.map (fn x => Table.toSeq (AStar (G,x))) (Set.toSeq S))
      val res = Seq.filter (fn (x,y) => Set.find T x) pre
    in
      if Seq.length res = 0 then NONE
      else
        SOME (Seq.reduce (fn ((a,b),(c,d)) => if b<d then (a,b) else (c,d)) (#1 (Seq.nth res 0),100000.0) res)
    end

渐进复杂度分析:

上述修改仅为替换,相比较Dijkstra算法多了加减运算,故时间复杂度不变









SML实现图像标注/分类 本文分享《信息搜索与人工智能》大作业的实现。 阅读详情

相关推荐

直方图规定化:SML和GML

1.单映射规则(SML) 当采用SML映射时,从原始累计直方图向目标累计直方图进行,分别在每一列中找到最小值第一次出现的数的行号。在目标累计直方图中找到与原始累计直方图第一次出现的差值最小的数的行号。然后将原始直方图中灰度级为该列的像素点映射到该行号上。 2.组映射规则(GML) 当采用GML映射时,从目标累计直方图向原始累计直方图进行,找到最小值第一次出现的列号,目标累计直方图从下一个灰度级开始,在原始累计直方图中找到与第一个该灰度级最接近的值。在原始累计直方图中上一个...

zhangxue1232的博客 1万+

启发函数heuristic 与 A*

consistent heuristic 启发的一致性 admissible heuristic 可接受启发 https://blog.youkuaiyun.com/haolexiao/article/details/70302848 https://www.jianshu.com/p/c728bb269116 https://www.zhihu.com/question/23052955

hxxjxw的博客 2353

sml:机器学习算法(例如,ELM,高斯过程,Boosting)用于事件生存时间的结果

机器学习的生存数据 安装 # Install sml library( devtools ); install_github( ' linxihui/sml ' ); 背景:考克斯比例风险模型 考克斯模型假设比例风险在所有观察结果之间成比例。 在这种假设下,出现了部分可能性,该部分可能性也可以被视为不涉及基线危险函数的概貌和条件可能性,因此感兴趣的参数获得了更大程度的估计自由度。 考克斯偏似的样子 其中$ \ theta_i $通常被称为links或log risk (因为$ \ exp {\ theta_i} $被称为risk )。 在考克斯的模型中 当前实施的算法 高斯过程 高斯过程的回归和分类已被证明是强大的。 但是,R中没有生存扩展。​​但是,通过假设$ \ theta $是从高斯过程(先前)中采样而来的,扩展是非常简单的。 其中$ K =(k_ {ij})= K(x_i

A star算法

A star算法介绍 我们在解空间搜索问题的可行解或者最优解时常用宽度优先搜索(BFS)或者深度优先搜索(DFS),但是有时候会扩展出很多无用节点,搜索时间较长,而A*算法则是选择当前估计成本最低的节点进行扩展,图示如下: g(n)为从起始节点到节点n的成本,h(n)为从节点n到目标点的估计成本 总的成本估计f(n) = g(n) + h(n) 整题实现大概以下几个步骤: 1. 初始

Sundrops的专栏 1万+

C# SECS 通信实例源代码

SECS HSMS, socket create by csharp , easy to use or reference resources

图像直方图的规定化处理(SML算法)

图像直方图的规定化处理(SML算法),和大家分享一下。

有监督的多类标注(SML)的原理及matlab实现

注:本文基于北邮Web搜索课程大作业。作业题目为:任选某类图像为训练样本,编程实现其基于SML算法的类模型。 有监督的多类标注(Supervised Multiclass Labeling,SML)是一种结合有监督的二类标注和无监督的多类标注优点的图像文本标注算法。 一、基本原理 其总体方案为:将图像简单地表示为各局部特征向量的“口袋”式集合,以此估计每幅图像的混合概率密度(GMM)。将

vivian_ll的博客 7847

sml-interface-gen:从XML或JSON生成TS接口

从JSON或XML生成接口 这个工具是在工作时制作的,因为XSplit核心返回的通常格式是XML,而在XJS上工作时,我必须为其创建适当的类型/接口。

Programming Languages PartA Week2学习笔记——SML基本语法

Programming Languages PartA Week2学习笔记——SML基本语法 首先简单介绍使用的SML语言,参考维基百科: ML(Meta Language:元语言),是一个函数式、指令式的通用的编程语言,它著称于使用了多态的Hindley–Milner类型推论。ML能自动的指定多数表达式的类型,不要求显式的类型标注,而且能够确保类型安全,已经正式证明了有良好类型的ML程序不会导致运行时间类型错误。 ML提供了对函数实际参数的模式匹配、垃圾回收、指令式编程、传值调用和柯里化。它被大量的

df1445的博客 3022

SML教程.doc

天语T91线刷就钻教程,可以下载查看!谢谢!

解决 Clawdbot 对接 Minimax 出现 401 (Token is unusable) 的问题排查与修复

即便确认 API Key 有效且余额充足,该问题仍可能在 Clawdbot 中持续出现,而在其他工具(如 curl 或 Postman)中测试正常。

hampeter的博客 3075

C# XML添加属性和节点

XmlDocument XmlDoc = new XmlDocument(); XmlDoc.Load("DBConfig.xml"); XmlNode root = XmlDoc.SelectSingleNode("Config"); XmlElement db = XmlDoc.CreateElement("DB");

@ 2534

淘晶驰串口屏自定义协议实战:5分钟搞定苹果时钟通信(附完整代码)

本文详细介绍了如何使用淘晶驰串口屏自定义通信协议快速实现苹果风格时钟的通信功能。通过精简的协议设计和完整的代码示例,开发者可以在5分钟内完成从硬件连接到软件实现的整个过程,适用于嵌入式开发中的高效通信需求。

weixin_29184371的博客 323

c#新手必看

1.decimal适用于钱财货币运算 2.@无视后面的\n之类的符号 3.const后面跟上类型声明常量            /1常量不能再次赋值 4.a+=100//等于a=a+100..... 5.checked可以检查算术运算 6.continue是跳出本圈循环,而break是跳出本次循环. 7.枚举定义一种数据的类型 8.*c#和C语言的结构体定义不一样,要加上public. 9.与C语...

大白豚 369

光伏发电系统模拟及其发电预测开源python工具pvlib

本文介绍光伏发电系统模拟及其发电预测开源python工具pvlib,以及举例介绍获取辐照度方法、光伏发电预测思路。

肖永威的专栏 1万+

转录组分析中的Fastp和FastQC:如何快速检测数据质量并优化流程

本文深入探讨了转录组分析中数据质量控制的核心流程,重点介绍了Fastp和FastQC两款工具的组合应用。FastQC负责对原始测序数据进行全面质量评估,生成可视化报告;Fastp则能一站式完成接头切除、低质量序列过滤、长度筛选等关键质控步骤。文章提供了详细的参数解读、实战脚本和自动化流程构建指南,帮助研究人员快速检测数据质量并优化预处理流程,为下游的差异表达等分析奠定可靠基础。

weixin_28452161的博客 181

SML-Rangelab

Rangelab 实验背景 为实现范围查找,设计orderTable数据结构,本实验实现了一些基本的接口,并实现一定条件下的Rane query 实验细节 1 Ordered Tables 思路:

Numlogn的博客 716

1.4 你绝对不能错过的天气查询工具:MCP 标准化接入实战

本文介绍了如何构建一个符合MCP标准的天气查询服务。通过FastMCP框架集成OpenWeatherMap API,实现实时天气、天气预报和历史天气查询功能。文章详细展示了从环境准备、插件设计到控制器实现的完整流程,包括如何定义工具函数、配置路由和中间件。同时讲解了如何将MCP服务封装为LangChain工具并与DeepSeek等大模型集成,还涵盖了缓存、限流等高级特性。该示例演示了如何将任意API标准化为MCP服务,为Agent应用提供统一接口。

yonggeit的博客 3047

C#命名空间详解

Microsoft.Csharp包含支持用C#语言进行编译的代码 Microsoft.Jscript包含支持用Jscript语言进行殡仪和代码生成的Jscript运行库和类 Microsoft.VisualBasic包含Visual Basic.NET运行库。此运行库于Visual Basic.NET语言一起使用。此命名空间包含支持Visual Basic.NET语言进行编译和代码生成类。

IDLlanguage的专栏 1191

YOLOv11改进 - C3k2融合 | C3k2融合融合WDBB宽度多样分支模块(Width Diverse Branch Block)通过多尺度分支增强特征表征能力

本文着眼于灰度图像目标检测所面临的挑战,提出了增强型目标检测网络 YOLO - MIF,该网络整合了多种多信息融合策略以对 YOLOv8 网络进行改进。文章开篇介绍了一种可创建伪多通道灰度图像的技术,此技术能增加网络的通道信息,同时缓解潜在的图像噪声与虚焦模糊问题。随后运用网络结构重新参数化技术,在不增加推断时间的情况下提升网络的检测性能。此外,引入了一种新颖的解耦式检测头,增强了模型处理灰度图像时的表现能力。

魔改工程师的博客 770

不藏了!Wireshark 命令、捕获、过滤器大全分享给你

Wireshark,这款广受欢迎的开源网络协议分析工具,堪称网络管理员、网络安全专家和网络爱好者的“显微镜”!它可以帮助我们捕获网络中的数据包,并提供详细的解码和分析能力。本文将为您全面剖析 Wireshark 的强大功能,从基础到高级,让你快速掌握这个神器!💡Wireshark 是一款功能强大的网络协议分析器,最早由 Gerald Combs 于 1998 年开发,经过多年发展,已成为网络诊断和分析的首选工具。

网络技术联盟站 727

隐语实训09-SML入门基于SPU迁移机器学习算法实践

32位浮点数(Single Precision Floating Point)是一种用于表示实数的标准格式,由IEEE 754标准定义。8位定点数常用于嵌入式系统、DSP(数字信号处理)和物联网设备中,这些场景对计算资源和存储空间要求严格,且数值范围和精度需求较低。8位定点数(Fixed Point)是一种用于表示小范围数值的表示方法,适用于嵌入式系统和资源受限的环境。32位浮点数广泛用于科学计算、图形处理、机器学习等需要高精度和大范围数值表示的领域。任务时间上快了一些,通信没什么变化,还是有一定效果的。

sunxi1900的博客 1945

PCL 计算点云AABB包围盒的体积【2026最新版】

AABB包围盒又称了 轴对齐包围盒,是点云包围盒里最简单的一种,其计算方法也极其简单。获取包围盒之后,根据包围盒的长宽高进行体积计算即可!博客长期更新,本文最近一次更新时间为:2026年5月3日。

点云侠的博客 2295

C#配置文件解析工具的实现

相对于java开发者来说,VS的开发者不知幸福多少倍。但是,幸福的另一方面是,我们很少能够了解底层的技术,更多的是跟随者微软的技术走。开源的框架,少之甚少。最近,我研究了.Net Framework中的配置文件管理部分技术,结合实际的应用,重写了相关的类,实现SQL语句、消息的XML配置管理。 配置管理单独工程代码及应用程序中的使用方法代码的下载地址是:http://download.csdn.

AttaGain的专栏 2446

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

整数高精度运算的库(加法,减法,乘法,除法,取模)

这几天开始做些ACM的Online Judge题目,遇到了个数据范围有10^100的题目,原题 是求两个整数的最小公倍数,没用高精写好算法后发现需要的运算类型比较多,基本除了加法没用到其他的都要,于是乎决定写这么个库,也能方便以后刷刷水题,^_^。 这是前面

hiiiiiu 2954

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

A*算法

如此好贴,不能不转!原文地址:http://dev.gameres.com/Program/Abstract/Arithmetic/AmitAStar.mht 本文版权归原作者、译者所有,我只是转贴;如果侵害到您的权益,请联系我,我将删除本文。 基本上,这文章可以说是最佳A*

6449

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

上一篇: SML-Rangelab
下一篇: SML-Segmentlab
Numlogn
博客等级 码龄10年 1粉丝 17原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值