C#委托介绍(delegate、Action、Func、predicate)(一)

C#中的委托(Delegate)和事件 (Event)详解与使用范例 阅读详情

委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递。事件是一种特殊的委托。

  1.委托的声明

  (1). delegate

        delegate我们常用到的一种声明

    Delegate至少0个参数,至多32个参数,可以无返回值,也可以指定返回值类型。

    例:public delegate int MethodtDelegate(int x, int y);表示有两个参数,并返回int型。

  (2). Action

       Action是无返回值的泛型委托。

   Action 表示无参,无返回值的委托

   Action<int,string> 表示有传入参数int,string无返回值的委托

   Action<int,string,bool> 表示有传入参数int,string,bool无返回值的委托

       Action<int,int,int,int> 表示有传入4个int型参数,无返回值的委托

   Action至少0个参数,至多16个参数,无返回值。

   例:

        public void Test<T>(Action<T> action,T p)
        {
            action(p);
        }

    (3). Func

   Func是有返回值的泛型委托

   Func<int> 表示无参,返回值为int的委托

   Func<object,string,int> 表示传入参数为object, string 返回值为int的委托

   Func<object,string,int> 表示传入参数为object, string 返回值为int的委托

   Func<T1,T2,,T3,int> 表示传入参数为T1,T2,,T3(泛型)返回值为int的委托

   Func至少0个参数,至多16个参数,根据返回值泛型返回。必须有返回值,不可void

      例:   

        public int Test<T1,T2>(Func<T1,T2,int>func,T1 a,T2 b)
        {
            return func(a, b);
        }

    (4) .predicate

   predicate 是返回bool型的泛型委托

   predicate<int> 表示传入参数为int 返回bool的委托

   Predicate有且只有一个参数,返回值固定为bool

   例:public delegate bool Predicate<T> (T obj)

  

  2.委托的使用

  (1).Delegate的使用  

复制代码
        public delegate int MethodDelegate(int x, int y);
        private static MethodDelegate method;
        static void Main(string[] args)
        {
            method = new MethodDelegate(Add);
            Console.WriteLine(method(10,20));
            Console.ReadKey();
        }

        private static int Add(int x, int y)
        {
            return x + y;
        }
复制代码

  (2).Action的使用   

复制代码
 static void Main(string[] args)
        {
            Test<string>(Action,"Hello World!");
            Test<int>(Action, 1000);
            Test<string>(p => { Console.WriteLine("{0}", p); }, "Hello World");//使用Lambda表达式定义委托
            Console.ReadKey();
        }
        public static void Test<T>(Action<T> action, T p)
        {
            action(p);
        }
        private static void Action(string s)
        {
            Console.WriteLine(s);
        }
        private static void Action(int s)
        {
            Console.WriteLine(s);
        }
复制代码

  可以使用 Action<T1, T2, T3, T4> 委托以参数形式传递方法,而不用显式声明自定义的委托。 封装的方法必须与此委托定义的方法签名相对应。 也就是说,封装的方法必须具有四个均通过值传递给它的参数,并且不能返回值。 (在 C# 中,该方法必须返回 void)通常,这种方法用于执行某个操作。

  (3).Func的使用

复制代码
        static void Main(string[] args)
        {
            Console.WriteLine(Test<int,int>(Fun,100,200));
            Console.ReadKey();
        }
        public static int Test<T1, T2>(Func<T1, T2, int> func, T1 a, T2 b)
        {
            return func(a, b);
        }
        private static int Fun(int a, int b)
        {
            return a + b;
        }
复制代码

  (4). predicate的使用

  泛型委托:表示定义一组条件并确定指定对象是否符合这些条件的方法。此委托由 Array 和 List 类的几种方法使用,用于在集合中搜索元素。

复制代码
        static void Main(string[] args)
        {
            Point[] points = { new Point(100, 200), 
            new Point(150, 250), new Point(250, 375), 
            new Point(275, 395), new Point(295, 450) };
            Point first = Array.Find(points, ProductGT10);
            Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
            Console.ReadKey();
        }
        private static bool ProductGT10(Point p)
        {
            if (p.X * p.Y > 100000)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
复制代码

  使用带有 Array.Find 方法的 Predicate 委托搜索 Point 结构的数组。如果 X 和 Y 字段的乘积大于 100,000,此委托表示的方法 ProductGT10 将返回 true。Find 方法为数组的每个元素调用此委托,在符合测试条件的第一个点处停止。

  3.委托的清空

  (1).在类中申明清空委托方法,依次循环去除委托引用。

         方法如下:

复制代码
      public MethodDelegate OnDelegate;                
        public void ClearDelegate()        
        {             
            while (this.OnDelegate != null) 
            {                 
                this.OnDelegate -= this.OnDelegate;  
            }        
        } 
复制代码

  (2).如果在类中没有申明清空委托的方法,我们可以利用GetInvocationList查询出委托引用,然后进行去除。  

  方法如下:

复制代码
        public MethodDelegate OnDelegate; 
     static void Main(string[] args)
        {
            Program test = new Program();

            if (test.OnDelegate != null) 
            { 
                System.Delegate[] dels = test.OnDelegate.GetInvocationList(); 
                for (int i = 0; i < dels.Length; i++) 
                {
                    test.OnDelegate -= dels[i] as MethodDelegate;
                }
            }
        }
复制代码

  4.委托的特点

  委托类似于 C++ 函数指针,但它们是类型安全的。
  委托允许将方法作为参数进行传递。
  委托可用于定义回调方法。
  委托可以链接在一起;例如,可以对一个事件调用多个方法。
  方法不必与委托签名完全匹配。

  5.总结:

    Delegate至少0个参数,至多32个参数,可以无返回值,也可以指定返回值类型

  Func可以接受0个至16个传入参数,必须具有返回值

  Action可以接受0个至16个传入参数,无返回值

  Predicate只能接受一个传入参数,返回值为bool类型 


  详细参考:http://www.fengfly.com/plus/view-209140-1.html

       http://www.cnblogs.com/foolishfox/archive/2010/09/16/1827964.html

附:

Event & Delegate

An Event declaration adds a layer of abstraction and protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.

Delegate对应到设计模式中的代理模式,而event则对应到观察者模式。

  1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:   
   6:  namespace ConsoleApplication1
   7:  {
   8:      class Program
   9:      {
  10:          public class Test
  11:          {
  12:              public delegate void WriteName(string name);  //定义委托
  13:              public static event WriteName WriteNameEvent; //定义事件
  14:          }
  15:   
  16:          static Action<string> WriteNameAction;//Action是参数从0到4,返回类型为void(即没有返回值)的委托
  17:          static Func<string, int> WriteNameFunction;//Func的参数从1到5个,有返回值的委托,最后一个是返回类型
  18:         
  19:          static void Main(string[] args)
  20:          {
  21:              Test.WriteName myDelegate = x => { Console.WriteLine("abc,{0}!", x); }; // 使用 Lambda 表达式
  22:              myDelegate("teststring");
  23:   
  24:              Test.WriteName w = (string name) => { Console.WriteLine("Hello,{0}!", name); };//使用匿名委托
  25:              w("Jimmy");
  26:   
  27:              Test.WriteNameEvent += (string name) => { Console.WriteLine("Hello,{0}!", name); };//使用匿名委托
  28:              Test.WriteNameEvent += delegate(string name) { Console.Write("test"); }; //使用匿名方法(.net 2.0)
  29:   
  30:              WriteNameAction = HelloWrite; // 匿名委托,和这个一样:WriteNameAction = new Action<string>(HelloWrite);
  31:              WriteNameAction("test");
  32:   
  33:              WriteNameAction = (string name) => { Console.WriteLine("hello,{0}!", name); };//使用匿名委托
  34:              WriteNameAction("test2");
  35:   
  36:   
  37:              WriteNameFunction = HelloWrite2; // 匿名委托,和这个一样:WriteNameFunction = new Func<string, int>(HelloWrite2);
  38:              Console.WriteLine(WriteNameFunction("test3"));
  39:   
  40:              Predicate<int[]> preTest = i => i.Length == 10;
  41:   
  42:              Console.Read();
  43:   
  44:          }
  45:   
  46:          static List<String> listString = new List<String>()
  47:          {
  48:              "One","Two","Three","Four","Fice","Six","Seven","Eight","Nine","Ten"
  49:          };
  50:   
  51:          static List<String> GetFirstStringFromList()
  52:          {
  53:              string str = GetStringList(a => { return a.Length <= 3 && a.Contains('S'); });// 使用 Predicate 泛型委托
  54:   
  55:              return listString.FindAll((c) => { return c.Length <= 3; });// 使用 Predicate 泛型委托
  56:          }
  57:   
  58:          static String GetStringList(Predicate<String> p) // 使用 Predicate 泛型委托
  59:          {
  60:              foreach (string item in listString)
  61:              {
  62:                  if (p(item))
  63:                      return item;
  64:              }
  65:              return null;
  66:          }
  67:   
  68:          static void HelloWrite(string name)
  69:          {
  70:              Console.WriteLine("Hello world,{0}!", name);
  71:          }
  72:   
  73:          static int HelloWrite2(string name)
  74:          {
  75:              Console.WriteLine("Hello world,{0}!", name);
  76:              return 1;
  77:          }
  78:      }
  79:  }

  • delegate example

使用delegate的目的是在方法中传递方法指针。通过声明delegate的方法签名,可以在运行时在符合delegate方法签名的方法中选择要执行的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ModernLanguageConstructs
{
    class Program
    {
        // Part 1 - Explicit declaration of a delegate 
        //(helps a compiler ensure type safety)
        public delegate double delegateConvertTemperature(double sourceTemp);

        // A sample class to play with
        class TemperatureConverterImp
        {
            // Part 2 - Will be attached to a delegate later in the code
            public double ConvertToFahrenheit(double celsius)
            {
                return (celsius * 9.0/5.0) + 32.0;
            }

            //  Part 3 - Will be attached to a delegate later in the code
            public double ConvertToCelsius(double fahrenheit)
            {
                return (fahrenheit - 32.0) * 5.0 / 9.0;
            }
        }


        static void Main(string[] args)
        {
            //  Part 4 - Instantiate the main object
            TemperatureConverterImp obj = new TemperatureConverterImp();

            //  Part 5 - Intantiate delegate #1
            delegateConvertTemperature delConvertToFahrenheit =
                         new delegateConvertTemperature(obj.ConvertToFahrenheit);

            //  Part 6 - Intantiate delegate #2
            delegateConvertTemperature delConvertToCelsius =
                         new delegateConvertTemperature(obj.ConvertToCelsius);

            // Use delegates to accomplish work

            //  Part 7 - delegate #1
            double celsius = 0.0;
            double fahrenheit = delConvertToFahrenheit(celsius);
            string msg1 = string.Format("Celsius = {0}, Fahrenheit = {1}",
                                         celsius, fahrenheit);
            Console.WriteLine(msg1);

            //  Part 8 - delegate #2
            fahrenheit = 212.0;
            celsius = delConvertToCelsius(fahrenheit);
            string msg2 = string.Format("Celsius = {0}, Fahrenheit = {1}",
                                         celsius, fahrenheit);
            Console.WriteLine(msg2);
        }
    }
}

  • Event example
    Event是一种特殊类型的delegate,使用Event可以很方便的实现观察者模式。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class SampleEventArgs
{
    public SampleEventArgs(string s) { Text = s; }
    public String Text {get; private set;} // readonly
}
public class Publisher
{
    // Declare the delegate (if using non-generic pattern).
    public delegate void SampleEventHandler(object sender, SampleEventArgs e);

    // Declare the event.
    public event SampleEventHandler SampleEvent;

    // Wrap the event in a protected virtual method
    // to enable derived classes to raise the event.
    protected virtual void RaiseSampleEvent()
    {
        // Raise the event by using the () operator.
        if (SampleEvent != null)
            SampleEvent(this, new SampleEventArgs("Hello"));
    }
}
  • Action example
    Action是一种语法糖,它是一种不需要提前声明的delegate,使得delegate的使用更加方便,局限性就是不能定义返回值。(Func<> Delegates是一种可以定义返回值的语法糖)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ModernLanguageConstructs
{
    class Program
    {
        static void Main(string[] args)
        {
            // Part 1 - First action that takes an int and converts it to hex
            Action<int> displayHex = delegate(int intValue)
            {
                Console.WriteLine(intValue.ToString("X"));
            };

            // Part 2 - Second action that takes a hex string and 
            // converts it to an int
            Action<string> displayInteger = delegate(string hexValue)
            {
                Console.WriteLine(int.Parse(hexValue,
                    System.Globalization.NumberStyles.HexNumber));
            };

            // Part 3 - exercise Action methods
            displayHex(16);
            displayInteger("10");
        }
    }
}


What are the differences between delegates and events?

An  Event  declaration adds a layer of abstraction and protection on the  delegate  instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.

If course, this protection layer also prevents "clients" (code outside the defining class/struct) from invokingthe delegate, and from obtaining in any way the delegate object "behind" the event.


来源:

http://ariequ.github.io/blog/2014/09/19/delegate-event-action/

http://www.cnblogs.com/mainz/archive/2011/03/11/1981201.html

http://www.cnblogs.com/akwwl/p/3232679.html 

C#学习笔记(十三)委托——一切皆地址 委托(delegate)是函数指针的“升级版”。C/C++中的函数指针。 C语言中的函数指针: #include<stdio.h> // 声明函数指针,定义为一种数据类型。 typedef int (*Calc)(int a, int b); int Add(int a, int b) { int result = a + b; return result; } int Sub(int a, int b) { int result = a - b; return resu 阅读详情

相关推荐

Delegate与Action,建议先看为敬

背景 很多C#初学者,都遇到过这样的问题,今天就这个问题,进行分析。 根源 先说下这个问题产生的根源,大家都知道,程序运行起来之后,首先会有一个主线程,主线程用于处理控件生成、界面渲染、事件响应等操作,因此我们可以理解为窗体里的控件是属于主线程的。 如果我们想实现与主线程同时执行另一件事,一般会去使用多线程,因此多线程,从某种意义上来说,它和主线程的身份是平等的,就像你和你的同事的关系一样,你们是平级的关系。如果你同事有一天想从你手上把你的项目程序拿过去,你愿不愿意? 所以,如果在多线程里

xiketangAndy的博客 1119

C#代理机制(3):Predicate

Predicate 是.NET类库从3.0开始新增的内置委托,用于实现返回类型为bool型的函数的调用。以下示例定义了一个Predicate,在使用已经有函数 IsAdult(int) 赋值后,再进行调用。 public override void Test() { Predicate<int> fun = Show; if(!fun(20)) { Console.Writ...

郝伟老师的博客——大数据、并行计算与人工智能时代 3645

STM32F103+W5500网络通信

STM32F103+W5500网络通信一、W5500模块(一)W5500以太网模块介绍(二)模块排针功能表二、 modbus协议(一)modbus协议原理(二)Modbus 通讯方式1.Modbus三种通讯方式2.在Modbus网络上传输3.以太网(modbus tcp/ip)三、参考资料 一、W5500模块 (一)W5500以太网模块介绍 D-W5500 EVB以太网模块是一款基于WIZnet W5500芯片的以太网模块,且性价比高的以太网模块。W5500是一款全硬件TCP/IP嵌入式以太网控制器,为

”一只特立独行的猪“的博客 1万+

C# Predicate

一、Predicate是什么?(注:以下摘自C#技术文档)            摘要:表示定义一组条件并确定指定对象是否符合这些条件的方法。            public delegate bool Predicate(T obj)。            参数:obj:要按照由此委托表示的方法中定义的条件进行比较的对象。            类型参数:T:要比较的对象的

ilipan的专栏 1万+

RM机器人麦轮底盘实战:从零搭建到PID调参全记录(附避坑指南)

本文详细记录了RM机器人麦轮底盘从零搭建到PID调参的全过程,涵盖硬件组装、开发环境搭建、底盘解算和PID调参等关键步骤,并附有实用的避坑指南。特别针对麦轮控制、底盘解算和电机调试等核心问题提供了专业解决方案,帮助开发者快速提升机器人性能。

bush的博客 372

2021年J题:基于STM32F103的周期信号波形识别与参数测量系统设计(立创EDA+SZPT_ZXL)

本文详细复盘了2021年全国大学生电子设计竞赛J题获奖项目,手把手教你如何基于STM32F103微控制器设计并实现周期信号波形识别与参数测量系统。文章深入剖析了硬件电路设计(包括程控放大、工作点抬升与滞回比较器)与核心软件算法(如动态采样、FFT频谱分析与波形识别逻辑),并分享了DMA传输、FFT库使用等实战要点与避坑指南,为嵌入式信号处理与电赛备赛提供了宝贵经验。

weixin_32673065的博客 230

C#委托的介绍(delegate、Action、Func、predicate)

委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递。事件是一种特殊的委托。   1.委托的声明   (1). delegate         delegate我们常用到的一种声明     Delegate至少0个参数,至多32个参数,可以无返回值,也可以指定返回值类型。     例:public delegate int MethodtD

believe的专栏 4030

Cursor锁机了怎么办?实测这个开源插件帮你无限“续杯”,附详细安装与防踩坑指南

本文提供了Cursor锁机问题的详细解决方案,包括使用开源插件`cursor-fake-machine`修改机器标识、锁定配置文件权限以及优化使用规范。同时介绍了如何利用Cursor开发油猴脚本将微信公众号文章高效转换为Markdown格式,提升内容创作效率。

weixin_26805597的博客 767

C# 委托的比较 delegate、Action、Func、predicate

一、委托的定义  1、官方定义    委托是一种定义方法签名的类型。当实例化委托时,您可以将其实例与任何具有兼容签名的方法相关联。您可以通过委托实例调用方法。  2、个人理解    委托就是执行方法(函数)的一个类。事件是一种特殊的委托 二、如何申明委托及各种申明的区别  1、使用delegate关键字申明委托,如下:    public delegate int CalcDelega

高级项目经理、专注于技术架构、分享项目管理及职场心得 1426

告别高延迟!用RV1106+4G模块+libdatachannel搭建低功耗WebRTC监控,保姆级避坑指南

本文详细介绍了如何利用RV1106低功耗处理器、4G模块和libdatachannel库构建嵌入式WebRTC监控系统,解决高延迟问题。通过硬件选型、系统优化和核心代码实现,提供了一套完整的低功耗实时视频传输方案,特别适合智能安防和工业物联网应用。

weixin_42527401的博客 192

qcc51xx如何配置spdif输入

qcc51xx如何配置spdif输入。

Alex_886的博客 1373

Unity学习 - C#委托的介绍(delegate、Action、Func、predicate)

 C#委托的介绍(delegate、Action、Func、predicate)   委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递。事件是一种特殊的委托。   1.委托的声明   (1). delegate         delegate我们常用到的一种声明     Delegate至少0个参数,至多32个参数,可以无返回值,也可以指定返回值

sinat_23383269的专栏 2875

同花顺 python量化交易_开启量化第一步!同花顺iFinD数据接口免费版简易操作教程...

来源:雪球App,作者: 同花顺-iFinD,(https://xueqiu.com/6706494343/141951051)金融市场波动频繁,投资往往会夹杂非理性的情绪。而量化交易,旨在以先进的数学模型替代人为的主观判断,利用计算机技术从庞大的历史数据中海选能带来超额收益的多种“大概率”事件以制定策略,辅助投资者进行理性投资。不过计算机分析存在一定的技术门槛,有没有简单易学的量化交易方式,能够...

weixin_35911805的博客 2万+

C#:深入浅出委托(Delegate/Func/Action/Predicate)

深入浅出C#中委托(Delegate/Func/Action)及事件Event,以及一些理解上的误区

龟速船长 859

PCIe 全解析笔记:从协议本质到工程实现

学习 PCIe,最容易陷入的误区是直接跳进协议手册(Base Spec 1300 多页),然后在 TLP 字段、LTSSM 状态、Ordering Rules 中迷失方向。正确的思维路径历史维度:从 PCI 到 PCIe,解决了什么核心矛盾?抽象维度:协议栈分层的真正意图是什么?工程维度:高速串行链路面临哪些物理挑战?协议如何应对?系统维度:作为 CPU 与外设的"动脉",PCIe 如何融入整个计算机体系?带着这四个视角去看每一个细节,知识才能内化为认知。

m0_46644103的博客 261

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

c# 四种委托的区别【delegate 、action、func和predicate 】

c# 四种委托的区别和基础应用。

qq_39024280的博客 4466

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

C#委托的介绍(delegate、Action、Func、predicate)(转)

C#委托的介绍(delegate、Action、Func、predicate)(转) c# 委托 事件 lamda 简写 btnOK.Click += delegate{ MessageBox.Show("OK"); }; btnOK.Click += (sender, e) => { MessageBox.Show("OK"); }; 委托是一个类,它定义了方法的类型,使...

cxu123321的博客 549

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

C#委托(delegate、Action、Func、predicate)和事件

C#委托(delegate、Action、Func、predicate)和事件 一、前言 刚开始工作的时候,觉得委托和事件有些神秘,而当你理解他们之后,也觉得好像没有想象中的那么难。在项目中运用委托和事件,你会发现他非常棒,这篇博文算是自己对委托和事件的一次梳理和总结。 二、委托 C#中的委托,相当于C++中的指针函数...

零一 866

c# 带返回值的action_C#委托的介绍(delegate、Action、Func、predicate)

委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递。事件是一种特殊的委托。1.委托的声明(1). delegatedelegate我们常用到的一种声明Delegate至少0个参数,至多32个参数,可以无返回值,也可以指定返回值类型。例:public delegate int MethodtDelegate(int x, int y);表示有两个参数,并返回int型。(2...

weixin_39949413的博客 475

C#中委托(delegate、Func、Action、precidate)学习笔记

C#中Func和Action的简单使用delegate的简单使用Func声明Func结合Lambda表达式使用结合匿名方法使用Action声明Action结合Lambda表达式使用结合匿名函数使用 通常自定义使用委托是用delegate。Func和Action类是特殊的类型,它们允许程序员在不必指定自定义委托类型的情况下,去使用委托。而通过F12查看函数声明可以发现,Func和Action类本质上也是通过delegate关键字实现的。 Func和Action在使用时非常相似,下面将简单介绍Func和Acti

SQWH_SSGS的博客 1397

C#的委托(Action、Func、delegate、predicate)

委托是什么?如何使用? 委托是一种类,类是数据类型所以委托也是一种数据类型,它的声明方式与一般的类不同,主要是为了照顾可读性和C/C++,委托使用要慎之又慎 C#有已经定义好的两种委托方式,一个是Action,一个是Func,Action是无返回值的,而Func是要求有返回值的,两者都通过泛型定义好了参数类型,上限为16个。详细用法如下代码所示。 此外C#中还有自定义的委托,需要使用delegate关键字来定义 需要注意声明委托的位置,因为委托也是一种类,所以声明位置应当是与命名空间下,与其他类同级

旧时佑忆的空间 905
上一篇: unity3d优化总结篇
下一篇: C#委托介绍(delegate、Action、Func、predicate)(二)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值