JSP环境基于Session的在线用户统计深入分析

实现Web用户停留时间统计的JavaWeb与JSP教程 JavaWeb是指使用Java技术开发基于浏览器/服务器(B/S)架构的网络应用的平台。JavaWeb的核心包括了Java Servlet、Java Server Pages(JSP)、Java Expression Language和Java WebSocket等技术。自从1990年代中期发展起来,JavaWeb已经成为构建动态网页应用的标准。 阅读详情

JSP环境基于Session的在线用户统计深入分析

JSP作为后起之秀能够在服务器编程环境中占据一定地位,是和它良好支持一系列业界标准
密切相关的。Session就是它提供的基础设施之一。作为一个程序员,你可以不介意具体在
客户端是如何实现,就方便的实现简单的基于session的用户管理。

现在对于处理在线用户,有几种不同的处理方法。

一种是叶面刷新由用户控制,服务器端控制一个超时时间比如30分钟,到了时间之后用户
没有动作就被踢出。这种方法的优点是,如果用户忘了退出,可以防止别人恶意操作。
缺点是,如果你在做一件很耗时间的事情,超过了这个时间限制,submit的时候可能要
再次面临登陆。如果原来的叶面又是强制失效的话,就有可能丢失你做的工作。在实现
的角度来看,这是最简单的,Server端默认实现的就是这样的模式。

另一种方式是,站点采用框架结构,有一个Frame或者隐藏的iframe在不断刷新,这样你
永远不会被踢出,但是服务器端为了判断你是否在线,需要定一个发呆时间,如果超过
这个发呆时间你除了这个自动刷新的叶面外没有刷新其他叶面的话,就认为你已经不在
线了。采取这种方式的典型是xici.net。 他的优点是可以可以利用不断的刷新实现一些
类似server-push的功能,比如网友之间发送消息。

不管哪一种模式,为了实现浏览当前所有的在线用户,还需要做一些额外的工作。
servlet API中没有得到Session列表的API。

可以利用的是Listener. Servlet 2.2和2.3规范在这里略微有一些不一样。
2.2中HttpSessionBindingListener可以实现当一个HTTPSession中的Attribute变化的
时候通知你的类。而2.3中还引入了HttpSessionAttributeListener.鉴于我使用的环境
是Visual age for java 4和JRun server 3.1,他们还不直接支持Servlet 2.3的编程,
这里我用的是HttpSessionBindingListener.

需要做的事情包括做一个新的类来实现HttpSessionBindingListener接口。这个接口有
两个方法:
public void valueBound(HttpSessionBindingEvent event),和
public void valueUnbound(HttpSessionBindingEvent event)。
当你执行Session.addAttribute(String,Object)的时候,如果你已经把一个实现了
HttpSessionBindingListener接口的类加入为Attribute,Session会通知你的类,调用
你的valueBound方法。相反,Session.removeAttribute方法对应的是valueUndound方法。

public class HttpSessionBinding implements javax.servlet.http.HttpSessionBindingListener 
{
	ServletContext application = null;

	public HttpSessionBinding(ServletContext application)
	{
		super();
		if (application ==null)
			throw new IllegalArgumentException("Null application is not accept.");
		
		this.application = application;
		
	}

	public void valueBound(javax.servlet.http.HttpSessionBindingEvent e) 
	{ 
		Vector activeSessions = (Vector) application.getAttribute("activeSessions");
		if (activeSessions == null)
		{
			activeSessions = new Vector();
		}

		JDBCUser sessionUser = (JDBCUser)e.getSession().getAttribute("user");
		if (sessionUser != null)
		{
			activeSessions.add(e.getSession());
		}
		application.setAttribute("activeSessions",activeSessions);
	}

	public void valueUnbound(javax.servlet.http.HttpSessionBindingEvent e) 
	{
		JDBCUser sessionUser = (JDBCUser)e.getSession().getAttribute("user");
		if (sessionUser == null)
		{
			Vector activeSessions = (Vector) application.getAttribute("activeSessions");
			if (activeSessions != null)
			{
				activeSessions.remove(e.getSession().getId());
				application.setAttribute("activeSessions",activeSessions);
			}
		}
	}
}


假设其中的JDBCUser类是一个任意User类。
在执行用户登录时,把User类和HttpSessionBinding类都加入到Session中去。
这样,每次用户登录后,在application中的attribute "activeSessions"这个vector中
都会增加一条记录。
每当session超时,valueUnbound被触发,在这个vector中删去将要被超时的session.

public void login()
throws ACLException,SQLException,IOException
{
	/* get JDBC User Class */
	if (user != null)
	{
		logout();
	}
	{
		// if session time out, or user didn't login, save the target url temporary.

		JDBCUserFactory uf = new JDBCUserFactory();

		if ( (this.request.getParameter("userID")==null) 
			|| (this.request.getParameter("password")==null)  )
		{
			throw new ACLException("Please input a valid userName and password.");
		}
		
		JDBCUser user = 
			(JDBCUser) uf.UserLogin(
				this.request.getParameter("userID"),
				this.request.getParameter("password") );
		user.touchLoginTime();
		this.session.setAttribute("user",user);
		this.session.setAttribute("BindingNotify",new HttpSessionBinding(application));
	}
}


Login的时候,把User和这个BindingNotofy目的的类都加入到session中去。

logout的时候,就要主动在activeSessions这个vector中删去这个session.
public void logout()
throws SQLException,ACLException
{
	if (this.user == null 
		&& this.session.getAttribute("user")==null)
	{
		return;
	}

	Vector activeSessions = (Vector) this.application.getAttribute("activeSessions");
	if (activeSessions != null)
	{
		activeSessions.remove(this.session);
		application.setAttribute("activeSessions",activeSessions);
	}

	java.util.Enumeration e = this.session.getAttributeNames();

	while (e.hasMoreElements())
	{
		String s = (String)e.nextElement();
		this.session.removeAttribute(s);
	}
	this.user.touchLogoutTime();
	this.user = null;
}


这两个函数位于一个HttpSessionManager类中.这个类引用了jsp里面的application全局
对象。
这个类的其他代码和本文无关且相当长,我就不贴出来了。

下面来看看jsp里面怎么用。
假设一个登录用的表单被提交到doLogin.jsp, 表单中包含UserName和password域。

节选部分片段:
<%
	HttpSessionManager hsm = new HttpSessionManager(application,request,response);
	try
	{
		hsm.login();
	}
	catch ( UserNotFoundException e)
	{
		response.sendRedirect("InsufficientPrivilege.jsp?detail=User%20does%20not%20exist.");
		return;
	}
	catch (	InvalidPasswordException e2)
	{	
		response.sendRedirect("InsufficientPrivilege.jsp?detail=Invalid%20Password");
		return;
	}
	catch ( Exception e3)
	{
	%>	Error:<%=e3.toString() %><br>
		Press <a href="login.jsp">Here</a> to relogin.
<%		return;
	}
	response.sendRedirect("index.jsp");
%>


再来看看现在我们怎么得到一个当前在线的用户列表。
<body bgcolor="#FFFFFF">
<table cellspacing="0" cellpadding="0" width="100%">

	<tr >
	  <td style="width:24px">SessionId
	  </td>
	  <td style="width:80px" >User
	  </td>
	  <td style="width:80px" >Login Time
	  </td>
	  <td style="width:80px" >Last access Time
	  </td>
	</tr>
<%
	Vector activeSessions = (Vector) application.getAttribute("activeSessions");
	if (activeSessions == null)
	{
		activeSessions = new Vector();
		application.setAttribute("activeSessions",activeSessions);
	}
	
	Iterator it = activeSessions.iterator();
	while (it.hasNext())
	{
		HttpSession sess = (HttpSession)it.next();
		JDBCUser sessionUser = (JDBCUser)sess.getAttribute("user");
		String userId = (sessionUser!=null)?sessionUser.getUserID():"None";
%>
	<tr>
	  	<td nowrap=''><%= sess.getId() %></td>
	  	<td nowrap=''><%= userId %></td>
	  	<td nowrap=''>
		<%=  BeaconDate.getInstance( new java.util.Date(sess.getCreationTime())).getDateTimeString()%></td>
	  	<td class="<%= stl %>3" nowrap=''>
		<%=  BeaconDate.getInstance( new java.util.Date(sess.getLastAccessedTime())).getDateTimeString()%></td>
	</tr>
<%
	}
%>
</table>
</body>


以上的代码从application中取出activeSessions,并且显示出具体的时间。其中
BeaconDate类假设为格式化时间的类。

这样,我们得到了一个察看在线用户的列表的框架。至于在线用户列表分页等功能,
与本文无关,不予讨论。
这是一个非刷新模型的例子,依赖于session的超时机制。我的同事sonymusic指出很
多时候由于各个厂商思想的不同,这有可能是不可信赖的。考虑到这种需求,需要在
每个叶面刷新的时候都判断当前用户距离上次使用的时间是否超过某一个预定时间值。
这实质上就是自己实现session超时。
如果需要实现刷新模型,就必须使用这种每个叶面进行刷新判断的方法。
jsp中监听器实现在线用户统计 Servlet监听器的概念 各种类型的Servlet事件监听器的使用方法 监听器的配置方法 立即下载

相关推荐

ServletContextListener完成在线人数统计和显示人员列表

ServletContextListener完成在线人数统计和显示人员列表

我用代码教会你(三):Listener监听器实现在线用户统计

你是否想在项目中显示一个在线人数而无从下手??? 你是否想在自己的平台上查看当前登录的用户列表??? 本文通过JSP+Servlet+监听器Listener为你实现,花5分钟一起来看看吧。

u010312671的专栏 5743

Listener单点登录与显示在线用户

Listener单点登录与显示在线用户

监听器实现查看在线用户列表

需求说明 ​ 实现用户登录时,可查看在线用户列表;用户注销时,其信息从用户列表中删除。 实现思路 ​ 我们可以使用监听器来完成,实现3个监听器的接口 /** * ServletContextListener:服务器启动时,将一个集合放入到application域中 * HttpSessionAttributeListener:用户登录时,用户信息会保存到session域中,我们将session域中的信 息保存到application域中 * HttpSessionListener:用户注

哈哈哈 1584

HttpSessionBindingListener获取在线用户数(转)

NULL 博文链接:https://nopainnogain.iteye.com/blog/799596

VSCode玩转STM32:手把手教你配置EIDE插件与OpenOCD调试(附野火DAP配置文件详解)

本文详细介绍了如何在VSCode中配置EIDE插件与OpenOCD进行STM32开发,特别针对野火DAP调试器提供了配置文件详解。从基础环境搭建到深度调试技巧,帮助开发者高效完成STM32项目开发,实现现代化嵌入式开发工作流。

weixin_26905487的博客 563

第七章 监听器listener显示在线用户案例学习心得

前言:这个是我自己的学习笔记,用于加深自己对于java web 理解。 显示在线用户:这个案例主要是统计启动时间、累积访问人数、最大同时在线以及发生的时间、当前用户数以及当前登录的用户数。 这个案例和上一个案例基本类似,利用相关的listener可以实现。 统计信息的类代码如下所示。 1 package hellojava.listener.uti...

weixin_34356138的博客 175

arduino esp8266_Arduino传感器教程 第22章ESP8266 控制 5V 继电器

ESP8266控制5V继电器目录一、NodeMCU二、工作原理本文将使用亚马逊 AlexaEcho 和 ESP8266 控制 5V 继电器。NodeMCUNodeMCU 是一个开源的 IoT 物联网硬件开发板,由于它支持 WIFI 功能且使用方法十分类似 Arduino 开发板,所以近些年获得了越来越多来自全世界的创客朋友们的青睐。NodeMCU 尺寸与 Arduino Nano 类似。...

weixin_39611722的博客 3472

java web笔记之Listener显示在线用户

1.静态属性类 package com.wang.online; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; public class ApplicationConstants { public static

wangxuewei111的专栏 2137

MDB协议中设备级别和选项(Levels and Options)

MDB协议的LEVEL级别介绍

hbstart的博客 945

深度可分离卷积(DepthwiseSeparableConvolution):Depthwise卷积与Pointwise卷积

深度可分离卷积不用多说,在轻量级网络架构方面是一个绕不开的话题,只要接触深度学习多多少少会接触。深度可分离卷积即DepthwiseSeparableConvolution,该卷积将一个常规卷积过程划分成两个完成Depthwise卷积和Pointwise卷积,在保证输出一样时,计算量大大降低。首先来看,一个常规卷积是怎么实现的。其示意图如果我们从通道数变换的角度来看,卷积就是将3通道的tensor变为了4通道的tensor,我们来看看深度可分离卷积是怎么实现通道的变化的。...

xu.hyj 1万+

监听器Listener -,钝化,活化,利用监听器实现简易版 统计网站在线用户功能

思路分析:通过ServletContextListener监听,当Web应用上下文启动时,在ServletContext中添 加一个List集合,用来准备存放在线的用户名;然后,可以通过HttpSessionAttributeListener监 听器,当用户登录成功,把用户名设置到Session中时,同时将用户名存放到ServletContext中的 List列表中;过滤器---解决中文乱码问题-和未登录不能访问主页面。

weixin_62971115的博客 186

CYUSB3065配置CMOS

按照OG02B10的时序电路,在通过SCCB配置CMOS之前,需要三个电源上电,Xshutdown高电平和配置时钟电路。找到手册的第6章SCCB(跟IIC很像),可以看到SCCB的地址与SID引脚有关,这个需要到硬件原理图上确认下。这是Cypress的一个支持MIPI和UVC的模块,有例程支持OV5640,现在要替换替换成OG02B10。寄存器参数需要找到厂家的FAE,由他们提供,OG02B10的资料已经上传。(2)参考得宏的电路,时钟由主控提供,目前程序未实现。这里有两个重要参数需要搞定,摄像头的。

qq_40773212的博客 2981

JSP环境基于Session的在线用户统计深入分析,监听器Listener实现用户在线统计

JSP环境基于Session的在线用户统计深入分析JSP作为后起之秀能够在服务器编程环境中占据一定地位,是和它良好支持一系列业界标准密切相关的。Session就是它提供的基础设施之一。作为一个程序员,你可以不介意具体在客户端是如何实现,就方便的实现简单的基于session的用户管理。现在对于处理在线用户,有几种不同的处理方法。一种是页面刷新由用户控制,服务器端控制一个超时时间比如30分钟,到了时间之后用户没有动作就被踢出。这种方法的优点是,如果用户忘了退出,可以防止别人恶意操作。缺点是,如果你在做一件很耗时

黑K的专栏 552

Temporal Anti-Aliasing(时域抗锯齿TAA)

首先说一下走样:一般分为时域走样(如旋转车轮)和空域走样(锯齿),但在 TAA 技术是采用时域相关叠加混合技术来解决空域走样的问题。 简单看一下空域抗锯齿 (Spatial Anti-Aliasing, SAA)相关技术,最普及的莫过于 MSAA,被各大渲染引擎采用,但是 MSAA 并不适用于延迟渲染 (Deferred Rendering),随之出现了很多基于形态学的后处理抗锯齿技术,如 MLAA,FXAA,SMAA 等(具体看参见图形_反走样技术总结相关介绍),虽然他们表现良好且支持延迟渲染,但是都会面

qq_35312463的博客 1万+

深入解析mSATA与mini-PCIE接口的硬件设计要点

本文深入解析mSATA与mini-PCIE接口的硬件设计要点,涵盖信号定义、电源设计、高速信号处理及PCB布局布线等关键内容。通过实战案例和调试技巧,帮助工程师规避常见设计陷阱,提升电路设计效率,特别适合工业控制和嵌入式系统开发场景。

weixin_28741413的博客 327

JSP利用Session来实现在线用户统计

 JSP对于处理在线用户,有几种不同的处理方法。  一种是页面刷新由用户控制,服务器端控制一个超时时间比如30分钟,到了时间之后用户没有动作就被踢出。这种方法的优点是,如果用户忘了退出,可以防止别人恶意操作。缺点是,如果你在做一件很耗时间的事情,超过了这个时间限制,submit的时候可能要再次面临登陆。如果原来的叶面又是强制失效的话,就有可能丢失你做的工作。在实现的角度来看,这是最简单的,Serv

1201

3.4 ISIS和OSPF之间路由引入

通过以上输出可以看到OSPF的路由引入到了IS-IS中。通过以上输出可以看到ISIS的路由没有传递给OSPF。通过以上输出可以看到OSPF的路由没有传递给ISIS。通过以上输出可以看到ISIS的路由被引入进了OSPF。掌握在IS-IS中引入OSPF路由的方法。掌握在OSPF中引入IS-IS路由的方法。图3-3:ISIS和OSPF之间路由引入。在R3上把ISIS的路由引入到OSPF。OSPF引入外部路由的缺省度量值为1。在R3上把OSPF的路由引入到ISIS。引入的外部路由类型为Type2。

lwljh134的博客 1811

JSP中基于Session的在线用户统计分析

 JSP作为后起之秀能够在服务器编程环境中占据一定地位,是和它良好支持一系列业界标准密切相关的。Session就是它提供的基础设施之一。作为一个程序员,你可以不介意具体在客户端是如何实现,就方便的实现简单的基于session的用户管理。现在对于处理在线用户,有几种不同的处理方法。  一种是页面刷新由用户控制,服务器端控制一个超时时间比如30分钟,到了时间之后用户没有动作就被踢出。这种方法的优点是,

上海夜未眠 931

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

JavaWeb中的Session、SessionListener、在线人数统计

测试环境:Tomcat 5.0.28JavaWeb中的Session 在JavaWeb中使用HttpSession(以下简称session)对象来表示一个会话。 Session的创建(代表会话周期的开始):第一次调用request.getSession()方法时,会创建一个session对象。 Session的销毁(代表会话周期的结束):在某个请求周期内调

CaiKanXP的专栏 2万+

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

上一篇: 深入探讨SQL Server 2000对XML的支持
下一篇: 微软SQL Server 2005的30项顶尖特性
天地客人
博客等级 码龄23年 62粉丝 168原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址