C#对底层数据操作的通用类

C#知识|通用数据访问类SQLHelper的编写 哈喽,你好啊,我是雷工!前面学习了C#操作SQLServer数据库数据的增删改查,《C#知识|通过ADO.NET实现应用程序对数据库的增、删、改操作。其中实现的过程中有很多代码是重复的,此时作为高阶程序员为了使代码更优雅,避免重复,从而要考虑代码的复用技术,针对此案例中代码重复情况,结合项目中对数据库的操作还是挺普遍的,为了便于其他项目也能够复用该方法,可以将数据访问写成一个通用的类。 阅读详情

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace DataLibrary
{
 /// <summary>
 /// 数据连接设置
 /// </summary>
 public class SqlConnect
 {
  static string sqlconnstr;

  /// <summary>
  /// 连接字符串
  /// </summary>
  public string ConnString
  {
   set
   {
    sqlconnstr=value;
   }
   get
   {
    return sqlconnstr;
   }
  }

  /// <summary>
  /// 取得连接
  /// </summary>
  /// <returns></returns>
  public SqlConnection GetSqlConnection()
  {
   SqlConnection _connection=null;
   if(sqlconnstr==null || sqlconnstr=="")
   {
    string SystemDir=System.Environment.SystemDirectory;
    DisposalConductService DisposalConductService1= new DisposalConductService(SystemDir+"//CBERP_Dis.DLL") ;
    sqlconnstr = "server="+DisposalConductService1.GetValue("ServerName","(local)")
     +";user id="+DisposalConductService1.GetValue("SqlAccount","sa")
     +";password="+DisposalConductService1.GetValue("PassWord","jiayu520")
     +";Database="+DisposalConductService1.GetValue("Database","CBERP");
   }
   try
   {
    _connection = new SqlConnection(sqlconnstr);
    _connection.Open();
   }
   catch(SqlException SE)
   {
    if(SE.Number==17 || SE.Number==18456)
    {
     if( MessageBox.Show("数据库访问参数设置不正确,是否对需要对其进行设置?","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Question)==DialogResult.Yes)
     {
      sqlconnstr="";
      DisposalConduct config = new DisposalConduct();
      config.ShowDialog();
      _connection=GetSqlConnection();
     }
     else
     {
      MessageBox.Show("建立数据库连接失败,程序不能继续运行!","错误",MessageBoxButtons.OK,MessageBoxIcon.Stop);
      Application.ExitThread();
      Application.Exit();
     }
    }
    else
    {
     MessageBox.Show(SE.Message,"提示信息",MessageBoxButtons.OK,MessageBoxIcon.Information);
     _connection.Close();
    }
   }
   return _connection;
  }
 }

 /// <summary>
 /// 数据配置
 /// </summary>
 public class DataCatena : IDisposable
 {
  private SqlConnection _connection;
  /// <summary>
  /// 数据配置
  /// </summary>
  public DataCatena()
  {
   SqlConnect sqlconnect = new SqlConnect();
   _connection = sqlconnect.GetSqlConnection();
   _connection.Close();
  }

  /// <summary>
  /// 数据配置
  /// </summary>
  /// <param name="connStr">连接字符串</param>
  public DataCatena(String connStr)
  {
   _connection = new SqlConnection(connStr);
  }

  /// <summary>
  /// 取得DataView
  /// </summary>
  /// <param name="Sqlstr">连接字符串</param>
  /// <returns>数据视图</returns>
  public DataView GetDataView(String Sqlstr)
  {
   DataView dv=null;
   SqlDataAdapter myCommand = new SqlDataAdapter(Sqlstr, _connection);
   DataSet ds = new DataSet();
   try
   {
    myCommand.Fill(ds,"table");
    dv=ds.Tables["table"].DefaultView;
   }
   catch(SqlException exc)
   {
    DebugBox db = new DebugBox(Sqlstr + "/r/n" + exc.Message);
    db.Show();
   }
   return dv;
  }

  /// <summary>
  /// 清理资源
  /// </summary>
  public void Dispose()
  {
   Dispose(true);
   GC.SuppressFinalize(true);
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  /// <param name="disposing"></param>
  protected virtual void Dispose(bool disposing)
  {
   if (! disposing)
    return;

   if (this._connection != null)
   {
    this._connection.Dispose();
   }
  }

  /// <summary>
  /// 取得数据适配器
  /// </summary>
  /// <param name="Sqlstr">SQL语句</param>
  /// <returns>数据适配器</returns>
  public SqlDataAdapter GetSqlDA(string Sqlstr)
  {
   SqlDataAdapter myCommand = new SqlDataAdapter(Sqlstr, _connection);
   return myCommand;
  }

  /// <summary>
  /// 取得数据表
  /// </summary>
  /// <param name="Sqlstr">SQL语句</param>
  /// <returns>数据表</returns>
  public DataTable GetDT(String Sqlstr)
  {
   SqlDataAdapter myCommand = new SqlDataAdapter(Sqlstr, _connection);
   DataSet ds = new DataSet();
   try
   {
    myCommand.Fill(ds,"table");
   }
   catch(SqlException exc)
   {
    DebugBox db = new DebugBox(Sqlstr + "/r/n" + exc.ToString());
    db.Show();
   }
   return ds.Tables["table"];
  }

  /// <summary>
  /// 执行语句
  /// </summary>
  /// <param name="Sqlstr">SQL语句</param>
  /// <returns></returns>
  public object ExecWithValue(String Sqlstr)
  {
   object result=null;
   _connection.Open();
   SqlCommand myCommand = new SqlCommand(Sqlstr, _connection);
   try
   {
    result=myCommand.ExecuteScalar();
   }
   catch (SqlException exc)
   {
    DebugBox db = new DebugBox(Sqlstr + "/r/n" + exc.ToString());
    db.Show();
    //MessageBox.Show(exc.Message);
   }
   _connection.Close();
   return result;
  }

  /// <summary>
  /// 返回相应的行数
  /// </summary>
  /// <param name="Sqlstr">SQL语句</param>
  /// <returns>行数</returns>
  public int Exec(String Sqlstr)
  {
   int sucess=0;     
   SqlCommand myCommand = new SqlCommand(Sqlstr, _connection);
   _connection.Open();
   try
   {
    myCommand.ExecuteNonQuery();
   }
   catch (SqlException exc)
   {
    DebugBox db = new DebugBox(Sqlstr + "/r/n" + exc.ToString());
    db.Show();
    //    MessageBox.Show(exc.Message);
    sucess=exc.Number;
   }
   _connection.Close();
   return sucess;
  }
 }

 /// <summary>
 /// 单表操作
 /// </summary>
 public class SingleTable
 {
  private DataCatena DataCatena;
  private SqlDataAdapter myDataAdapter;
  private DataSet ds;
  /// <summary>
  /// 单表操作
  /// </summary>
  /// <param name="Sqlstr"></param>
  public SingleTable(string Sqlstr)
  {
   DataCatena = new DataCatena();
   myDataAdapter = DataCatena.GetSqlDA(Sqlstr);
   ds = new DataSet();
   myDataAdapter.Fill(ds, "Table1");
  }

  /// <summary>
  /// 更新一个表
  /// </summary>
  /// <param name="Sqlstr"></param>
  public void SetUpdateCommand(string Sqlstr)
  {
   myDataAdapter.UpdateCommand = new SqlCommand(Sqlstr,myDataAdapter.SelectCommand.Connection);
  }

  /// <summary>
  /// 返回数据表
  /// </summary>
  /// <returns></returns>
  public DataTable GetDataTable()
  {
   return ds.Tables["Table1"];
  }

  /// <summary>
  /// 返回数据适配器
  /// </summary>
  /// <returns></returns>
  public SqlDataAdapter GetDataAdapter()
  {
   return myDataAdapter;
  }

  /// <summary>
  /// 更新表
  /// </summary>
  public void Update()
  {
   myDataAdapter.Update(ds, "Table1");
  }
 }

 /// <summary>
 /// 自动更新
 /// </summary>
 public class AutoUpdateObj
 {
  private DataCatena DataCatena;
  private SqlDataAdapter myDataAdapter;
  private SqlCommandBuilder cb;
  private DataSet ds;
  /// <summary>
  /// 自动更新
  /// </summary>
  /// <param name="Sqlstr"></param>
  public AutoUpdateObj(string Sqlstr)
  {
   DataCatena = new DataCatena();
   myDataAdapter = DataCatena.GetSqlDA(Sqlstr);
   cb = new SqlCommandBuilder(myDataAdapter);
   ds = new DataSet();
   myDataAdapter.Fill(ds, "Table1");
  }

  /// <summary>
  /// 更新SQL语句
  /// </summary>
  /// <param name="Sqlstr"></param>
  public void SetUpdateCommand(string Sqlstr)
  {
   myDataAdapter.UpdateCommand = new SqlCommand(Sqlstr,myDataAdapter.SelectCommand.Connection);
  }

  /// <summary>
  /// 设置Select语句
  /// </summary>
  /// <param name="Sqlstr"></param>
  public void SetSelectCommand(string Sqlstr)
  {
   myDataAdapter.SelectCommand = new SqlCommand(Sqlstr,myDataAdapter.SelectCommand.Connection);
   cb.DataAdapter = myDataAdapter ;
   ds.Tables.Clear();
  }

  /// <summary>
  /// 取得数据表
  /// </summary>
  /// <returns></returns>
  public DataTable GetDataTable()
  {
   ds.Clear();
   myDataAdapter.Fill(ds, "Table1");
   return ds.Tables["Table1"];
  }

  /// <summary>
  /// 取得数据适配器
  /// </summary>
  /// <returns></returns>
  public SqlDataAdapter GetDataAdapter()
  {
   return myDataAdapter;
  }

  /// <summary>
  /// 更新
  /// </summary>
  public void Update()
  {
   try
   {
    myDataAdapter.Update(ds, "Table1");
   }
   catch(SqlException sqlex)
   {
    MessageBox.Show("出错原因:"+sqlex.Message,"出错",MessageBoxButtons.OK,MessageBoxIcon.Error);
   }
  }
 }
}

C#常用类大全(包括数据库操作类) 由本人整理收集的ASP.net,C#常用类(包括数据库操作类,日志记录类,字符串类,JS操作类,FTP操作类....) 立即下载

相关推荐

FATFS 官方库 SPI底层接口

STM32 SPI 底层,FATFS操作系统,官方文件

用C#打造自己的通用数据访问类库

http://blog.youkuaiyun.com/zhoufoxcn/article/details/7455708

leixg的专栏 697

C#.Net底层操作数据库及常用功能封装类

常用数据库操作功能的封装。 消息功能封装 常用加密解密方式的封装 邮件发送功能的封装 数据字符串功能的封装 等等

使用设计模式构建通用数据库访问类

使用设计模式构建通用数据库访问类作者:孙亚民    本文选自:赛迪网  2003年03月20日   在应用程序的设计中,数据库的访问是非常重要的,我们通常需要将对数据库的访问集中起来,以保证良好的封装性和可维护性。在.Net中,数据库的访问,对于微软自家的SqlServer和其他数据库(支持OleDb),采用不同的访问方法,这些类分别分布于System.Data.SqlCl

sunny_y_m的专栏 1905

C#轻量级通用最基础ORM,支持多数据库

最最最最最最基础的操作数据库增删改查,支持事务,通用类,理论上支持MsSql,Oracle,OleDb,MySql,Sqlite等。(由于后两种需要额外引入相关Dll,因此本类中不包含实现,自己添加即可。) 本类只是提供一种思路,可以参考。

DataAdapter是如何更新数据库数据的

DataAdapter对象不仅只是捕获数据的功能,事实上它还可以帮助你将更新后的DataSet以批次的方式再写回后台数据库,而且还相当简单,只要调入Update方法,并传入准备更新的DataSet及DataTable即可。

C#修改

C#修改,在客户端中获取到数据传到服务端进行数据处理传给数据库进行修改数据操作 在数据库中写好修改语句,传个@Type形參进行初步的判断它是否执行的是本方法,要修改的字段都要给个参数来进行接收数据,然后把参数的数据赋值给对应要修改的字段, 最重要的一个参数就是你的主键ID,应为ID是自增的,不会重复,所以要判断它修改的是哪条数据就要给个where条件进行筛选出来后再进行修改。 服...

weixin_44560357的博客 1132

6种常用数据分析方法详解:从描述统计到时间序列

数据分析是连接数据与业务决策的桥梁。面对海量数据,掌握描述性统计与对比分析可快速了解现状与差距;相关分析与回归分析能揭示变量间的关联与影响大小;聚类分析用于用户分群,时间序列分析则预测未来走势。这些方法广泛应用于用户画像、销量预测、活动效果评估等场景,是数据分析师和运营人员必备的技能。系统掌握这6种核心方法的使用场景、原理逻辑与实操步骤,能够帮助读者建立完整分析框架,真正用数据驱动业务增长。

weixin_34405354的博客 335

C#底层库--数据实体类

本专栏为【底层库】,主要介绍编程过程中 通用函数。我们将这些通用固化的源码,进行重写、封装、拓展,再进行单元测试、集成测试、beta测试,最终形成通用化模板,这里我们称为“底层库”。 作为研发人员的你,并不需要花大量时间,研究“底层库”的含义,及“底层库”的实现方法。你只需要几行调用代码,就可以解决项目上碰到的难题。而底层库使用方法,本专栏均有详细介绍,也有项目应用场景。 底层库已实现功能:MySQL脚本构建器、MySQL数据库访问操作、参数配置文件读写、加解密算法、日志记录、HTTP通信、Socket

花北城的博客 1816

PS/2鼠标接口协议

一、PS/2鼠标接口        PS/2接口用于许多现代的鼠标和键盘,由IBM最初开发和使用。物理上的PS/2接口有两种类型的连接器:5脚的DIN和6脚的MINI-DIN。        二、鼠标的接口协议原理             PS/2鼠标接口采用一种双向同步串行协议。即每在时钟线上发一个脉冲,就在数据线上发送一位数据。但是在相互传输中 ,主机是拥有总线控制权的

Ant's home 1万+

科研党必备:Zotero+Deepseek 打造AI文献阅读助手(附详细插件配置指南)

本文详细介绍了如何利用Zotero和Deepseek打造AI文献阅读助手,提升科研效率。从Zotero基础安装到中文文献处理插件茉莉花的配置,再到Deepseek API的集成与模型选择策略,全面覆盖了AI辅助阅读的关键环节。特别适合需要高效管理海量文献的科研工作者,显著提升文献筛选和分析速度。

backprop5master的博客 424

C#底层库–网络通信帮助类HTTP

文将新增一个专栏–底层库,分享编程过程中常用的方法函数。我们将这些常用的方法函数,进行封装,反复测试,形成通用化类库。方便研发人员,只需要几行代码就可以使用它,解决一些难点问题。底层库的封装涉及到:数据库操作、加解密算法、日志记录、网络通信、邮件发送、文件操作、参数保存、Excel导入导出等等,持续关注本专栏吧。大家有任何问题,也可以评论区反馈,私信我。网络访问帮助类,采用HTTP方式访问服务端,包含get、post、put、delete。

花北城的博客 1812

Python爬虫案例:从39问医生网爬取口腔科的在线问答记录(单轮问答)

本次实验爬取39问医生网中口腔科分类下的所有在线单轮问答记录,每页32条,共100页,总数据量为3200条,最终结果以excel格式保存。

JieBao11的博客 1641

LINQ不是SQL替代品,而是C#数据操作的通用协议

LINQ(Language Integrated Query)是C#语言内建的声明式数据查询机制,本质是一套面向集合与转换操作的通用协议,而非专为数据库设计的语法糖。其核心原理基于标准查询操作符(Where、Select、GroupBy等)、Lambda表达式与延迟执行模型,通过IEnumerable<T>和IQueryable<T>双接口抽象,统一内存集合、数据库、XML等异构数据源的操作范式。技术价值在于提升代码可读性、类型安全性与跨数据源复用能力;典型应用场景涵盖实时风控规则编排、微服务订单聚合、配置

世范水晶 413

【实战学习(五)】开源项目学习之uWSGI的部署以及配合nginx

文章目录1)uWSGI是什么?1.1 WSGI1.1.1 Application端1.1.2 Server端1.1.3 WSGI中间件1.2 uwgi1.3 uWSGI、WSGI、uwsgi之间的关系*为什么有了uWSGI为什么还需要nginx?2)连接uwsgi和Django*避坑之Windows10安装uWSGI非常极其艰难,最好勿浪费时间,直接转战Linux吧:2.1 uWGI部署2.1.1 在虚拟环境下安装uwsgi:2.1.2 测试uWSGI的运行2.1.3 使用uWSGI运行Django项目2.

黑黑白白君的博客 1507

AI之KE:Knowledge Engineering知识工程的简介、发展、应用案例之详细攻略

AI之KE:Knowledge Engineering知识工程的简介、发展、应用案例之详细攻略 目录 Knowledge Engineering知识工程的简介 0.1、What 0.2、How 0.3、Why 1、知识工程过程的5个活动 2、知识图谱的应用 Knowledge Engineering知识工程的发展 1、前知识工程时期——1950-1970时期:图...

头部AI社区如有邀博主AI主题演讲请私信—心比天高,仗剑走天涯,保持热爱,奔赴向梦想!低调,专注,谦虚,自律,反思,成长,还算比较正能量的博主,公益免费传播…内心特别想在AI界做出一些可以推进历史进程影响力的技术(兴趣使然,有点小情怀,也有点使命感呀 5335

c# DataSet 类

摘要:ADO.NET中的DataSet是一个内存数据库容器,支持离线数据操作和复杂关系管理。核心特性包括:离线存储、多表关联、数据状态跟踪和架构独立性。其结构包含Tables集合(数据表)、Relations集合(表关系)和扩展属性。通过示例展示了创建数据集、数据操作、关系定义和XML持久化等完整流程。DataSet适用于离线场景、复杂数据关系和批量更新,但需注意内存占用问题。它是处理中小规模关系型数据的有效工具,特别适合需要数据离线操作的应用程序开发。

weixin_66547608的博客 1657

基于STM32、HAL库的IP5356M_DBZ_CA快充协议芯片简介及驱动程序设计

IP5356M_BATTERY_LEVEL_25 = 1, /* 电池电量25% */IP5356M_CHARGE_STATE_CHARGE_DONE = 4, /* 充电完成 */IP5356M_CHARGE_STATE_FAST = 2, /* 快速充电 */IP5356M_CHARGE_STATE_NONE = 0, /* 无充电 */IP5356M_CHARGE_STATE_PRE = 1, /* 预充电 *//* 延时1秒 */

corlin6688的博客 1417

C# 数据操作系列 - 4. 自己实现一个ORM

0. 前言 在之前的几篇内容中,我们了解了如何通过ADO.NET 访问数据库,如何修改、新增数据。如何通过DataSet和DataAdapter获取数据,我们将在这一篇试试自己实现一个简单的ORM框架或者说ORM工具类。 涉及到的知识点: 反射(初级) ADO.NET 已有知识 1. ORM 那么,问题来了,什么是ORM?ORM全称 Object Relational Mapping,翻译过来就是对象关系映射。是一种通过描述对象与数据库之间映射关系的数据,将对象保存到数据库中的技术。 在C#中,曾经En

菜鸡成长日记 1254

【实战教程】OpenClaw接入MySQL数据库实战指南

本文介绍了在虚拟机Ubuntu中访问宿主机Win11中MySQL数据库的配置方法,重点包括创建远程用户、权限配置和安全设置。首先在MySQL中创建具有只读权限的用户并刷新权限,然后调整服务器设置允许远程连接。文章还提供了某金融机构财富管理系统的数据库设计方案,包含理财产品表、客户表和份额表的核心结构,其中金额字段使用DECIMAL类型确保精度,并设置唯一键约束。文末强调测试环境配置完成后应恢复安全更新模式以保障生产环境安全。

海兰 8697

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

揭秘C# Span底层原理:如何实现零分配高效数据处理

掌握C# Span高效数据处理技巧,解决内存分配性能瓶颈。通过C# Span 示例详解其在字符串操作、数组切片等场景的应用,揭示栈上内存管理与零分配优势,提升程序执行效率,值得收藏。

CodeWhim的博客 755

深度学习工具包 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、C++、C# 的语言定位与核心差异解析》

C、C++ 和 C# 的核心差异源于定位:C 是底层效率之王,C++ 是中层灵活性代表,C# 是高层生产力工具。

sycghjhjkk的博客 436

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

【编程】(1)-跨平台跨语言C#、Java、鸿蒙ArkTS三端通用实体接口

本文介绍了作者设计的一个跨平台、跨语言的轻量级框架,重点展示了在C#、Java和鸿蒙ArkTS三端通用的实体接口IEntity<TKey>的实现。该接口采用泛型设计支持多种主键类型,并保持三端接口定义完全一致,便于代码移植。文章阐述了只保留Id属性的设计考量,并预告了后续将发布更多三端通用组件。这种设计旨在为不同语言和平台提供统一的开发体验,同时保持足够的灵活性。

248
上一篇: 如何通过C#实现单据号码的自动增加。
下一篇: 公共配置对话框
甴曱
博客等级 码龄24年 184粉丝 29原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值