Oracle 游标使用全解

Oracle游标介绍及示例代码 本文介绍了显式游标和隐式游标的基本概念,并提供了相应的示例代码来演示其用法。它通常用于存储SQL语句的执行结果,在查询中使用隐式游标时,Oracle会自动为其分配一个默认的游标。,它存储了一个查询结果集,该结果集包含了部门ID为100的员工的员工ID、姓和名。然后,我们打开游标,并使用FETCH语句将查询结果集中的数据逐行获取到变量中,再进行相应的处理。在Oracle中,游标可以分为显式游标和隐式游标两种类型。显式游标是由程序员显式地定义、打开和关闭的游标,而隐式游标是由Oracle自动创建和管理的。 阅读详情
-- 声明游标;CURSOR cursor_name IS select_statement

--For 循环游标
--(1)定义游标
--(2)定义游标变量
--(3)使用for循环来使用这个游标
declare
       --类型定义
       cursor c_job
       is
       select empno,ename,job,sal
       from emp
       where job='MANAGER';
       --定义一个游标变量v_cinfo c_emp%ROWTYPE ,该类型为游标c_emp中的一行数据类型
       c_row c_job%rowtype;
begin
       for c_row in c_job loop
         dbms_output.put_line(c_row.empno||'-'||c_row.ename||'-'||c_row.job||'-'||c_row.sal);
       end loop;
end;


      
--Fetch游标
--使用的时候必须要明确的打开和关闭

declare 
       --类型定义
       cursor c_job
       is
       select empno,ename,job,sal
       from emp
       where job='MANAGER';
       --定义一个游标变量
       c_row c_job%rowtype;
begin
       open c_job;
         loop
           --提取一行数据到c_row
           fetch c_job into c_row;
           --判读是否提取到值,没取到值就退出
           --取到值c_job%notfound 是false 
           --取不到值c_job%notfound 是true
           exit when c_job%notfound;
            dbms_output.put_line(c_row.empno||'-'||c_row.ename||'-'||c_row.job||'-'||c_row.sal);
         end loop;
       --关闭游标
      close c_job;
end;

--1:任意执行一个update操作,用隐式游标sql的属性%found,%notfound,%rowcount,%isopen观察update语句的执行情况。
       begin
         update emp set ENAME='ALEARK' WHERE EMPNO=7469;
         if sql%isopen then
           dbms_output.put_line('Openging');
           else
             dbms_output.put_line('closing');
             end if;
          if sql%found then
            dbms_output.put_line('游标指向了有效行');--判断游标是否指向有效行
            else
              dbms_output.put_line('Sorry');
              end if;
              if sql%notfound then
                dbms_output.put_line('Also Sorry');
                else
                  dbms_output.put_line('Haha');
                  end if;
                   dbms_output.put_line(sql%rowcount);
                   exception 
                     when no_data_found then
                       dbms_output.put_line('Sorry No data');
                       when too_many_rows then
                         dbms_output.put_line('Too Many rows');
                         end;
declare
       empNumber emp.EMPNO%TYPE;
       empName emp.ENAME%TYPE;
       begin
         if sql%isopen then
           dbms_output.put_line('Cursor is opinging');
           else
             dbms_output.put_line('Cursor is Close');
             end if;
             if sql%notfound then
               dbms_output.put_line('No Value');
               else
                 dbms_output.put_line(empNumber);
                 end if;
                 dbms_output.put_line(sql%rowcount);
                 dbms_output.put_line('-------------');
                 
                 select EMPNO,ENAME into  empNumber,empName from emp where EMPNO=7499;
                 dbms_output.put_line(sql%rowcount);
                 
                if sql%isopen then
                dbms_output.put_line('Cursor is opinging');
                else
                dbms_output.put_line('Cursor is Closing');
                end if;
                 if sql%notfound then
                 dbms_output.put_line('No Value');
                 else
                 dbms_output.put_line(empNumber);
                 end if;
                 exception 
                   when no_data_found then
                     dbms_output.put_line('No Value');
                     when too_many_rows then
                       dbms_output.put_line('too many rows');
                       end;
                   
                 
       
--2,使用游标和loop循环来显示所有部门的名称
--游标声明
declare 
       cursor csr_dept
       is
       --select语句
       select DNAME
       from Depth;
       --指定行指针,这句话应该是指定和csr_dept行类型相同的变量
       row_dept csr_dept%rowtype;
begin
       --for循环
       for row_dept in csr_dept loop
           dbms_output.put_line('部门名称:'||row_dept.DNAME);
       end loop;
end;


--3,使用游标和while循环来显示所有部门的的地理位置(用%found属性)
declare
       --游标声明
       cursor csr_TestWhile
       is
       --select语句
       select  LOC
       from Depth;
       --指定行指针
       row_loc csr_TestWhile%rowtype;
begin
  --打开游标
       open csr_TestWhile;
       --给第一行喂数据
       fetch csr_TestWhile into row_loc;
       --测试是否有数据,并执行循环
         while csr_TestWhile%found loop
           dbms_output.put_line('部门地点:'||row_loc.LOC);
           --给下一行喂数据
           fetch csr_TestWhile into row_loc;
         end loop;
       close csr_TestWhile;
end; 
select * from emp



       
--4,接收用户输入的部门编号,用for循环和游标,打印出此部门的所有雇员的所有信息(使用循环游标)
--CURSOR cursor_name[(parameter[,parameter],...)] IS select_statement;
--定义参数的语法如下:Parameter_name [IN] data_type[{:=|DEFAULT} value]  

declare 
      CURSOR 
      c_dept(p_deptNo number)
      is
      select * from emp where emp.depno=p_deptNo;
      r_emp emp%rowtype;
begin
        for r_emp in c_dept(20) loop
            dbms_output.put_line('员工号:'||r_emp.EMPNO||'员工名:'||r_emp.ENAME||'工资:'||r_emp.SAL);
        end loop;
end;
select * from emp   
--5:向游标传递一个工种,显示此工种的所有雇员的所有信息(使用参数游标)
declare 
       cursor
       c_job(p_job nvarchar2)
       is 
       select * from emp where JOB=p_job;
       r_job emp%rowtype;
begin 
       for r_job in c_job('CLERK') loop
           dbms_output.put_line('员工号'||r_job.EMPNO||' '||'员工姓名'||r_job.ENAME);
        end loop;
end;
SELECT * FROM EMP

--6:用更新游标来为雇员加佣金:(用if实现,创建一个与emp表一摸一样的emp1表,对emp1表进行修改操作),并将更新前后的数据输出出来 
--http://zheng12tian.iteye.com/blog/815770 
        create table emp1 as select * from emp;
        
declare
        cursor
        csr_Update
        is
        select * from  emp1 for update OF SAL;
        empInfo csr_Update%rowtype;
        saleInfo  emp1.SAL%TYPE;
begin
    FOR empInfo IN csr_Update LOOP
      IF empInfo.SAL<1500 THEN
        saleInfo:=empInfo.SAL*1.2;
       elsif empInfo.SAL<2000 THEN
        saleInfo:=empInfo.SAL*1.5;
        elsif empInfo.SAL<3000 THEN
        saleInfo:=empInfo.SAL*2;
      END IF;
      UPDATE emp1 SET SAL=saleInfo WHERE CURRENT OF csr_Update;
     END LOOP;
END;

--7:编写一个PL/SQL程序块,对名字以‘A’或‘S’开始的所有雇员按他们的基本薪水(sal)的10%给他们加薪(对emp1表进行修改操作)
declare 
     cursor
      csr_AddSal
     is
      select * from emp1 where ENAME LIKE 'A%' OR ENAME LIKE 'S%' for update OF SAL;
      r_AddSal csr_AddSal%rowtype;
      saleInfo  emp1.SAL%TYPE;
begin
      for r_AddSal in csr_AddSal loop
          dbms_output.put_line(r_AddSal.ENAME||'原来的工资:'||r_AddSal.SAL);
          saleInfo:=r_AddSal.SAL*1.1;
          UPDATE emp1 SET SAL=saleInfo WHERE CURRENT OF csr_AddSal;
      end loop;
end;
--8:编写一个PL/SQL程序块,对所有的salesman增加佣金(comm)500
declare
      cursor
          csr_AddComm(p_job nvarchar2)
      is
          select * from emp1 where   JOB=p_job FOR UPDATE OF COMM;
      r_AddComm  emp1%rowtype;
      commInfo emp1.comm%type;
begin
    for r_AddComm in csr_AddComm('SALESMAN') LOOP
        commInfo:=r_AddComm.COMM+500;
         UPDATE EMP1 SET COMM=commInfo where CURRENT OF csr_AddComm;
    END LOOP;
END;

--9:编写一个PL/SQL程序块,以提升2个资格最老的职员为MANAGER(工作时间越长,资格越老)
--(提示:可以定义一个变量作为计数器控制游标只提取两条数据;也可以在声明游标的时候把雇员中资格最老的两个人查出来放到游标中。)
declare
    cursor crs_testComput
    is
    select * from emp1 order by HIREDATE asc;
    --计数器
    top_two number:=2;
    r_testComput crs_testComput%rowtype;
begin
    open crs_testComput;
       FETCH crs_testComput INTO r_testComput;
          while top_two>0 loop
             dbms_output.put_line('员工姓名:'||r_testComput.ENAME||' 工作时间:'||r_testComput.HIREDATE);
             --计速器减一
             top_two:=top_two-1;
             FETCH crs_testComput INTO r_testComput;
           end loop;
     close crs_testComput;
end;
    

--10:编写一个PL/SQL程序块,对所有雇员按他们的基本薪水(sal)的20%为他们加薪,
--如果增加的薪水大于300就取消加薪(对emp1表进行修改操作,并将更新前后的数据输出出来) 
declare
    cursor
        crs_UpadateSal
    is
        select * from emp1 for update of SAL;
        r_UpdateSal crs_UpadateSal%rowtype;
        salAdd emp1.sal%type;
        salInfo emp1.sal%type;
begin
        for r_UpdateSal in crs_UpadateSal loop
           salAdd:= r_UpdateSal.SAL*0.2;
           if salAdd>300 then
             salInfo:=r_UpdateSal.SAL;
              dbms_output.put_line(r_UpdateSal.ENAME||':  加薪失败。'||'薪水维持在:'||r_UpdateSal.SAL);
             else 
              salInfo:=r_UpdateSal.SAL+salAdd;
              dbms_output.put_line(r_UpdateSal.ENAME||':  加薪成功.'||'薪水变为:'||salInfo);
           end if;
           update emp1 set SAL=salInfo where current of crs_UpadateSal;
        end loop;
end;
     
--11:将每位员工工作了多少年零多少月零多少天输出出来   
--近似
  --CEIL(n)函数:取大于等于数值n的最小整数
  --FLOOR(n)函数:取小于等于数值n的最大整数
  --truc的用法 http://publish.it168.com/2005/1028/20051028034101.shtml
declare
  cursor
   crs_WorkDay
   is
   select ENAME,HIREDATE, trunc(months_between(sysdate, hiredate) / 12) AS SPANDYEARS,
       trunc(mod(months_between(sysdate, hiredate), 12)) AS months,
       trunc(mod(mod(sysdate - hiredate, 365), 12)) as days
   from emp1;
  r_WorkDay crs_WorkDay%rowtype;
begin
    for   r_WorkDay in crs_WorkDay loop
    dbms_output.put_line(r_WorkDay.ENAME||'已经工作了'||r_WorkDay.SPANDYEARS||'年,零'||r_WorkDay.months||'月,零'||r_WorkDay.days||'天');
    end loop;
end;
  
--12:输入部门编号,按照下列加薪比例执行(用CASE实现,创建一个emp1表,修改emp1表的数据),并将更新前后的数据输出出来
--  deptno  raise(%)
--  10      5%
--  20      10%
--  30      15%
--  40      20%
--  加薪比例以现有的sal为标准
--CASE expr WHEN comparison_expr THEN return_expr
--[, WHEN comparison_expr THEN return_expr]... [ELSE else_expr] END
declare
     cursor
         crs_caseTest
          is
          select * from emp1 for update of SAL;
          r_caseTest crs_caseTest%rowtype;
          salInfo emp1.sal%type;
     begin
         for r_caseTest in crs_caseTest loop
         case 
           when r_caseTest.DEPNO=10
           THEN salInfo:=r_caseTest.SAL*1.05;
           when r_caseTest.DEPNO=20
           THEN salInfo:=r_caseTest.SAL*1.1;
           when r_caseTest.DEPNO=30
           THEN salInfo:=r_caseTest.SAL*1.15;
            when r_caseTest.DEPNO=40
           THEN salInfo:=r_caseTest.SAL*1.2;
         end case;
          update emp1 set SAL=salInfo where current of crs_caseTest;
        end loop;
end;

--13:对每位员工的薪水进行判断,如果该员工薪水高于其所在部门的平均薪水,则将其薪水减50元,输出更新前后的薪水,员工姓名,所在部门编号。
--AVG([distinct|all] expr) over (analytic_clause)
---作用:
--按照analytic_clause中的规则求分组平均值。
  --分析函数语法:
  --FUNCTION_NAME(<argument>,<argument>...)
  --OVER
  --(<Partition-Clause><Order-by-Clause><Windowing Clause>)
     --PARTITION子句
     --按照表达式分区(就是分组),如果省略了分区子句,则全部的结果集被看作是一个单一的组
     select * from emp1
DECLARE
     CURSOR 
     crs_testAvg
     IS
     select EMPNO,ENAME,JOB,SAL,DEPNO,AVG(SAL) OVER (PARTITION BY DEPNO ) AS DEP_AVG
     FROM EMP1 for update of SAL;
     r_testAvg crs_testAvg%rowtype;
     salInfo emp1.sal%type;
     begin
     for r_testAvg in crs_testAvg loop
     if r_testAvg.SAL>r_testAvg.DEP_AVG then
     salInfo:=r_testAvg.SAL-50;
     end if;
     update emp1 set SAL=salInfo where current of crs_testAvg;
     end loop;
end;


centos7 清理缓存 一、系统环境 系统版本 CentOS Linux release 7.3.1611 (Core) 内核版本 Linux xx-user 3.10.0-514.el7.x86_64 #1 SMP 背景 服务器分配的账号是普通用户,只能执行sudo命令 二、缓存查看及基本概念 查看内存使用情况 [user01@xx-user ~]$ free -h total used free shared buff/cache availabl 阅读详情

相关推荐

Android无线调试:adb tcpip连接实战指南

本文详细介绍了Android无线调试的完整流程,重点讲解如何使用adb tcpip命令通过Wi-Fi连接设备,摆脱数据线束缚。涵盖环境配置、连接实战、稳定性优化及常见问题排查,帮助开发者高效实现无线adb调试,提升工作效率。

pink的博客 724

oracle 游标使用

--本文来自:http://www.cnblogs.com/sc-xx/archive/2011/12/03/2275084.html -- 声明游标;CURSOR cursor_name IS select_statement --For 循环游标 --(1)定义游标 --(2)定义游标变量 --(3)使用for循环来使用这个游标 declare --类型定义 cursor c

DJL296336953的专栏 707

基于Java+SpringBoot+Vue的中小企业设备管理系统的设计与开发(源码+lw+部署文档+讲解等)

💗博主介绍:✌新人博主,工作经验两年+、专注于Java、小程序技术领域和毕业项目实战✌💗🌟文末获取源码+数据库🌟

2301_76502068的博客 1385

Oracle管理知识点

保留策略:为了提高恢复的速度,在计算机内部的FRA磁盘上保留一部分,并且设置一个期限。 恢复目录:保存RMAN的数据资料档案。 完全备份(full):备份所有数据文件中有数据的块。 增量备份(incremental):必须以完全备份作为0级增量备份,并且在每一个期间做1级增量备份。(备份从上一次备份以来修改过的块) (ADR_ home)下的trace:保存预警日志和跟踪文件 external tables:外部表,只能查询,不能修改。 Oracle数据库文件存储结构的8中文件类型:数据文件,控

weixin_72843193的博客 610

CentOS 环境 sngrep 安装及使用

在呼叫中心类应用开发过程中,经常需要对 SIP 信令抓包,分析排查问题。通常抓包的工具非常多样,如 Wireshark、tcpdump、ngrep 等都是可选项,但是针对 SIP 信令的抓包,sngrep 则更为好用。因为 sngrep 不仅提供了图形界面,还会将一通会话的 SIP 信令关联汇总,非常直观执行以下命令下载 的相关依赖库 1.2 添加 sngrep 的源并导入 执行下面的命令新增一个源仓库配置文件 然后在该文件中写入以下配置内容 执行命令导入源仓库的公钥 1.3 安装 sngrep

谈谈1974 8153

Windows11上CUDA 12.3配PyTorch踩坑记:一条官网命令救了我的GPU加速

本文详细介绍了在Windows 11上配置CUDA 12.3与PyTorch的完整指南,包括环境准备、安装要点、兼容性解决方案和性能验证。通过官方推荐的conda命令和实用技巧,帮助开发者解决常见问题,实现高效的GPU加速,提升深度学习开发效率。

weixin_42528974的博客 109

确定Oracle参数修改后是否需要重启数据库

一般情况下,需要指定scope=spfile的参数都要重启后才能生效。 v$parameter视图的ISSYS_MODIFIABLE字段,会指明该参数能否使用ALTER SYSTEM命令进行修改,并且什么时候生效。 该列的可能取值有3种: IMMEDIATE:可以使用ALTER SYSTEM修改,立即生效。 DEFERRED:可以使用ALTER SYSTEM修改,后面的session中生效。 FA...

andyguan01_2的博客 5770

YOLOv26详解 | 一文带你从代码角度深入理解ultralytics最新作品yolov26的创新 | 训练、推理、验证、导出 (附网络结构图PPT可用,全网最全)

YOLOv26带来多项创新:1)采用双检测头机制(One-to-Many和One-to-One)实现端到端无NMS推理;2)移除DFL简化边界框回归;3)引入ProgLoss+STAL优化小目标检测;4)使用MuSGD优化器提升训练稳定性。网络结构方面,SPPF模块增加shortcut连接,并在C3k2中引入PSABlock注意力机制。该版本更注重实际部署,简化了推理流程,提升硬件兼容性。教程涵盖模型训练、验证、推理及导出全流程,支持多种格式转换如ONNX、TensorRT等,适合工业应用场景。

Snu77的博客 4085

oralce 游标

游标的概念:     游标是SQL的一个内存工作区,由系统或用户以变量的形式定义。游标的作用就是用于临时存储从数据库中提取的数据块。在某些情况下,需要把数据从存放在磁盘的表中调到计算机内存中进行处理,最后将处理结果显示出来或最终写回数据库。这样数据处理的速度才会提高,否则频繁的磁盘数据交换会降低效率。 游标有两种类型:显式游标和隐式游标。在前述程序中用到的SELECT...INTO...查询语句,...

renwenzhi的博客 1371

C语言试题四之计算并输出3到n之间所有素数的平方根之和

1、题目 请编写函数function,它的功能是:计算并输出3到n之间所有素数的平方根之和 例子:若我们main函数从键盘给n输入5之后,我们需要输出结果为3.968119 输入值n的要求:正整数n, 要求小于100。 2、部分函数说明 C 库函数 double sqrt(double x) 返回 x 的平方根 3、源代码实现 #include <stdio.h> #...

码莎拉蒂 7238

学Simulink--基于机器人与自动化系统的场景实例:六自由度机械臂的逆运动学控制仿真

摘要:本文详细介绍了在Simulink中实现六自由度机械臂逆运动学控制的仿真方法。通过构建包含机械臂模型、路径规划器、逆运动学求解器和控制器等模块的系统,利用MATLAB Robotics工具箱进行建模。文章逐步讲解了从模型创建、轨迹规划、逆运动学求解到控制器设计的完整流程,并提供了性能评估标准。该方法能有效验证逆运动学算法,优化机械臂控制策略,提高操作精度和效率,为机器人自动化系统开发提供实用参考。

xiaoheshang_123的博客 231

oracle用游标,Oracle游标使用全解

这个lt;Oracle 游标使用全解gt;文档几乎包含了Oracle游标使用的方方面面,全部通过了测试这个文档几乎包含了Oracle游标使用的方方面面,全部通过了测试-- 声明游标;CURSOR cursor_name IS select_statement--For 循环游标--(1)定义游标--(2)定义游标变量--(3)使用for循环来使用这个游标declare--类型定义cursor c_...

weixin_32279911的博客 297

Buck电源设计常见的一些问题(一)半桥栅极驱动芯片共性失效问题

半桥驱动芯片主要用在器件可应用于电信,数据通信,便携式存储或更低电压系统中的电源转换器,半桥、全桥、推挽、同步降压,正激变换器和同步整流器等方面。当然难免会遇到不少问题。基本上我们在产品开发的过程中都遇到过栅极驱动芯片坏掉的情况,所以找了一些资料,学习学习。也查找查找原因。

小幽余生不加糖 2373

Oracle游标使用全解

游标: 定义 ①从表中检索出结果集,从中每次指向一条记录进行交互的机制。 ②关系数据库中的操作是在完整的行集合上执行的。 由SELECT 语句返回的行集合包括满足该语句的WHERE 子句所列条件的所有行。由该语句返回完整的行集合叫做结果集。 游标是通过游标库来实现的。游标库是常常作为数据库系统或数据访问API 的一部分而得以实现的软件。

jeathenzhang的专栏 1万+

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

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

Oracle 游标使用全解

Oracle 游标使用全解 这个文档几乎包含了oracle游标使用的方方面面,全部通过了测试 -- 声明游标;CURSOR cursor_name IS select_statement --For 循环游标 --(1)定义游标 --(2)定义游标变量 --(3)使用for循环来使用这个游标declare --类型定义 cursor c_j

allen_wang_power的博客 339

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

oracle游标使用全解

-- 声明游标;CURSOR cursor_name IS select_statement --For 循环游标 --(1)定义游标 --(2)定义游标变量 --(3)使用for循环来使用这个游标 declare --类型定义 cursor c_job is select empno,ename,job,sal from e

Fight for Dignitity & Responsibility 的专栏 818

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

上一篇: 计数排序
下一篇: 用java解压缩zip和rar的工具类
Coder_Jiang
博客等级 码龄14年 28粉丝 8原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值