你必须懂的.NET中Attribute

Attribute在.net编程中的应用(一) Attribute在.net编程中的应用(一)Attribute的基本概念经常有朋友问,Attribute是什么?它有什么用?好像没有这个东东程序也能运行。实际上在.Net中,Attribute是一个非常重要的组成部分,为了帮助大家理解和掌握Attribute,以及它的使用方法,特地收集了几个Attribute使用的例子,提供给大家参考。在具体的演示之前,我想先大致介绍一下Attribut 阅读详情
        作为一个.NET开发人员,懂Attribute的重要性,用.NET大师Jeffrey Richter的话就是“ 任何.NET Framework 开发人员都有必要对定制attribute有一个牢靠的掌握”,所以掌握Attitude,这是必须的!

  什么是Attribute(特性)?和Property(属性)是什么区别?

  我们来看看MSDN中对特性的描述:

  Attribute 类将预定义的系统信息或用户定义的自定义信息与目标元素相关联。 目标元素可以是程序集、类、构造函数、委托、枚举、事件、字段、接口、方法、可移植可执行文件模块、参数、属性、返回值、结构或其他特性。特性在您编译代码时被发送到元数据中,并可通过运行时反射服务用于公共语言运行时以及任何自定义工具或应用程序。通俗地理解可以这么表述:你可以通过Attribute将一些额外信息加在一些目标元素上(类,字段,接口等),程序编译的时候就将这些额外的信息系列化程序集的元数据中,当你运行程序的时候可以通过反射技术从程序集元数据中读取这些额外信息,并根据这些额外信息决定你程序的行为。

  Attribute和Property有什么区别?其实这个问题是针对中文背景的开发者而言的,因为很多中文译本把Attribute和Property都翻译成属性,在这里为了区分,我们把Attribute翻译为特性,Attribute和Property基本没有什么瓜葛,因为它们是.NET中不同层面的东西,Property就是我们再熟悉不过的定义在类中的属性,它属于面向对象理论范畴,而Attribute是编程语言文法层面的东西,其定义在上面一段已经描述。

  你使用过.NET定义好的Attribute吗?

  在.NET的基础类库中提供了很多定制好的Attribute供开发人员使用,这些定制的Attribute目的的方便开发者在代码中表达他们的意图。如下面三个Attribute类都是C#编译器能够理解的特性类:

  Obsolete:这个属性用来标记不再使用的程序实体(如类或方法),每次使用标记为过时的实体时,会设设定此特性的方法,产生警告或错误。

  Conditional:该特性可以标示出某种环境设置下某个方法是否应该被调用。

  Serializable:指示一个类可以序列化。

  下面以Obsolete特性的使用为例,说明Attribute是如何应用它的目标元素的。

namespace AttributeDemo
{
   
class Program
    {
       
static void Main( string [] args)
        {
            MyClass myclass
= new MyClass();
            myclass.OldMethod();
            Console.ReadKey();
        }
    }

   
public class MyClass
    {
        [Obsolete(
" 这是一个旧的方法,请调用新的方法NewMethod " )]
       
public void OldMethod()
        {
            Console.WriteLine(
" 这是旧方法 " );
        }

       
public void NewMethod()
        {
            Console.WriteLine(
" 这是新方法 " );
        }
    }
}

  调试这段程序的时候会发出警告信息,如下图所示:

       

  像Obsolete这样的定制特性,编译器能够做出相应处理,如在使用标记了Obsolete特性的方法时会发出警告信息,但如果我们自己定制的Attribute时,编译器会做什么处理呢。下面我们自己定义一个Attribute。

  我也来定义一个Attribute

  为了符合“公共语言规范”(CLS),定制Attribute必须直接或间接从公共抽象类System.Attribute派生。所以我们前面提到Obsolete、Conditional和Serializable都是派生于Attribute。这里需要说明下的是自定制的Attribute的命名规范,其规则是“特性名+Attribute”,也就是我们自定制必须以Attribute为后缀,那么我们上面提到的三个特性都没有Attribute为后缀的呢,原来定义它们的时候都是有Attribute后缀的,如Obsolete是ObsoleteAttribute,只是我们将一个特性应用于某个目标元素时可以将Attribute这个后缀去掉,因为编译器会先查找没有Attribute后缀的特性,如果没有找到,则会查找加了Attribute后缀的特性名称。

System.Attribute类的构造器被protected修饰,说明它不能自己实例化,只能被它的派生类调用。它有三个重要的静态方法,如下:

方法名称说明
GetCustomAttributes有多个重载,返回作用于目标的Attribute类实例的数组,也就是返回的类型是Attribute[]
GetCustomAttribute有多个重载,返回作用于目标的Attribute类的一个实例,如果目标没有应用任何的Attribute则返回null,如果目标应用了指定的Attribute的多个实例,就抛出一个System.Reflection.AmbiguousMatchException异常。
IsDefined如果至少有一个指定的Attribute派生类实例作用于目标,就返回true,否则返回false。这个方法效率很高,因为它不构建Attribute的实例,前面的两个方法返回都是Attribute实例,也就是需要从元数据中获取信息来构建实例,耗费性能多

  通常检查一个目标元素是否被应用了某个Attribute时,就调用System.Attribute.IsDefined方法,因为它的性能比GetCustomAttributes和GetCustomAttribute要高,如果需要返回Attribute的实例,则调用GetCustomAttributes或GetCustomAttribute方法。调用这三个方法都会扫描托管模块的元数据(因为Attribute是在编译的时候保存在托管模块的元数据上的),执行字符串比较来定义指定的Attribute类。这样的操作对时间性能消耗大,如果需要反复调用这些方法,可以缓存这些方法的调用结果,也就是把实例保存在全局变量中,不需要每次都扫描和构造实例。

  除了System.Attribute类提供的上面的三个静态方法可以检查目标元素应用Attribute的情况外,System.Reflection命名空间定义的一些类也允许你检查一个模块的元数据的内容,这些类包括Assembly,Module,ParameterInfo,MemberInfo,Type,MethodInfo,ConstrucorInfo,FieldInfo,EventInfo,PropertyInfo等,它们都提供了GetCustomAttributes和IsDefined方法。这些类GetCustomAttributes返回的类型是Object[],而System.Attribute类GetCustomAttributes方法返回的类型是Attribute[]。

下面将分别使用System.Attribute和System.Reflection.Type各自提供的GetCustomAttributes方法获取Attribute实例提供示例代码,以让您有一个更加直观的认识。

定义一个Attribute

public class MyMsgAttribute:Attribute
    {
       
public string Msg { get ; set ; }
       
public MyMsgAttribute( string msg)
        {
            Msg
= msg;
        }
    }

  定义一个类,使自定制的MyMsgAttribute类能够应用在这个类上,如下:

[MyMsgAttribute( " 我的自定义Attribute " )]
   
public class MyClass
    {

    }

  使用System.Reflection.Type提供的GetCustomAttributes方法获取MyMsgAttribute类的实例,代码如下:

var attributes = typeof (MyClass).GetCustomAttributes( typeof (MyMsgAttribute), true );
            MyMsgAttribute myAttribute
= attributes[ 0 ] as MyMsgAttribute;
           
if (myAttribute != null )
            {
                Console.WriteLine(myAttribute.Msg);
            }

  

      使用System.Attribute提供的GetCustomAttributes方法获取MyMsgAttribute类的实例,代码如下:

var attributes2 = Attribute.GetCustomAttributes( typeof (MyClass));
            MyMsgAttribute myAttribute2
= (MyMsgAttribute)attributes2[ 0 ];
            Console.WriteLine(myAttribute2.Msg);

  上面两段代码输出的结果都是Msg是属性值——“我的自定义Attribute”。

  经过上面两段代码的分析,我们已经知道自定义一个Attribute类,并使这个Attribute应用在一个类上,同时在了解了在运行时如何从元数据构造这个Attribute的实例,我们得到Attribute对象,就可以根据这个对象的信息来执行一些逻辑分支代码,上面只是简单地输出Attribute对象Msg属性值,可见,定制Attribute是非常有用的,因为它能在运行时决定我们执行不同的逻辑分支代码。如我们可以通过IsDefined检查一个类是否应用了SerializableAttribute,从而判断这个类是否可以用于系列化操作。

  在我们使用Attribute应用于目标元素的时候,我们会发现一个想象,就是有些Attribute可以应用于类,也可以应用于属性,如SerializableAttribute,而有些Attribute只能应用于方法这个目标元素,如ConditionalAttribute,为什么不同的Attribute会有这种应用目标元素的区别呢?我们查看这两个Attribute的定义,发现它们本身应用了一个Attribute类,这个Attribute类就是AttributeUsage。因为Attribute本身就是一个类,所以它是允许应用其它Attribute类的。而AttributeUsage的目的就是限定你的Attribute 所施加的元素的类型,比如限制你的Attribute能够应用于类还是方法或者属性上。

  AttributeUsage的构造函数有一个参数,这个参数是AttributeTargets的枚举类型。

  AttributeTargets的枚举成员名称说明如下:
  All 可以对任何应用程序元素应用特性。 
  Assembly 可以对程序集应用特性。 
  Class 可以对类应用特性。 
  Constructor 可以对构造函数应用特性。 
  Delegate 可以对委托应用特性。 
  Enum 可以对枚举应用特性。 
  Event 可以对事件应用特性。 
  Field 可以对字段应用特性。 
  GenericParameter 可以对泛型参数应用特性。 
  Interface 可以对接口应用特性。 
  Method 可以对方法应用特性。 
  Module 可以对模块应用特性。 注意Module 指的是可移植的可执行文件(.dll 或 .exe),而非 Visual Basic 标准模块。

  如果你的自定制的Attribute没有显示应用AttributeUsage,编译器会自动给你加上一个默认的AttributeUsage,而这个默认的构造函数参数就是AttributeTargets.All,也就是你的这个自定制Attribute能够应用下面元素类型为Assembly | Module | Class | Struct | Enum | Constructor | Method | Property | Field | Event | Interface | Parameter | Delegate,
ClassMembers = Class | Struct | Enum | Constructor | Method | Property | Field | Event | Delegate | Interface 。

 

  如果你的自定制Attribute只想作用于类和方法,实例代码如下:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
   
public class MyMsgAttribute:Attribute
    {
       
public string Msg { get ; set ; }
       
public MyMsgAttribute( string msg)
        {
            Msg
= msg;
        }
    }

  这样定义的MyMsgAttribute只能应用于类和方法,应用于其它类型的目标元素时编译的时候会报错。

  AttributeUsage类提供了两个公共的属性,AllowMultiple和Inherited。AllowMultiple是使用允许让多个Attribute实例应用在同一个目标元素上,当我们将AttributeUsage应用于自定制Attribute时,可以指定AllowMultiple属性值为True,这样自定制的Attribute就允许将它的多个实例应用于单个目标元素,如果不将AllowMultiple显示设为True,自定制的Attribute只能向一个选定的目标元素应用一次。Inherited属性指定自定制Attribute应用于基类时,是否同时应用于派生类和重写的方法。我们用代码演示AllowMultiple和Inherited的概念:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,AllowMultiple = true ,Inherited = true )]
   
public class MyMsgAttribute:Attribute
    {
       
public string Msg { get ; set ; }
       
public MyMsgAttribute( string msg)
        {
            Msg
= msg;
        }
    }

    [MyMsgAttribute(
" 我的自定义Attribute " )]
    [MyMsgAttribute(
" 也是你的自定义Attribute " )]
   
public class MyClass
    {
      
       
public string Name { get ; set ; }

      
       
public string GetName()
        {
           
return Name;
        }
    }

   
public class YourClass : MyClass
    { }
 
static void Main( string [] args)
        {
           var attributes
= typeof (MyClass).GetCustomAttributes( typeof (MyMsgAttribute), true );
           
foreach (var attribute in attributes)
            {
                MyMsgAttribute myAttribute
= attribute as MyMsgAttribute;
               
if (myAttribute != null )
                {
                    Console.WriteLine(myAttribute.Msg);
                }
            }

             attributes
= typeof (YourClass).GetCustomAttributes( typeof (MyMsgAttribute), true );
           
foreach (var attribute in attributes)
            {
                MyMsgAttribute myAttribute
= attribute as MyMsgAttribute;
               
if (myAttribute != null )
                {
                    Console.WriteLine(myAttribute.Msg);
                }
            }

                       Console.ReadKey();
        }

  输出的结果为:

      

  总结

  我们根据上面文章的分析对自定制Attribute的定义和使用进行总结:

  1、自定制的Attribute必须派生于System.Attribute。

  2、在自定制的Attribute应用AttributeUsageAttribute可以对自定制的Attribute进行应用目标元素、目标元素是否支持应用同一个Attribute多个实例,目标元素应用的Attribute是否能应用于的派生类和派生类的重写方法等进行控制。

  3、自定制的Attribute是在编译时保存在模块的元数据上的,在运行时从元数据读取信息来构建Attribute实例。

  4、获取或判断某个目标元素应用Attribute的信息,可以通过System.Attribute提供的三个镜头方法:System.Attribute.IsDefined,

System.Attribute.GetCustomAttributes和System.Attribute.GetCustomAttribute,也可以通过System.Reflection命名空间定义的一些类来检查一个模块的元数据的内容,这些类包括Assembly,Module,ParameterInfo,MemberInfo,Type,MethodInfo,ConstrucorInfo,FieldInfo,EventInfo,PropertyInfo等,它们都提供了GetCustomAttributes和IsDefined方法。

  

  参考资料:

    Jeffrey Richter CLR Via C#

    微软 MSDN

    dudu Attribute在.net编程中的应用(一)

C# IsDefined的问题 主要介绍了C# IsDefined的问题,通俗易懂,需要的朋友可以参考下。 立即下载

相关推荐

使用C#的Attribute(特性)实现一个简单的ORM

【内容概要】:在C#中通过学习使用Attribute,实现一个简单的ORM框架。里面主要有两部分的内容,学习使用Attribute获得设定值;学习通过反射获取属性的值 【适应人群】:初级工程师。但需要对反射、Attribute有一定的了解 【使用场景及目标】:通过样例,能够更好的理解与掌握Attribute的知识,同时也对一般的ORM框架有个基本的任职 【其他说明】:暂无

【.NET Core】特性(Attribute)详解

公共语言运行时添加类的关键描述性声明(称为特性),以便批注编程元素(如类型、字段、方法和属性)。编译运行时的代码时,它将被转换为中间语言(MSIL),并和编译器生成的元数据一起放置在可移植可执行文件内。特性使得将额外的描述信息放到可使用运行时反射服务提取的元数据中。当你声明派生自的特殊类的实例时,编译器会创建特性。在.NET内置了很多特性,这些特性描述数据序列化、指定用于强制安全性的特性并限制通过实时(JIT)编译器进行优化,来对代码进行调优。应用AttributeUsageAttribute。

记录总结工作过往 3360

Intel Mobileye EyeQ Ultra:RISC-V架构的L4自动驾驶芯片解析

RISC-V作为开源指令集架构,凭借其模块化设计和可定制特性,正在重塑高性能计算领域。其精简指令集带来的确定性执行时序,特别适合自动驾驶等实时性要求严苛的场景。在异构计算架构中,RISC-V与专用加速器(如NPU、GPU)的协同设计,能显著提升能效比和算力密度。Mobileye EyeQ Ultra采用12核RISC-V集群,结合176TOPS AI加速器和5nm工艺,实现了L4级自动驾驶所需的实时感知与决策能力。这种架构为车载计算平台提供了可扩展的解决方案,同时降低了系统复杂度和BOM成本。

weixin_33245447的博客 427

.net高级技术——Attribute

什么是Attribute?Attribute有什么用? Attribute相当于标签,比如说我们在即将拆迁的房子上会画一个拆字,还比如说被查封的公司会有一个封条!这些都是标签。那么在C#中的标签是什么样子的呢? 常见的Attribute有:[Obsolete]、 在使用一些窗体控价的时候可以使用[ReadOnly]、[DisplayName]等等! 以后在很多框架里面还会有很多的Attri...

qq_33407246的博客 1695

从临床试验到互联网AB测试:边缘结构模型(MSM)如何解决‘时依性混杂’这个老大难问题

本文探讨边缘结构模型(MSM)如何解决时依性混杂问题,适用于临床试验和互联网AB测试。通过逆概率加权(IPTW)等方法,MSM能有效剥离混杂效应,准确评估长期干预效果。文章结合跨领域案例,详细解析MSM的核心原理、实施步骤及在推荐算法效果评估中的实战应用,帮助读者掌握这一先进因果推断工具。

weixin_28725949的博客 208

在VScode中配置Python开发环境(详细图片文字结合)

需要用到的软件下载包在官网里找一下,在window下的点击安装就行了;找一个3.8到3.10版本差不多都完善跟的上;

m0_72811193的博客 1599

C# 特性(Attribute)

特性(Attribute)是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。您可以通过使用特性向程序添加声明性信息。 特性使用中括号声明,特性是一个类且必须直接或者间接继承 Attribute。一个声明性标签是通过放置在它所应用的元素前面的方括号([ ])来描述的。

qq_42335551的博客 2688

【实践指南】Wasserstein距离在电力系统鲁棒优化中的核心应用

本文深入探讨了Wasserstein距离在电力系统分布鲁棒优化中的核心应用。针对风电、光伏出力的不确定性,文章阐述了如何利用Wasserstein距离构建模糊集,将复杂的分布鲁棒优化问题转化为可求解的确定性模型,并提供了从理论到代码实现的完整实践指南,有效平衡了系统运行的经济性与鲁棒性。

weixin_29229261的博客 308

Attribute在.net编程中的应用

原文链接 在研究 Silverlight 中的 TypeConverter 时必须要对 Attribute 有所了解,如果你对 .NET 中的 Attribute 了解的比较透彻的话,那么 Silverlight 中的 TypeConverter 也就不难理解了。下面的资料对我的帮助很大:  Attribute 在.NET编程中的应用(一) Attribute 在.NET编程中的应用

jiangxinyu的专栏 990

DAC60501与STM32的I2C通信实战:从寄存器配置到电压输出

本文详细介绍了如何使用STM32通过I2C通信驱动DAC60501数模转换器,实现精确的模拟电压输出。内容涵盖从硬件连接到软件模拟I2C驱动编写,再到DAC寄存器配置与电压计算的全流程实战指南,并提供了关键的驱动实例代码和常见问题调试技巧,帮助开发者快速掌握这一嵌入式开发中的实用技能。

weixin_29197835的博客 369

大数据利器Hadoop:从基础到实战,一篇文章掌握大数据处理精髓!

在当今大数据时代,数据量的爆炸式增长对企业和技术提出了前所未有的挑战。如何高效地存储、处理和分析这些庞大的数据集,成为了亟待解决的问题。Hadoop作为一种分布式计算框架,应运而生,为大数据处理提供了有效的解决方案。Hadoop是一个由Apache软件基金会维护的开源项目,它基于Google的分布式文件系统(Google File System,GFS)和MapReduce计算模型设计。Hadoop的主要目标是处理大规模数据集,它可以在普通硬件集群上运行,从而降低了大数据处理的成本。

邓邓子的博客 8282

Attribute在.net编程中的应用(二)

.NET Framework中对Attribute的支持是一个全新的功能,这种支持来自它的Attribute类。在你的程序中适当地使用这个类,或者是灵活巧妙地利用这个类,将使你的程序获得某种在以往编程中很难做到的能力。我们来看一个例子:假如你是一个项目开发小组中的成员,你想要跟踪项目代码检查的信息,通常你可以把代码的检查信息保存在数据库中以便查询;或者把信息写到代码的注释里面,这样可以阅读代码

动感程序 3456

利用恒源云在云端租用GPU服务器训练YOLOv10模型(包括Linux系统命令讲解)

为当涉及到深度学习的训练任务时,GPU的计算能力是不可或缺的。相对于传统的中央处理器(CPU),图形处理器(GPU)具有更强大的并行计算能力,能够显著加速深度学习模型的训练过程。深度学习算法通常涉及大量的矩阵运算和张量操作,而GPU的并行计算架构使得它们能够高效地执行这些计算,从而加速模型训练的速度。恒源云是一个经济高效的云计算平台,您可以通过恒源云的控制台或者命令行界面来管理实例、上传和下载数据、执行训练任务等。

Snu77的博客 1891

.NET Attribute的自描述机制 一

   Attribute是C#的自描述的基类,用于对appliction element进行描述,比如程序集,类,方法,字段,属性等等。他它与正常定义的类不同,它是在编译时实例化的,普通的类是在运行时实例化。Attribute的派生类也可以应用AttributeUsage类型进行描述,AttributeUsage(AttributeTarget target),其中AttributeTarget target是可选参数,在其中还可以应用命名参数,for example: AttributeUsage(Att

liaoxiaoli99的专栏 1197

【通信原理】基于【MATLAB】的通信OFDM系统仿真

主要进行OFDM系统的仿真,使用MATLAB软件对OFDM系统的接收端和发射端分别进行模拟仿真。

ALi.S的博客 5793

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

.net中的Attribute,C#

本文转载自:http://www.cnblogs.com/zoupeiyang/archive/2011/07/28/2119182.html     作为一个.NET开发人员,懂Attribute重要性,用.NET大师Jeffrey Richter的话就是“任何.NET Framework 开发人员都有必要对定制attribute有一个牢靠的掌握”,所以掌握Attitude,这

鲁信的专栏 5956

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

.NET Attribute在数据校验上的应用

Attribute(特性)的概念不在此赘述了,相信有点.NET基础的开发人员都明白,用过Attribute的人也不在少数,毕竟很多框架都提供自定义的属性,类似于Newtonsoft.JSON中JsonProperty、JsonIgnore等 自定义特性 .NET 框架允许创建自定义特性,用于存储声明性的信息,且可在运行时被检索。该信息根据设计标准和应用程序需要,可与任何目标元素相关。 创建并使用自定义特性包含四个步骤: 声明自定义特性 构建自定义特性 在目标程序元素上应用自定义特性 通过反射访问特性 声明.

深蓝旭的博客 262

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

Attribute的基本概念

经常有朋友问,Attribute是什么?它有什么用?好像没有这个东东程序也能运行。实际上在.Net中,Attribute是一个非常重要的组成部分,为了帮助大家理解和掌握Attribute,以及它的使用方法,特地收集了几个Attribute使用的例子,提供给大家参考。在具体的演示之前,我想先大致介绍一下Attribute。我们知道在类的成员中有property成员,二者在中文中都做属性解释,那么

dshj的专栏 996

Attribute 在.NET编程中的应用(二)

Attribute在.net编程中的应用(二).NET Framework中对Attribute的支持是一个全新的功能,这种支持来自它的Attribute类。在你的程序中适当地使用这个类,或者是灵活巧妙地利用这个类,将使你的程序获得某种在以往编程中很难做到的能力。我们来看一个例子:假如你是一个项目开发小组中的成员,你想要跟踪项目代码检查的信息,通常你可以把代码的检查信息保存在数据库中以便查询;

niwalker的专栏 6235

【VB/.NET】What Is Attribute In .NET?

Attribute的基本概念 经常有朋友问,Attribute是什么?它有什么用?好像没有这个东东程序也能运行。实际上在.Net中,Attribute是一个非常重要的组成部分,为了帮助大家理解和掌握Attribute,以及它的使用方法,特地收集了几个Attribute使用的例子,提供给大家参考。 在具体的演示之前,我想先大致介绍一下Attribute。我们知道在类的成员中有proper

XiaoY 2827
上一篇: 欧几里德算法及其扩展算法
下一篇: C#常用开源项目
jackfirst86
博客等级 码龄18年 28粉丝 27原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值