温故知新ASP.NET 2.0(C#)(8) - DataSourceControl(数据源控件)

AccessDataSource的使用,一行代码实现增删改 以下以AccessDataSource为例,你只要写一行代码,便实现一个增删查改的页面。 一、我们先建立这个解决方案,使用Access做数据库。 二、看一下数据库表吧 我们的任务便是对这个Test表里面的数据进行增删查改。 三、在页面上拖入如下图的控件,意思很明显。 id是自增类型,time则自动获取时间,所以只需要录入title和content两个字段的内容,下 阅读详情
[索引页]
[源码下载]



温故知新ASP.NET 2.0(C#)(8) - DataSourceControl(数据源控件)


作者: webabcd


介绍
在 ASP.NET 2.0 中有几个新的数据源控件,例如,SqlDataSource、ObjectDataSource、XmlDataSource、AccessDataSource 和 SiteMapDataSource。它们全都可以用来从它们各自类型的数据源中检索数据,并且可以绑定到各种数据绑定控件。数据源控件减少了为检索和绑定数据甚至对数据进行排序、分页或编辑而需要编写的自定义代码的数量。

其中 ObjectDataSource 控件可针对各种基础数据存储区(如 SQL 数据库或 XML)启用声明性数据绑定模型。因为页开发人员也常常将数据检索(也可能包含业务逻辑)封装在一个组件对象中,从而在呈现页和数据提供程序之间引入另一个层。ObjectDataSource 控件允许开发人员使用此传统的三层结构构造应用程序,同时仍然能够利用 ASP.NET 中的声明性数据绑定模型的易用性优点。


关键
1、在数据层创建 强类型的DataSet和TableAdapter,TableAdapter查询可以使用现有的存储过程。注:直接把表或存储过程拖进来会自动创建TableAdapter

2、中间层的类用[System.ComponentModel.DataObject]声明为数据组件,CRUD方法分别对应[DataObjectMethod(DataObjectMethodType.Insert)],[DataObjectMethod(DataObjectMethodType.Select)],[DataObjectMethod(DataObjectMethodType.Update)],[DataObjectMethod(DataObjectMethodType.Delete)]

3、web层使用ObjectDataSource展现数据,ObjectDataSource就相当于一个代理。ObjectDataSource只是查找具有匹配的参数名称的方法,它不会使用参数的 Type 或 Size,而只是对参数的名称进行匹配

4、其它
  ·<asp:Parameter />有ConvertEmptyStringToNull属性,默认是true。另外还有Direction属性
  ·注意<asp:BoundField />的这几个属性NullDisplayText,HtmlEncode,ApplyFormatInEditMode,InsertVisible,DataFormatString,ReadOnly
  ·DataKeyNames有多个值的话用“,”分隔,用<asp:ControlParameter />绑定的话给其加一个“PropertyName”属性,值类似如下“SelectedDataKey.Values[0]”
  ·关于绑定:简单属性<%# custID %>;集合<asp:ListBox id="List1" datasource='<%# myArray %>' runat="server">;表达式<%# ( customer.FirstName + " " + customer.LastName ) %>;方法<%# GetBalance(custID) %> 
  ·<%# Eval("field1") %> 和 <%# Bind("field1") %>,Eval是单向绑定,Bind是双向邦定
  ·<asp:ObjectDataSource />有一个OldValuesParameterFormatString属性一般不用,不过如果要处理乐观并发之类的就会用到。当该属性的值为“original_{0}”的时候“original_参数名”则为初始值
  ·还有一些如编程方式给参数赋值,错误处理,得到返回值之类的请看源码


示例
相关存储过程和数据层略,见源码

单例模式的实现
App_Code/Singleton.cs
using  System;
using  System.Data;
using  System.Configuration;
using  System.Web;
using  System.Web.Security;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.WebControls.WebParts;
using  System.Web.UI.HtmlControls;

/// <summary>
/// Singleton 的摘要说明
/// </summary>

public   class  Singleton < T >  where T :  new ()
{
    
public static T Instance
    
{
        
get { return SingletonCreator.instance; }
    }


    
class SingletonCreator
    
{
        
internal static readonly T instance = new T();
    }

}


中间层代码
App_Code/Test.cs
using  System;
using  System.Data;
using  System.Configuration;
using  System.Web;
using  System.Web.Security;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.WebControls.WebParts;
using  System.Web.UI.HtmlControls;

using  TestDatabaseTableAdapters;
using  System.ComponentModel;

/// <summary>
/// Test 的摘要说明
/// </summary>

[DataObject]
public   class  Test
{
    [DataObjectMethod(DataObjectMethodType.Select, 
true)]
    
public TestDatabase.TestDataTable GetTest()
    
{
        
return Singleton<TestTableAdapter>.Instance.GetTest();
    }


    [DataObjectMethod(DataObjectMethodType.Select, 
false)]
    
public TestDatabase.TestDataTable GetTestById(int id)
    
{
        
return Singleton<TestTableAdapter>.Instance.GetTestById(id);
    }


    [DataObjectMethod(DataObjectMethodType.Insert, 
true)]
    
public int?[] InsertTest(int? parentId, string name, DateTime? publishTime, decimal? price, bool? isGood, out int? minId)
    
{
        
// 仅为说明如何做错误处理
        if (String.IsNullOrEmpty(name))
            
throw new ArgumentException("参数不能是空", "name");

        
int? id = null;
        
int? count = null;
        minId 
= null;

        Singleton
<TestTableAdapter>.Instance.InsertTest(parentId, name, publishTime, price, isGood, ref id, ref count, ref minId);
        
return new int?[] { id, count };
    }


    [DataObjectMethod(DataObjectMethodType.Delete, 
true)]
    
public int? DeleteTest(int id)
    
{
        
int? rowAffected;

        rowAffected 
= Singleton<TestTableAdapter>.Instance.DeleteTest(id);
        
return rowAffected;
    }


    [DataObjectMethod(DataObjectMethodType.Update, 
true)]
    
public int? UpdateTest(int? id, int? parentId, string name, DateTime? publishTime, decimal? price, bool? isGood)
    
{
        
int? rowAffected;

        rowAffected 
= Singleton<TestTableAdapter>.Instance.UpdateTest(id, parentId, name, publishTime, price, isGood);
        
return rowAffected;
    }

}


DataSourceControl/Test.aspx
<% @ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Test.aspx.cs"
    Inherits
="DataSourceControl_Test" Title="数据源控件测试" 
%>

< asp:Content  ID ="Content1"  ContentPlaceHolderID ="ContentPlaceHolder1"  runat ="Server" >
    
< p >
        
< asp:Label  ID ="lblMsg"  runat ="server"  ForeColor ="red"   />
    
</ p >
    
< table  cellpadding ="6" >
        
< tr >
            
< td  valign ="top" >
                
< asp:DetailsView  ID ="DetailsView1"  runat ="server"  AllowPaging ="True"  AutoGenerateRows ="False"
                    DataKeyNames
="Id"  DataSourceID ="ObjectDataSource1"  Height ="50px"  Width ="125px"  OnItemInserted ="DetailsView1_ItemInserted" >
                    
< Fields >
                        
< asp:BoundField  DataField ="Id"  HeaderText ="Id"  InsertVisible ="False"  ReadOnly ="True"
                            SortExpression
="Id"   />
                        
< asp:BoundField  DataField ="ParentId"  HeaderText ="ParentId"  SortExpression ="ParentId"   />
                        
< asp:BoundField  DataField ="Name"  HeaderText ="Name"  SortExpression ="Name"   />
                        
< asp:BoundField  DataField ="PublishTime"  HeaderText ="PublishTime"  SortExpression ="PublishTime"
                            InsertVisible
="False"   />
                        
< asp:BoundField  DataField ="Price"  HeaderText ="Price"  SortExpression ="Price"  DataFormatString ="{0:c}"  HtmlEncode ="False"   />
                        
< asp:CheckBoxField  DataField ="IsGood"  HeaderText ="IsGood"  SortExpression ="IsGood"   />
                        
< asp:CommandField  ShowInsertButton ="True"   />
                    
</ Fields >
                
</ asp:DetailsView >
            
</ td >
            
< td  valign ="top" >
                
< asp:DetailsView  ID ="DetailsView2"  runat ="server"  Height ="50px"  Width ="125px"  AutoGenerateRows ="False"  DataKeyNames ="Id"  DataSourceID ="ObjectDataSource2" >
                    
< Fields >
                        
< asp:BoundField  DataField ="Id"  HeaderText ="Id"  InsertVisible ="False"  ReadOnly ="True"
                            SortExpression
="Id"   />
                        
< asp:BoundField  DataField ="ParentId"  HeaderText ="ParentId"  SortExpression ="ParentId"   />
                        
< asp:BoundField  DataField ="Name"  HeaderText ="Name"  SortExpression ="Name"   />
                        
< asp:BoundField  DataField ="PublishTime"  HeaderText ="PublishTime"  SortExpression ="PublishTime"   />
                        
< asp:BoundField  DataField ="Price"  HeaderText ="Price"  SortExpression ="Price"  DataFormatString ="{0:c}"  HtmlEncode ="false"   />
                        
< asp:CheckBoxField  DataField ="IsGood"  HeaderText ="IsGood"  SortExpression ="IsGood"   />
                    
</ Fields >
                
</ asp:DetailsView >
            
</ td >
        
</ tr >
    
</ table >
    
< p >
        
< asp:GridView  ID ="GridView1"  runat ="server"  AutoGenerateColumns ="False"  DataKeyNames ="Id"
            DataSourceID
="ObjectDataSource1"  AllowPaging ="True"  AllowSorting ="True"  OnRowUpdating ="GridView1_RowUpdating" >
            
< Columns >
                
< asp:CommandField  ShowDeleteButton ="True"  ShowEditButton ="True"  ShowSelectButton ="True"   />
                
< asp:BoundField  DataField ="Id"  HeaderText ="Id"  InsertVisible ="False"  ReadOnly ="True"
                    SortExpression
="Id"   />
                
< asp:BoundField  DataField ="ParentId"  HeaderText ="ParentId"  SortExpression ="ParentId"
                    NullDisplayText
="我的值是NULL"   />
                
< asp:BoundField  DataField ="Name"  HeaderText ="Name"  SortExpression ="Name"   />
                
< asp:BoundField  DataField ="PublishTime"  HeaderText ="PublishTime"  SortExpression ="PublishTime"
                    ReadOnly
="true"   />
                
< asp:BoundField  DataField ="Price"  HeaderText ="Price"  SortExpression ="Price"  DataFormatString ="{0:c}"  HtmlEncode ="false"  ApplyFormatInEditMode ="True"   />
                
< asp:CheckBoxField  DataField ="IsGood"  HeaderText ="IsGood"  SortExpression ="IsGood"   />
            
</ Columns >
        
</ asp:GridView >
    
</ p >
    
< asp:ObjectDataSource  ID ="ObjectDataSource1"  runat ="server"  SelectMethod ="GetTest"
        TypeName
="Test"  InsertMethod ="InsertTest"  DeleteMethod ="DeleteTest"  UpdateMethod ="UpdateTest"
        OnInserting
="ObjectDataSource1_Inserting"  OnInserted ="ObjectDataSource1_Inserted" >
        
< InsertParameters >
            
<% --ConvertEmptyStringToNull属性默认为true-- %>
            
< asp:Parameter  Name ="parentId"  Type ="Int32"  ConvertEmptyStringToNull ="true"   />
            
< asp:Parameter  Name ="name"  Type ="String"   />
            
< asp:Parameter  Name ="publishTime"  Type ="DateTime"   />
            
< asp:Parameter  Name ="price"  Type ="Decimal"   />
            
< asp:Parameter  Name ="isGood"  Type ="Boolean"   />
            
< asp:Parameter  Direction ="Output"  Name ="minId"  Type ="Int32"   />
        
</ InsertParameters >
        
< DeleteParameters >
            
< asp:Parameter  Name ="id"  Type ="Int32"   />
        
</ DeleteParameters >
        
< UpdateParameters >
            
< asp:Parameter  Name ="id"  Type ="Int32"   />
            
< asp:Parameter  Name ="parentId"  Type ="Int32"   />
            
< asp:Parameter  Name ="name"  Type ="String"   />
            
< asp:Parameter  Name ="publishTime"  Type ="DateTime"   />
            
< asp:Parameter  Name ="price"  Type ="Decimal"   />
            
< asp:Parameter  Name ="isGood"  Type ="Boolean"   />
        
</ UpdateParameters >
    
</ asp:ObjectDataSource >
    
< asp:ObjectDataSource  ID ="ObjectDataSource2"  runat ="server"  OldValuesParameterFormatString ="original_{0}"
        SelectMethod
="GetTestById"  TypeName ="Test" >
        
< SelectParameters >
            
< asp:ControlParameter  ControlID ="GridView1"  Name ="id"  PropertyName ="SelectedValue"
                Type
="Int32"   />
        
</ SelectParameters >
    
</ asp:ObjectDataSource >
</ asp:Content >

DataSourceControl/Test.aspx.cs
using  System;
using  System.Data;
using  System.Configuration;
using  System.Collections;
using  System.Web;
using  System.Web.Security;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.WebControls.WebParts;
using  System.Web.UI.HtmlControls;

public  partial  class  DataSourceControl_Test : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    
{

    }


    
protected void ObjectDataSource1_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
    
{
        
// 编程方式给参数赋值
        if (e.InputParameters["publishTime"] == null)
        
{
            e.InputParameters[
"publishTime"] = DateTime.Now;
        }

    }


    
protected void ObjectDataSource1_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
    
{
        
// 错误处理
        if (e.Exception != null)
        
{
            
if (e.Exception.InnerException != null)
            
{
                Exception inner 
= e.Exception.InnerException;

                
if (inner is ArgumentException)
                
{
                    
string paramName = ((ArgumentException)inner).ParamName;
                    lblMsg.Text 
= string.Concat("参数 ", paramName, " 有问题");
                }

            }

        }

        
else
        
{
            
int?[] ary = (int?[])e.ReturnValue;
            lblMsg.Text 
= "新插入信息的ID是:" + ary[0].ToString();
            lblMsg.Text 
+= "<br />数据总数是:" + ary[1].ToString();

            lblMsg.Text 
+= "<br />最小ID是:" + e.OutputParameters["minId"].ToString();
        }

    }


    
protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
    
{
        
if (e.Exception != null)
        
{
            
// 错误已处理
            e.ExceptionHandled = true;
            
// DetailsView保持插入状态
            e.KeepInInsertMode = true;
        }

    }


    
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    
{
        
// 价格格式转换为decimal格式
        if (e.NewValues["Price"] != null)
            e.NewValues[
"Price"] = decimal.Parse(e.NewValues["Price"].ToString(), System.Globalization.NumberStyles.Currency);
    }

}



OK
[源码下载]
 
新一代数据访问工具(一)--DataSource控件概述 新一代数据访问工具(一)--DataSource控件概述2007年09月01日 星期六 11:49在asp.net2.0中提供了新一代的数据访问工具--DataSource。它为简单的数据库开发提供了便捷的方式。一、DataSource & ADO.Net    ADO.Net是微软先进的数据库访问技术,那它和DataSource控件相比有哪些区别呢?    1、ADO.N 阅读详情

相关推荐

ASP.NET中DataSource与GridView数据绑定的深入解析

本文还有配套的精品资源,点击获取 简介:在ASP.NET Web Forms开发中,DataSource控件和GridView控件用于高效地展示和管理数据。文章详细介绍了如何利用DataSource控件从多种数据源获取数据,并通过GridView控件绑定和更新数据,同时涵盖了删除、验证、事务处理、分页等关键操作。 1. DataSource控件与数据获取 在...

weixin_36019375的博客 1319

DataSourceControl基类

它用来作为控件的基类,其派生类通常用来作为数据绑定控件的数据源。 所在命名空间:System.Web.UI 所在程序集:System.Web(System.Web.dll中)   ASP.NET支持控件数据绑定结构,该结构使Web服务器控件 能够 以一致的方式 绑定到数据。 绑定到数据的web服务器控件称为数据绑定控件,促成这种绑定的类 称为 数据源控件。 数据源控件可以表示任何数据源...

weixin_34375233的博客 121

DataSource控件与GridView控件的数据绑定

要求通过DataSource控件将数据库中的数据绑定到GridView中,并实现数据的更新和删除

USB记录删除?文件使用记录删除?系统日志删除?何必呢?

USB记录删除?文件使用记录删除?系统日志删除?其实不用那么麻烦?关于系统记录清除功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导...

weixin_44410083的博客 1512

ATE测试的未来:自动化与智能化的技术演进

本文探讨了自动测试设备(ATE)在半导体产业中的技术演进,重点关注自动化与智能化的发展趋势。随着芯片制程的不断进步,ATE面临测试复杂度激增和成本压力等挑战。文章分析了AI技术在测试优化中的应用,如自适应测试和缺陷预测,以及模块化架构和端到端测试生态系统的创新。这些技术突破显著提升了测试效率和设备利用率,为半导体测试的未来发展指明了方向。

weixin_29232507的博客 624

231003-四步MacOS-iPadOS设置无线竖屏随航SideCar

新建虚拟屏幕参考文献。

专注机器学习之路 7508

我的ASP.NET2.0学习笔记:数据源控件

AcessDataSource数据源控件 随便说说 AccessDataSource数据源控件使用Access数据库作为数据源。使用DataFile属性直接指定Access数据库位置。AccessDataSource控件可以检索Microsoft Access数据库(文件后缀名为.mdb的文件)中的数据。同时,该控件也支持排序、筛选、分页等功能。 不能不说的秘密 一:Access...

weixin_30511039的博客 201

图像质量评估(9) -- 杂散光(Flare)的测量标准与实战解析

本文深入解析了杂散光(Flare)对图像质量的影响及其测量标准,包括ISO 9358和ISO 18844的核心方法。通过实战指南和优化策略,帮助读者掌握杂散光的测量与控制技术,提升光学系统性能。

sql99的博客 257

html5 天地图,index.html

天地图-地图API-范例-根据关键字搜索纯POI(不搜公交线).search {font-size: 13px;border: 1px solid #999999;}.ls {line-height: 27px;padding-left: 7px;}.prompt {display: none;font-size: 13px;border: 1px solid #999999;}.statisti...

weixin_39786155的博客 683

PCB设计教程【入门篇】——PCB设计基础-PCB构成与组成

本教程基于B站Expert电子实验室的PCB设计教学的整理,为个人学习记录,旨在帮助PCB设计新手入门。所有内容仅作学习交流使用,无任何商业目的。若涉及侵权,请随时联系,将会立即处理。

2501_91732643的博客 7717

YOLOv5+Astra Pro Plus深度相机:手把手教你实现实时目标检测(附ROS配置技巧)

本文详细介绍了如何将YOLOv5目标检测算法与Astra Pro Plus深度相机结合,构建实时目标检测系统。内容涵盖从硬件选型、环境搭建、ROS配置到YOLOv5部署与深度信息融合的完整流程,并分享了性能优化、避障算法等实战技巧,帮助开发者在机器人视觉等场景中快速实现智能感知应用。

weixin_28292761的博客 401

温故知新ASP.NET 2.0(C#)系列文章索引

[源码下载]温故知新ASP.NET 2.0(C#)系列文章索引作者:webabcd介绍温故知新ASP.NET 2.0(C#)系列文章索引:MasterPage(母版页)、Themes(主题)、SiteMap(站点地图)、Cache&SqlCacheDependency(缓存和SqlCacheDependency特性)、Localization(本地化,多语言)、Membership&Rol

johncools的博客 2418

【RT-DETR有效改进】计算训练好权重文件对应的FPS、推理每张图片的平均时间(科研必备)

本文给大家带来的改进机制是利用我们训练好的权重文件计算FPS,同时打印每张图片所利用的平均时间,模型大小(以MB为单位),同时支持batch_size功能的选择,对于轻量化模型的读者来说,本文的内容对你一定有帮助,可以清晰帮你展示出模型速度性能的提升以及轻量化的效果(模型大小),对于以提高精度为目的的读者本文也能够帮助大家展示出现阶段的模型速度指标。所以本文的内容是十分有用的机制,对于大家发表论文来说,下面的图片为运行后的效果可以看到,该有的指标均已打印(本文内容为我独家创新,全网无第二份)下面是效果图和文

Snu77的博客 3637

转 温故知新ASP.NET 2.0(C#)系列文章索引

 温故知新ASP.NET 2.0(C#)系列文章索引作者:webabcd介绍温故知新ASP.NET 2.0(C#)系列文章索引:MasterPage(母版页)、Themes(主题)、SiteMap(站点地图)、Cache&SqlCacheDependency(缓存和SqlCacheDependency特性)、Localization(本地化,多语言)、Membership&RoleMana

Many a little makes a mickle. 430

javafx结合Scene Builder自定义fxml实现漂亮的登录界面、自定义最小化、关闭按钮

本节主要介绍了如何结合Scene Builder工具来制作一个好看又漂亮的登录界面,以及介绍了如何在程序中调用生成界面文件fxml文件,如何获取到fxml文件中的组件等,并演示登录、最小化和关闭等功能。

c1007857613的专栏 5225

EML 全面实践指南:把 SAP RAP 业务对象玩出工程化的稳定与优雅

本文面向掌握ABAP基础、正在实施RAP的开发者,深入讲解EML(Entity Manipulation Language)的核心用法。文章围绕READ ENTITIES、MODIFY ENTITIES、COMMIT ENTITIES三大语句,详细解析其语义、类型体系、事务机制及工程实践。重点内容包括:字段裁剪、派生类型、草稿控制、批量更新、事务缓冲与保存序列等关键技术点,并配合真实案例代码。旨在帮助开发者在SAP ABAP On-Premise和BTP环境中构建可维护、可演进的业务对象访问层,同时避免常见

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 337

用AI Agent打造APP测试搭子:用例生成到缺陷整理的工作流实践

AI Agent是具备任务拆解与工具调用能力的智能体,其核心原理是通过Function Calling或流程编排,让模型输出结构化指令并调用外部工具。在APP测试工程中,AI Agent可以显著提升用例设计、缺陷整理、日志初筛等重复性工作的效率,将测试工程师从繁琐的信息搬运中解放出来。典型应用场景包括:将PRD结构化转换为测试用例、通过ADB命令控制设备并抓取日志、自动组装缺陷描述、汇总测试报告等。本文以“测试搭子”为切入点,介绍如何基于状态机工作流搭建一个可落地的APP测试智能体,涵盖任务边界定义、工具配

weixin_33795743的博客 463

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

深入了解数据源控件(Data Source controls):DataSourceControl(二)

原文:http://www.manuelabadia.com/blog/PermaLink,guid,eb... 前一篇:深入了解数据源控件(Data Souce controls):BaseDataBoundControl和DataBoundControl(一) 在前一篇文章,我解释了数据绑定控件的基本结构(当框架调用绑定方法时怎样得到数据从DataSourceView)。现在是该解释Data...

weixin_33979203的博客 194

WINCC7.3破解文件

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

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

vue方法中如何获得另外一个方法的返回值

问题: 比如方法A()调用B()方法,然后B方法中返回一个值给A,A接收到这个方法再继续执行下一步的代码,如何实现?? 解决: methods: { async A() { const result = await B(); // dosomethings . . . }, B() { // dosomethings . . .

Rocky balboa 1万+

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

上一篇: 温故知新ASP.NET 2.0(C#)(7) - Profile(存储用户配置)
下一篇: 我(webabcd)的文章索引
webabcd
博客等级 码龄17年 28粉丝 911原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址