测试J2EE Web Services

如何测试webservice接口 看过网上很多对Web Service的解释,有些文章写得通俗易懂,但是缺少深度解读;有的文章图文并茂,但是没有现成案例;有的文章非常详细,但是没有直观感受。于是,我想从测试一个web service接口的角度,写一篇比较系统的文章,来进一步认识web service。首先要知道什么是Service,才能理解 Web Service。服务(Service)是计算机提供的某种功能,在以前的计算机中,通常以后台程序(Daemon)的形式存在。比如,在计算机中可以安装MySQL服务,提供访问数据库的功能;在计算机 阅读详情
标题:测试J2EE Web Services 浏览次数: 46 时间:2004-08-31
作者:Abhijit Patil 和 Seetharam Param


我们已经了解了很多关于Web Services开发方面的知识,而对于Web Services测试所面临的挑战却知之甚少。本文将阐述对Web Services功能性和互用性的测试。本文同时也指出了与传统测试模式相比Web Services测试所面临的挑战。本文的目标读者是开发人员、测试人员以及那些对Web Services的技术知识或工作方式没有深入了解的项目经理。同时本文假设读者已经很熟悉Web Services的基本知识。

下载作者提供的与本文相关的文件

以下所述及的示例的环境由WebLogic Server 8.1和Microsoft Windows .Net构成,二者所用操作系统均为Windows 2000。

挑战

测试Web Services的有效性、性能、可伸缩性、可靠性以及安全性时所面临的主要挑战是 Web Services的分布性。

为了使完整的Web Services能够实现预期的功能,就要求客户端和服务都要满足一系列的要求。接口必须在其WSDL文档中正确描述出来,消息必须遵守传输协议规范(如HTTP1.1)和消息协议(如SOAP 1.1)。同时消息必须遵守描述该服务的WSDL文档中的契约,要求同时考虑到消息的内容和传输层的绑定。加上综合的安全条款、互操作性问题、UDDI注册要求以及一定负载下的性能需求,就很容易发现为什么网络测试不是无足轻重的事情。

Web Services组件可由多个利益相关者来共同构建和部署。因此,测试这些组件过程中会发现确定代码质量、可用性等都有很大的难度。Web Services的标准是简单的,数据驱动的,并且共享一个公共的基于XML的基础。传统的测试工具可能不足以有效地测试这些标准。而且GUI自动化工具也不足以有效地测试Web Services的接口点和消息格式。

功能测试

该测试的目标相当直观易懂:确保服务器能够对给定的请求发送正确的响应。然而,由于Web Services的复杂性,该任务原非想象的那么简单。对于大多数的Web Services而言,它不可能精确预见客户端会发来什么类型的请求。枚举所有可能的请求并不切实可行,因为可能输入的空间要么是没有边界,要么就是无穷大。因此,验证服务器是否能处理大范围的请求类型和参数是极其重要的。

  public boolean execute(String action, String symbol, int quantity)

  throws javax.xml.soap.SOAPException{

     Detail detail = null;

     detail = SOAPFactory.newInstance().createDetail();

     detail.addChildElement( "Stock Trade" ).addTextNode( "failed" );

      System.out.println("execute() in webservices.stock.trade webservice has been invoked

      with following arguments:: action:" + action +

      " symbol:" + symbol + " quantity:" + quantity);

      if(action == null) {

        throw new SOAPFaultException(new QName( "http://StockTrade/execute", "ServerFailed" ),

                                                "action parameter is null.",

                                                null,

                                                detail);

      }

      if(symbol == null) {

        throw new SOAPFaultException(new QName( "http://StockTrade/execute", "ServerFailed" ),

                                                "symbol parameter is null.",

                                                null,

                                                detail);

   }

      if(action.equalsIgnoreCase("BUY"))

        System.out.println("BUYING quantity: "+ quantity + " of symbol:" + symbol);

        // Invoke method to execute trade here.

      else if(action.equalsIgnoreCase("SELL"))

        System.out.println("SELLING quantity: "+ quantity + " of symbol:" + symbol);

        // Invoke method to execute trade here.

      else

      {

        System.out.println("INVALID action: "+ action);

        throw new SOAPFaultException(new QName( "http://StockTrade/execute", "ServerFailed" ),

                                                "Invalid Action:" + action,

                                                null,

                                                detail);

      }

      return true;

    }

代码摘录:Stock Trade Web Services

该段摘录的代码是Stock Trade Web Services的“execute()”方法的实现代码。该方法首先验证输入参数的有效性,验证成功才执行功能。举例说明,如果参数action是空值,它就会抛出一个SoapFaultException异常,用faultstring参数(第二个参数)说明造成异常的原因。为了举例说明,在对参数symbol进行相似的验证之后,Web Services给出了处理机。在实际的情况下,商业逻辑应该在此位置中实现:

  try{

       // Setup the global JAXM message factory

       System.setProperty("javax.xml.soap.MessageFactory",

         "weblogic.webservice.core.soap.MessageFactoryImpl");

       // Setup the global JAX-RPC service factory

       System.setProperty( "javax.xml.rpc.ServiceFactory",

         "weblogic.webservice.core.rpc.ServiceFactoryImpl");

       StockTrade_Impl ws = new StockTrade_Impl();

       StockTradePort port  = ws.getStockTradePort();

       boolean returnVal = port.execute(action, symbol, quantity);

       System.out.println("The webservice got back the following result:" + returnVal);

      }catch(Exception e) {

      }

代码摘录:Web Services的客户端

上面的一段代码描述了测试客户端如何激活前面讨论的Stock Trade Web Services,该例子使用了JAX-RPC API(JAX远程处理应用程序接口函数),并且假设在读者的CLASSPATH中已经含有了必要的BEA提供的JAR文件。这是一个静态实现,在这里可获得一个stub实现的实例。获得stub实现后,Web Services的“execute”方法就会被激活。

互操作性测试

SOAP和Web Services的承诺之一就是互操作性。就是两个应用系统可以自动交互而不需要人为的介入。Web Services未来成功的关键就在于互操作性。

Web Services互操作性测试套件的目标应针对于测试以下方面:

·                 服务器分析客户端的SOAP包的能力。

·                 服务器对包中所含的已编码参数进行反串行化的能力。

·                 客户端对由服务器作为响应发送而来的SOAP包进行分析的能力。

·                 客户端对从服务器发回的已编码参数进行反串行化的能力。

测试模式

对于一个WLS客户和.NET Web Services:

·                 用Microsoft Visual Studio在目录/InetPub/wwwroot/DotNetServices/下创建一个.NET Web Services。

·                 在WLS端,在为DotNetService 提供了WSDL URL后,用WebLlogic clientgen ant task生成一个clientjar。

·                 从testclient,对JAVA Stub进行一次调用。

  WebLogic Server

  .NET Server

  .NET Web Service

  WLS Client

         // STOCK TRADE WEB SERVICE

         // The Stock Trade web service executes a trade and returns result.

          [WebMethod]

          public bool execute(string action, string symbol, int quantity)

          {

                           if(action == null) {

                             Console.WriteLine("action null");

                        return false;

                                         }

                   if(symbol == null) {

                           Console.WriteLine("symbol null");

                          return false;

                                         }

                    if(action.Equals("BUY"))

                            Console.WriteLine("BUYING quantity: "+ quantity + " of symbol:" + symbol);

                    else if(action.Equals("SELL"))

                    Console.WriteLine("SELLING quantity: "+ quantity + " of symbol:" + symbol);

                             else {

                    Console.WriteLine("INVALID action: "+ action);

                    return false;

                                         }              

                             return true;

                                }

代码摘录:.NET Web Services

上面摘录的一段代码是Stock Trade Web Services,它是前面所设计的WLS Web Services的.NET版。它用与JAVA非常相似的C#语言编写。文件名是“StockTrade.asmx.cs”。

代码编写完成后,在WebLogic服务器上部署WLS客户程序,在.NET框架上部署.NET Web Services,验证客户端是否能调用Web Services。

.NET客户端和WLS Web 服务器端

·                 创建一个WLS Web Services(EAR文件)

·                 使用WLS Web 服务WSDL并通过运行wsdl.exe生成一个.NetClient Stub。这一过程将生成一个.cs文件,该文件包含对应于WSDL提供的Web Services的方法定义。

·                 另外一步是在Stub中定义一个新的构造函数,并将WSL URL作为一个参数。这一步是必须的,因为wsdl.exe所生成的Stub在缺省情况下指向USDL URL中的本地主机。

·                 创建一个.NetClient 类(另外一个.cs文件),该类实际上以WSDL URL作为构造函数参数。该类是一个代理类,它含有与Stub中所定义的相同的方法。.Net客户首先对Stub类进行了实例化,然后将方法的调用委托到Stub。

  .NET Server

  .Net Client

  WebLogic Server

  WLS Web Service

  using System;

  namespace interop

  {

                /// <summary>

                /// Client for StockTrade web service

                /// </summary>

                public class StockTradeClient

                {

                                public StockTradeClient()

                                {

                                        //

                                        // TODO: Add constructor logic here

                                        //

                                }

                static void Main()

                {

                                string action = "BUY";

                string symbol = "BEAS";

                int quantity = 100;

                StockTradeService stService = new StockTradeService();

                Console.WriteLine("Stock Trade Service: ");

                bool result = stService.execute(action,symbol, quantity);

                Console.Write("Result of Stock Trade: ");

                Console.WriteLine(result.ToString());

                                }

                }

  }

代码摘录:.NET客户端

上面摘录的的一段代码是对应于我们前面创建的Stock Trade Web Services的.NET客户端代码,该段代码是用与JAVA语言极为相似的C#语言开发的。文件名是“StockTradeClient.cs”。

代码编写完成后,在.NET框架上部署.NET客户端,并且在WebLogic Server上部署WLS Web Services,验证客户端是否能正确调用Web Services。

下面的就是在WebLogic Server中显示的日志的格式:

  SELLING quantity: 300 of symbol:IBM

  execute() in webservices.stock.trade webservice has been invoked with following

  arguments:: action:SELL123 symbol:IBM quantity:300

  INVALID action: SELL123

  execute() in webservices.stock.trade webservice has been invoked with following

  arguments:: action:SELL symbol:IBM quantity:300

  SELLING quantity: 300 of symbol:IBM

  execute() in webservices.stock.trade webservice has been invoked with following

  arguments:: action:SELL123 symbol:IBM quantity:300

  INVALID action: SELL123


结束语

通过将所讨论的测试方法集成到 Web 服务开发过程中,我们就可以确保Web Services服务器能够良好处理可能类型和数量的客户端请求,而且Web Services的客户端也能正确地访问和检索服务所提供的任何数据。

您可以从开发流程中的任何一点开始实施所讨论的方法,但如果您较早的开始测试,那么您防止错误以及发现错误的能力就强。通常,错误发现得越早,其解决就越早,而且也越有可能避免因创建与有问题模块交互的代码或组件而在不经意中使问题变得更为糟糕的情况,也越有可能避免在其他服务器或者客户中重用有问题的模块。

 

spring mvc搭建web services 问题背景        这两日在处理上司交给的任务的时候接触到了web services,感觉这个跨越语言还有环境的接口调用方式真的是非常之优雅,于是就想着自己能不能试着实现一下。技术选型&&准备        在技术的选型上初期的话遇到了比较多的问题,也看到了网上非常多的技术方案,在茫茫的信息流中还是看到了一款非常适合我的方案,那就是spring mvc。        当然,第一件需要我们做的事 阅读详情

相关推荐

信息系统集成专业技术

考试大纲 1、系统集成:

专注于计算机研发知识和资讯分享 1万+

调用webservice报错。

自己部署了webservice, 以前调用一直没问题, 前两日服务器中毒,重装系统,。 网站什么的都正常,但是发现webservice不能调用,报错!; 错误: System.InvalidOperationException: Unable to generate a temporary class(result=1). error CS2001: Source file &#

柒柒捌捌。 2608

【软考】系统集成项目管理工程师(三)系统集成专业技术知识

软考中级——系统集成项目管理工程师备考干货第三章:系统集成专业技术知识。

商务合作 | 共同学习 | 携手共进 9万+

对接webservice接口时报错:发送方和接收方 Action 不匹配

s:Envelope xmlns:s=“http://schemas.xmlsoap.org/soap/envelope/”>a:ActionNotSupported由于 ContractFilter 在 EndpointDispatcher 不匹配,因此 Action 为“”的消息无法在接收方处理。这可能是由于协定不匹配(发送方和接收方 Action 不匹配)或发送方和接收方绑定/安全不匹配。

四条眉毛的陆小凤 1425

实现webServices接口调用demo

java使用xfire实现webServices接口调用(包括实现内部访问以及外部访问的方式)

webService接口测试工具

非常简单有效的webservice 接口测试工具,解压后,只需输入命令:java -jar wsCaller.jar就可以运行jar包了

WebService 简介和入门 Demo

目录简介WebService 开发规范SOAP 协议wsdl 说明书UDDI面向服务架构 SOAJAXWS Quick Start服务端客户端通过配置日志拦截器查看 SOAP 协议内容 简介 WebService 即 web 服务,它是一种跨语言和跨操作系统平台的远程调用技术,适用于不同系统不同平台的数据交互传递。 Java 中一共有三种 WebService 规范,分别是 JAX-WS(基于W...

weixin_43994677的博客 381

webservice的一个测试例子

webservice的一个测试例子,为了方便以后使用,在此存储一下

xfire发布webservice服务

JavaEE平台从1.3版本开始就完整地支持Web服务,包括调用和发布Web服务两部分。为了让Java应用程序获得访问和发布Web服务的能力,SUN定义了一系列相关的API标准,包括SAAJ、JAXB、JAX-RPC和最新的JAX- WS。 SAAJ(SOAP with Attachments API for Java)已经完整地实现了SOAP协议,可以直接使用SAAJ实现Web服务的底层传...

xuyuanshu123的博客 368

科研指南:IEEE期刊LaTeX/Word模板下载与使用全解析

本文详细解析了IEEE期刊LaTeX/Word模板的下载与使用技巧,帮助科研人员高效完成论文排版。从官方模板获取入口到LaTeX文档结构配置,再到Word样式管理与常见问题解决方案,全面覆盖投稿准备的关键步骤。特别针对数学公式、参考文献和图片处理等难点提供实用建议,助力学术写作规范化。

weixin_28396629的博客 566

[代码开源]基于DistFlow的IEEE33和IEEE69节点最优潮流模型(OPF)实现与性能分析

本文详细介绍了基于DistFlow的IEEE33和IEEE69节点最优潮流模型(OPF)的实现与性能分析。通过代码开源,展示了如何从零搭建电力系统优化模型,解决配电网中的发电成本最小化问题。文章涵盖数据准备、模型实现细节、性能优化建议及常见问题解答,为电力系统研究者提供实用参考。

weixin_29103191的博客 707

AXIS2发布WebService服务示例(Eclipse+AXIS)

我们将Web Service发布在Tomcat或者其他应用服务器上后,有两种方法可以调用该Web Service:       1、通过浏览器调用,返回规范的XML文件       2、通过客户端程序调用,返回结果可自定义格式  接下来,我利用Eclipse J2EE作为开发工具,演示一个Axis调用WebService的简单示例  步骤如下:           

杨杨得懿的博客 501

AI产品经理必备:Agent评测维度、指标与工程化落地指南

随着大模型从单轮问答走向复杂的Agent应用,如何科学地评测一个Agent是否真正“办成了事”,成为AI产品经理必须掌握的核心能力。与传统大模型评测关注回答质量不同,Agent评测需要综合评估任务规划、工具调用、多轮对话一致性以及失败自愈等行为。任务完成率与工具调用成功率是最关键的两个量化指标,同时还需关注延迟与Token成本等工程约束。在实际落地中,评测集的设计要覆盖业务主流程与边界场景,并通过批量回归测试与版本对比,为产品选型、算法迭代和上线决策提供数据支持。本文系统拆解了Agent评测的完整流程,帮助

weixin_29057163的博客 342

用Web Services整合.NET和J2EE

互用性(Interoperability)问题说起来容易但通常实现起来却比较困难。尽管Web service曾承诺要提供最佳的解决方案来衔接基于.NET和J2EE的应用程序,但其过程却并不简单。我们发现在使用SOAPBuilders和Web Services Interoperability Demo (WSID) 时还需要考虑许多问题。近期发布的Web Services Interoperabi

ddarkelf的专栏 1417

【经验&技巧】DDR仿真中的挑战与解决方案

由于DDR的数据总线具备双向数据传输功能,需要对读写模式进行独立仿真环境的创建,并且分为连续和突发模式,再加之有单端和差分信号、有数据总线和地址总线,需要在数据传输过程中额外注意串扰的影响,并选择合适的驱动和负载以找寻设计裕量与串扰强度之间的平衡,因此,实际操作步骤和分析过程还是较为繁琐耗时的,需要设计者具有足够的耐心。

一只豌豆象的博客 1643

【腾讯小龙虾WorkBuddy专栏05】深度解析WorkBuddy连接器(Connector)

深度解析WorkBuddy连接器(Connector)

AI人人懂 1308

用JAVA开发程序或web services服务环境搭建

        我做过简单的java 的web services程序,主要是JDK、MyEclipse、Tomcat服务器就可以啦。////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

zhoubl668的专栏:远帆,梦之帆! 4397

《【一看就会】Autoware.universe的“规划”部分源码梳理》系列文章目录(持续更新中)

第零章:Planning综述 第一章:【一】全局路径生成模块——mission_planner 第二章:【二】路径行为规划模块——behavior_path_planner第一部分——behavior_path_planner模块 第三章:【二】路径行为规划模块——behavior_path_planner第二部分——behavior_path_planner_common模块(1) 第四章:【二】路径行为规划模块——behavior_path_planner第三部分——behavior_path_plan

weixin_48386130的博客 2339

J2EE搭建WebServices开发环境

需要用到的软件: ①               JDK 软件版本:jdk-6u24-windows-i586.exe 下载地址:http://www.oracle.com/technetwork/java/javase/downloads/index.html

AndYou Studio 588

7.12真题华为OD机试真题 新系统 - 字符串压缩编码 (Java/Py/C/C++/Js/Go)

7.12真题华为OD机试真题 新系统 - 字符串压缩编码 (Java/Py/C/C++/Js/Go)

算法大师! 836

Codex入门00-初识神器(小白入门:到底什么是Codex CLI,和ChatGPT写代码有什么不同?)

OpenAI Codex CLI 是 OpenAI 于2025年推出的终端原生AI编程代理,不是在网页里聊天写代码,而是直接在你的终端里自主读代码、改文件、跑命令。它拥有三种安全模式、/goal 持久化任务、云端沙箱执行等独特能力。本文从零介绍 Codex CLI 的核心概念、与 ChatGPT 写代码的本质区别、典型使用场景和费用说明,让你全面认识这个改变开发方式的神器。

yueyeguzhuo的专栏 302

Spring Framework(2)-Spring与开发模式演进

点击查看更多Spring文章 目录 一、 JavaEE开发模式的演变 1.1、Model1时代 1.2、Model2时代 二、Spring:JavaEE开发者的春天到来 2.1、Spring如何通过IOC来达到解耦合的目的? 2.2、那么,怎么理解控制反转和依赖注入之间的关系? 2.3、依赖注入有什么好处? 三、 用Gradle构建Spring应用 3.1、使用Idea或者Ec...

BoringError的博客 4800

IDEA的使用指南

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

用Web Services来整合.NET和J2EE

互用性(Interoperability)问题说起来容易但通常实现起来却比较困难。尽管Web service曾承诺要提供最佳的解决方案来衔接基于.NET和J2EE的应用程序,但其过程却并不简单。我们发现在使用SOAPBuilders和Web Services Interoperability Demo (WSID) 时还需要考虑许多问题。近期发布的Web Services Interoperabi...

weixin_34221112的博客 143

visio安装包

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

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

上一篇: J2EE 1.4 的新特性
下一篇: SOA 比 Web Services 涵义更广
fraternity_java
博客等级 码龄22年 1粉丝 30原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值