Tomcat类加载,自己看源码

《Tomcat源码解析》Tomcat类加载器 《Tomcat源码解析》Tomcat类加载器 文章目录《Tomcat源码解析》Tomcat类加载器前言一、J2SE类加载器1.1 启动类加载器1.2 扩展类加载器1.3 系统类加载器1.4 代码获取各种类加载器1.5 双亲委派机制1.6 ClassLoader二、Tomcat类加载器三、Web应用类加载器四、Tomcat类加载器源码 前言 一、J2SE类加载器 JVM默认提供了3个类加载器,他们以一种父子树的方式创建,同时使用委派模式确保应用程序可通过自身的类加载器(System)加载所有可见的J 阅读详情

在java本身的类加载器的基础上增加了5个类加载器
在这里插入图片描述

下载tomcat源码:https://tomcat.apache.org/download-90.cgi
找到java/org/apache/catalina/startup/Bootstrap.java
这个是启动类,找到这块,我们来看他的逻辑
main() -> start() -> init() -> initClassLoaders(),依次创建我们的三个类加载器
在这里插入图片描述
看创建类加载器的方法

private ClassLoader createClassLoader(String name, ClassLoader parent)
        throws Exception {
		//得到属性,以common为例,得到common.loader属性,可以在tomcat/conf/catalina.properties中找到
		//common.loader="${catalina.base}/lib","${catalina.base}/lib/*.jar","${catalina.home}/lib","${catalina.home}/lib/*.jar"
        String value = CatalinaProperties.getProperty(name + ".loader");
        if ((value == null) || (value.equals(""))) {
            return parent;
        }
		//下面就是加载tomcat自身字节码文件的逻辑
        value = replace(value);
		//把需要加载的都添加到repositories中
        List<Repository> repositories = new ArrayList<>();

        String[] repositoryPaths = getPaths(value);

        for (String repository : repositoryPaths) {
            // Check for a JAR URL repository
            try {
                @SuppressWarnings("unused")
                URL url = new URL(repository);
                repositories.add(new Repository(repository, RepositoryType.URL));
                continue;
            } catch (MalformedURLException e) {
                // Ignore
            }

            // Local repository
            if (repository.endsWith("*.jar")) {
                repository = repository.substring
                    (0, repository.length() - "*.jar".length());
                repositories.add(new Repository(repository, RepositoryType.GLOB));
            } else if (repository.endsWith(".jar")) {
                repositories.add(new Repository(repository, RepositoryType.JAR));
            } else {
                repositories.add(new Repository(repository, RepositoryType.DIR));
            }
        }
		//传入repositories
        return ClassLoaderFactory.createClassLoader(repositories, parent);
    }

我们接着跳转到ClassLoaderFactory.createClassLoader()方法

   public static ClassLoader createClassLoader(List<Repository> repositories,
                                                final ClassLoader parent)
        throws Exception {

        if (log.isDebugEnabled()) {
            log.debug("Creating new class loader");
        }

        // Construct the "class path" for this class loader
        //set存储不重复的资源
        Set<URL> set = new LinkedHashSet<>();

        if (repositories != null) {
            for (Repository repository : repositories)  {
                if (repository.getType() == RepositoryType.URL) {
                    URL url = buildClassLoaderUrl(repository.getLocation());
                    if (log.isDebugEnabled()) {
                        log.debug("  Including URL " + url);
                    }
                    set.add(url);
                } else if (repository.getType() == RepositoryType.DIR) {
                    File directory = new File(repository.getLocation());
                    directory = directory.getCanonicalFile();
                    if (!validateFile(directory, RepositoryType.DIR)) {
                        continue;
                    }
                    URL url = buildClassLoaderUrl(directory);
                    if (log.isDebugEnabled()) {
                        log.debug("  Including directory " + url);
                    }
                    set.add(url);
                } else if (repository.getType() == RepositoryType.JAR) {
                    File file=new File(repository.getLocation());
                    file = file.getCanonicalFile();
                    if (!validateFile(file, RepositoryType.JAR)) {
                        continue;
                    }
                    URL url = buildClassLoaderUrl(file);
                    if (log.isDebugEnabled()) {
                        log.debug("  Including jar file " + url);
                    }
                    set.add(url);
                } else if (repository.getType() == RepositoryType.GLOB) {
                    File directory=new File(repository.getLocation());
                    directory = directory.getCanonicalFile();
                    if (!validateFile(directory, RepositoryType.GLOB)) {
                        continue;
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("  Including directory glob "
                            + directory.getAbsolutePath());
                    }
                    String filenames[] = directory.list();
                    if (filenames == null) {
                        continue;
                    }
                    for (String s : filenames) {
                        String filename = s.toLowerCase(Locale.ENGLISH);
                        if (!filename.endsWith(".jar")) {
                            continue;
                        }
                        File file = new File(directory, s);
                        file = file.getCanonicalFile();
                        if (!validateFile(file, RepositoryType.JAR)) {
                            continue;
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("    Including glob jar file "
                                    + file.getAbsolutePath());
                        }
                        URL url = buildClassLoaderUrl(file);
                        set.add(url);
                    }
                }
            }
        }

        // Construct the class loader itself
        //根据set生成array
        final URL[] array = set.toArray(new URL[0]);
        if (log.isDebugEnabled()) {
            for (int i = 0; i < array.length; i++) {
                log.debug("  location " + i + " is " + array[i]);
            }
        }

        return AccessController.doPrivileged(
                (PrivilegedAction<URLClassLoader>) () -> {
                    if (parent == null) {
                    	//传入array,生成URLClassLoader
                        return new URLClassLoader(array);
                    } else {
                        return new URLClassLoader(array, parent);
                    }
                });
    }

接着看,我们重点关注ucp这个变量

    public URLClassLoader(URL[] urls, ClassLoader parent) {
        super(parent);
        // this is to make the stack depth consistent with 1.1
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkCreateClassLoader();
        }
        this.acc = AccessController.getContext();
        //我们传入的array最终生成ucp
        ucp = new URLClassPath(urls, acc);
    }

最终在findClass中找到ucp的身影

    protected Class<?> findClass(final String name)
        throws ClassNotFoundException
    {
        final Class<?> result;
        try {
            result = AccessController.doPrivileged(
                new PrivilegedExceptionAction<Class<?>>() {
                    public Class<?> run() throws ClassNotFoundException {
                        String path = name.replace('.', '/').concat(".class");
                        //在这里
                        Resource res = ucp.getResource(path, false);
                        if (res != null) {
                            try {
                                return defineClass(name, res);
                            } catch (IOException e) {
                                throw new ClassNotFoundException(name, e);
                            }
                        } else {
                            return null;
                        }
                    }
                }, acc);
        } catch (java.security.PrivilegedActionException pae) {
            throw (ClassNotFoundException) pae.getException();
        }
        if (result == null) {
            throw new ClassNotFoundException(name);
        }
        return result;
    }

还记得双亲委派吗?
我们分析一下tomcat从运行,到加载commonLoader,catalinaLoader,sharedLoader这三个类的全过程。拿commonLoader举例
首先启动tomcat的bootstrap.java,交给AppClassLoader,委派给ExtClassLoader,再委派给BootStrapLoader,依次返回,最终AppClassLoader加载。然后实例化,执行我们的main方法,最终执行到initClassLoaders()方法,初始化我们的commonLoader,初始化的过程中,会把tomcat自身的资源传入到URLClassLoader类型的commonLoader中。当程序的其他地方使用我们commonLoader的时候会先执行loadClass方法委派给AppClassLoader重复上面步骤,最终执行commonLoader的findClass方法,去加载tomcat的资源。

即,commonLoader,catalinaLoader,sharedLoader没有重写loadClass方法,都没有打破双亲委派规则

我们再看WebAppClassLoader和JasperLoader

public class WebappClassLoader extends WebappClassLoaderBase {

    public WebappClassLoader() {
        super();
    }


    public WebappClassLoader(ClassLoader parent) {
        super(parent);
    }
}

我们看WebappClassLoaderBase中,重写了loadClass
并且JasperLoader中也重写了loadClass
所以二者打破了双亲委派规则

总结:

为什么WebAppClassLoader和JasperLoader要打破双亲委派规则?
1、部署在同一个Tomcat上的两个Web应用所使用的Java类库要相互隔离;
2、部署在同一个Tomcat上的两个Web应用所使用的Java类库要互相共享;
3、保证Tomcat服务器自身的安全不受部署的Web应用程序影响;
4、需要支持JSP页面的热部署和热加载;

加入我们没有打破,那么WebAppClassLoader在加载我们的web应用中的资源的时候,就会先去BootStrapClassLoader中找,再到extClassLoader中去等等,那些是tomcat本身jre中的资源,而不是web的资源,没有起到隔离的效果。加载就乱套了。所以要自定义类加载。

第三章 Tomcat源码分析—类加载与类加载器笔记 一、Tomcat的挑战 Tomcat上可以部署多个项目: Tomcat的一般部署,可以通过多种方式启动一个Tomcat部署多个项目,那么Tomcat在设计时会遇到什么挑战呢? 1)Tomcat运行时需要加载哪些类。 2)Tomcat中的多个项目可能存在相同的类。 3)Tomcat中类加载的挑战。 源码分析彻底弄懂Tomcat的类加载 1、类加载与类加载器 1.1、类加载 类加载:... 阅读详情

相关推荐

深入理解 Tomcat(五)源码剖析Tomcat 启动过程----类加载过程

这是我们深入理解tomcat的第五篇文章,按照我们的思路,这次我们本应该区分析tomcat的连接器组件,但楼主思前想后,觉得连接器组件不能只是纸上谈兵,需要深入源码,但楼主本能的认为我们应该先分析tomcat的启动过程,以能够和我们上一篇文章深入理解 Tomcat(四)Tomcat 类加载器之为何违背双亲委派模型相衔接。因为启动类加载器的核心代码就在启动过程中,所以,我决定先分析tomcat的启动过

ignore 2481

谈谈类加载器!关于类加载器的源码

一、类加载 1.1、在java代码中,类型的加载,连接,初始化过程都是在程序运行期间完成的。 图示: 1.2、类型的加载——这里的类型是指的什么? 答:类型就是指的我们Java源代码通过编译后的class文件。 1.3、类型的来源有哪些? (1)本地磁盘 (2)网络下载,class文件 (3)war,jar下加载,class文件 (4)从专门的数据库中读取,class文件(少见) (5)将java源文件动态编译成class文件 1)典型的就是动态代理,通过运行期生成class文件 2)我们的jsp会被转换成

gg7894125的博客 377

Tomcat 9 源码分析(2)— 类加载体系

Java虚拟机主要类加载器 Bootstrap Loader(启动类加载器):加载lib目录下或者System.getProperty("sun.boot.class.path")、或者-XBootclasspath所指定的路径或jar Extended Loader(扩展类加载器):加载lib\ext目录下或者System.getProperty("java.ext.dirs")所指定的路径或jar。在使用Java运行程序时,也可以指定其搜索路径,例如: java -Djava.ext.dirs=

lanyingchu的博客 312

Tomcat源码分析三:Tomcat启动加载过程(一)的源码解析

Tomcat启动加载过程(一)的源码解析 今天,我将分享用源码的方式讲解Tomcat启动的加载过程,关于Tomcat的架构请参阅《Tomcat源码分析二:先看看Tomcat的整体架构》一文。 先看看应用情况 在《Servlet与Tomcat运行示例》一文中,我详细的记录了Tomcat是如何启动一个Servlet的程序的步骤。其中,第6步骤是启动Tomcat,也就是在windows系统上执行star...

ZhiyouWu的博客 1318

Tomcat源码解读『Tomcat类加载机制』

本篇文章我们来探索一下Tomcat的类加载机制,如果我们搜Tomcat的类加载机制,绝大多数结果都会给出答案——打破双亲委托机制。但是感觉很多文章介绍的都不是很清楚,所以本篇文章就从我的理解上来分析一下Tomcat的类加载机制,希望能讲的明白。 关于JVM类加载机制,我们在之前的文章Java编程拾遗『Java ClassLoader工作机制』已经介绍过,有兴趣的可以去了解一下。 1. Tomcat类加载机制要考虑的问题 Tomcat作为Servlet容器,它负责加载我们的Servlet类,此外它还负.

卓立的博客 1879

张量积曲面:数学原理与Python实现

Suv∑i0m∑j0nPij⋅Bipu⋅BjqvSuvi0∑m​j0∑n​Pij​⋅Bip​u⋅Bjq​v其中PijP_{i,j}Pij​是控制点网格,BipuB_i^p(u)Bip​u和BjqvB_j^q(v)Bjq​v是基函数,分别沿uuu和vvv方向定义。

T20151470的博客 1168

Tomcat源码:启动类Bootstrap与Catalina的加载

本文开始我们将会介绍tomcat的源码,整个流程会按照tomcat的启动顺序来开展,在此之前建议先阅读下前文理清servlet与servlet容器之间的关系。传送门在tomcat的bin目录下有两个启动tomcat的文件, 一个是startup.bat, 它用于windows环境下启动tomcat;另一个是startup.sh, 它用于linux环境下tomcat的启动. 两个文件中的逻辑是一样的, 我们只分析其中的startup.bat。

CRUD工程师 1479

51单片机IAP技术详解:从原理到实战,实现远程程序自更新

在嵌入式系统开发中,程序更新是产品维护和功能迭代的核心需求。传统方式依赖外部烧录器,操作繁琐且无法远程进行。IAP(在应用中编程)技术则从原理层面解决了这一难题,它允许单片机在运行过程中通过特定接口(如串口)动态修改自身的Flash程序存储器。这项技术的核心价值在于赋予设备远程升级和自主维护的能力,极大地延长了产品生命周期并降低了维护成本。其典型应用场景包括智能家居控制器、工业数据采集模块和远程仪表等部署后不便拆卸的设备。本文以经典的51单片机(如STC89C52)为例,深入剖析IAP的实现,其中Bootl

weixin_29161719的博客 417

Tomcat源码解析系列二:Tomcat类加载机制以及Context的初始化

Bootstrap Loader:加载lib目录下或者System.getProperty(“sun.boot.class.path”)、或者-XBootclasspath所指定的路径或jarExtended Loader:加载lib\ext目录下或者System.getProperty(“java.ext.dirs”) 所指定的 路径或jar。例如:java -Djava.ext.dirs=/projects/testproj/classes HelloWorld。

Running666的博客 1156

OpenCV透视变换实战:5分钟搞定歪斜证件照矫正(附完整代码)

本文详细介绍了如何使用OpenCV的透视变换技术快速矫正歪斜证件照,包含完整的Python代码实现。通过特征检测、坐标计算和矩阵变换三个核心步骤,5分钟内即可将手机拍摄的歪斜图像自动矫正为专业级证件照,大幅提升图像处理效率。

weixin_29094979的博客 497

回归预测 | MATLAB实现SVR(支持向量机回归)K折交叉验证

回归预测 | MATLAB实现SVR(支持向量机回归)K折交叉验证 目录回归预测 | MATLAB实现SVR(支持向量机回归)K折交叉验证基本介绍划分原理留一划分交叉验证K折交叉数据下载程序设计参考资料致谢 基本介绍 在机器学习里,通常来说我们不能将全部用于数据训练模型,否则我们将没有数据集对该模型进行验证,从而评估我们的模型的预测效果。为了解决这一问题,有如下常用的方法: 第一种是最简单的,也是很容易就想到的。我们可以把整个数据集分成两部分,一部分用于训练,一部分用于验证,这也就是我们经常提到的训练集

机器学习之心的博客,关注并私信文章链接,获取对应文章源码和数据。 6390

Tomcat源码解析——类加载机制

在之前的Tomcat启动源码中,简单的介绍了Tomcat的四种类加载器,再复习一遍。类加载器类加载器的结构层次:commonLoader、catalinaLoader、sharedLoader可以在tomcat下的conf/catalina.properties文件中修改。在Tomcat的启动中,一开始就创建了commonLoader、catalinaLoader、sharedLoader类加载器并且加载对应设置的资源。

m0_37914588的博客 1294

从数据到行动:客服运营必分析的8大核心维度

服务运营正从被动响应升级为数据驱动型战略体系。客服中心的海量交互数据能精准反映服务效能、客户体验及运营短板,关键在于实现数据的可视化与可操作化。本文系统剖析了八类核心数据指标:1)客户行为数据(CSAT/NPS/投诉内容);2)通话效率指标(AHT/接通率);3)服务质量(质检体系/情绪识别);4)坐席绩效(FCR/客户评价);5)流程与知识库(转接率/工单时效);6)渠道流量分析;7)异常预警机制;8)成本收益模型。通过构建多维数据分析体系,企业可在客户全生命周期管理中实现服务升级、风险防控与资源

2202_75469062的博客 1410

三. Tomcat源码分析-类加载和类加载器

三. Tomcat源码分析-类加载和类加载器 1. 使用maven构建tomcat源码 1. 下载源码 https://tomcat.apache.org/download-80.cgi 2. 新建catalina-home目录 解压、新建catalina-home目录,同时将目录中的conf和webapps文件夹复制到catalina-home目录中 源码原始目录 新建后 3. 添加pom.xml 需要通过Maven组织文件,因此需要在根目录下创建目录中新建pom.xml文件: <?xml v

努力学习 1254

AD9613操作控制

输出250M时钟给AD9613,过FPGA ILA逻辑分析仪将AD9613采集的两个通道ADC数据250M数据显示出来。其中AD9613输出的是LVDS数据,通过select IO核转为并行数据。 一,搜索IP核:selectIO interface wizad ,并双击配置 配置为input,DDR模式,数据位宽为12bit,IO类型为差分,这里配置的是12对数据差分对。然后配置外部差分时钟。 将tap setting 设置为13,将时钟的边沿对准数据的中间,以免数据出错 二,

wangjie36的博客 4062

ComfyUI整合包、秋叶ComfyUI、Florence节点报错下载并加载Florence2模型No module named ‘timm.layers‘、ComfyUI报错解决

步骤操作1打开2地址栏输入cmd并回车3输入命令:4安装完成后重新打开 ComfyUI,执行工作流,即可解决报错。

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 1276

tomcat类加载-源码解析

上文:tomcat热加载、热部署-源码解析背景继上文,那么你可能跟我开始一样,tomcat的类加载与我们的java有什么区别?是一样的还是有哪些区别?其次tomcat项目怎么隔离?其三tomat如何打破双亲委派机制?相关基础java类如何加载的?这个问题建议阅读我以往的文章,有这个基础会更好了解如下。文章:‍类的加载时机‍jvm的类加载器(classloader)及类的加载过程以前画的图,...

逍遥壮士 739

基于DynamicHead的YOLOv8四头版本改进:面向复杂场景的多目标检测优化【YOLOv8】

YOLOv8的检测头是通过不同尺度的特征层输出检测结果。这些检测头通常包括三个:用于大物体、中等物体和小物体的检测。然而,这种单一结构可能会在复杂场景下失去针对性和灵活性,特别是当多个目标之间差异较大时。为了进一步提升模型在特定目标上的检测性能,DynamicHead的引入为我们提供了一个多检测头的优化方案。本文提出了一种基于DynamicHead的四头版本YOLOv8改进方案,以解决复杂场景下多目标检测的挑战。通过引入四个独立检测头,分别针对不同目标特征进行优化,实现了更灵活的检测结构。

博客 1727

【Tomcat源码分析 】 类加载机制的源码解读

继前文深入剖析双亲委派机制之后,本文将引直接走进具体的代码实现,一探其真正的实现思路。源码阅读Tomcat 启动的起点在于 Bootstrap 类的 main()方法。在 main()方法执行之前,其静态代码块(static{})会率先被执行。因此,我们将首先深入探讨静态代码块的运行机制,然后再分析 main()方法的执行流程。static {// 获取用户目录// 优先从环境变量获取 CATALINA_HOMEif (home!

Json的博客 1273

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

Statistics and Machine Learning Toolbox

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

Tomcat源码分析 (五)----- Tomcat 类加载器

Java虚拟机把描述类的数据从Class文件加载进内存,并对数据进行校验,转换解析和初始化,最终形成可以呗虚拟机直接使用的Java类型,这就是虚拟机的类加载机制。虚拟机设计团队把类加载阶段中的“通过一个类的全限定名来获取描述此类的二进制字节流”这个动作放到Java虚拟机外部去实现,以便让应用程序自己决定如何去获取所需要的类。实现这动作的代码模块成为“类加载器”。从Java虚拟机的角度来说,只存在两种不同类加载器:一种是启动类加载器(Bootstrap ClassLoader)

smart_an的专栏 1328

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Tomcat的类加载体系及Tomcat源码

>>> Java虚拟机规范中提到的主要类加载器:   Bootstrap Loader:加载lib目录下或者System.getProperty(“sun.boot.class.path”)、或者-XBootclasspath所指定的路径或jar。   Extended Loader:加载lib\ext目录下或者System.getProperty(“java.ext.dirs”) 所指定的

ShareUs的专栏 786

Tomcat7.0源码分析——类加载体系

前言 Tomcat遵循J2EE规范,实现了Web容器。很多有关web的书籍和文章都离不开对Tomcat的分析,初学者可以从Tomcat的实现对J2EE有更深入的了解。此外,Tomcat还根据Java虚拟机规范实现了经典的双亲委派模式的类加载体系。本文基于Tomcat7.0的Java源码,对其类加载体系进行分析。 概述 首先简单介绍下Java虚拟机规范中提到的主要类加载器; Bootst

beliefer的博客 1万+

Tomcat源码分析——类加载体系

前言 Tomcat遵循J2EE规范,实现了Web容器。很多有关web的书籍和文章都离不开对Tomcat的分析,初学者可以从Tomcat的实现对J2EE有更深入的了解。此外,Tomcat还根据Java虚拟机规范实现了经典的双亲委派模式的类加载体系。本文基于Tomcat7.0的Java源码,对其类加载体系进行分析。 概述 首先简单介绍下Java虚拟机规范中提...

weixin_33943347的博客 192

Tomcat源码解析(二)---Tomcat中的类加载器

分析tomcat源码首先就要从tomcat的入口(tomcat的main方法)开始,tomcat的main方法在Bootstrap的这个类中,tomcat的启动main方法就在这里边,当jvm加载Bootstrap这个类的时候会执行其静态代码块,在bootstrap中有有一段静态代码块如下(省略了部分代码): static { // Will always be non-null...

TankyZhang的博客 267
上一篇: jvm双亲委派源码,自己看,自己写ClassLoader
下一篇: java并发和锁,自己动手(一)
小健健健
博客等级 码龄8年 101粉丝 68原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址