Understanding Class.forName (二)

Spring AI微服务集成实战:从ChatClient到多模态与AI Agent AI能力正从外部HTTP服务演进为可装配、可治理的微服务原生组件。理解Spring AI的核心抽象——如ChatClient对上下文管理、流式响应、错误语义化和可观测性的封装——是构建高可靠AI链路的前提。它将大模型调用升维为类似数据库连接池的基础设施层,支持动态模型路由、熔断重试与指标埋点。在电商、金融、工业等场景中,该能力可支撑实时物流分析、个性化欢迎语生成、身份证OCR校验等关键业务。本文聚焦Spring AI 2.0在真实微服务架构中的落地实践,涵盖Alibaba多模态集成、VisionChatCl 阅读详情

The Launcher constructor, after constructing both the ExtClassLoader and AppClassLoader, sets the thread context ClassLoader to be the AppClassLoader instance. This means, unless your code (or other code loaded by your application) changes it, the thread’s context ClassLoader is the AppClassLoader instance. This also means that now the AppClassLoader instance is available to Extension classes:

import java.lang.reflect.*;

public class FixedDynamicLoader

{

public static void main(String[] args)

throws Exception

{

// Instead of

// Class toRun = Class.forName(args[0]);

// use:

Thread t = Thread.currentThread();

ClassLoader cl = t.getContextClassLoader();

Class toRun = cl.loadClass(args[0]);

String[] newArgs = scrubArgs(args);

Method mainMethod = findMain(toRun);

mainMethod.invoke(null, new Object[] { newArgs });

}

private static String[] scrubArgs(String[] args)

{

String[] toReturn = new String[args.length-1];

for (int i=1; i<args.length; i++)

{

toReturn[i-1] = args[i].toLowerCase();

}

return toReturn;

}

private static Method findMain(Class clazz)

throws Exception

{

Method[] methods = clazz.getMethods();

for (int i=0; i<methods.length; i++)

{

if (methods[i].getName().equals("main"))

return methods[i];

}

return null;

}

}

After compiling, placing into a .jar and dropping that .jar into the Extensions directory, we achieve success:

> java FixedDynamicLoader Echo ONE TWO THREE

Echo arg0 = one

Echo arg1 = two

Echo arg2 = three

So the short answer is to use the ClassLoader associated with the current Thread to call loadClass to load the class desired, instead of using Class.forName.

 

Those readers familiar with multi-threaded environments may be wondering about Threads created by user-code—what ClassLoader is set to be the context ClassLoader for user-created Threads? A Thread, when created, inherits the context ClassLoader of the Thread that created it, so all Threads, unless modified, will have AppClassLoader set as their context ClassLoader. Use the 3-arg form of Class.forName. Sun introduced a new form of the forName method that takes 3 arguments, instead of just one. In addition to the name of the Class to load, callers pass a boolean parameter indicating whether to initialize the loaded Class or not, and a ClassLoader parameter to load the code through. This method performs the same steps as the 1-arg Class.forName; in fact, the 1-arg version of Class.forName calls directly into the 3-arg version, passing “true” and the caller’s ClassLoader as the second and third parameters, respectively. Class.forName(classname, init_flag, classloader) will load the code “through” the ClassLoader passed to it; crudely put, it functions somewhat similar to the following:

Class forName(String classnm, boolean init, ClassLoader loader)

throws . . .

{

// . . .

loader.loadClass(classnm);

// . . .

}

This is a gross oversimplification, but the point is clear—instead of using the caller’s ClassLoader to do the load, it uses the ClassLoader instance passed in. This now means, to avoid the problem that started this paper, FixedDynamicLoader could also do:

public class FixedDynamicLoader

{

public static void main(String[] args)

throws Exception

{

//Class toRun = Class.forName(args[0]);

Class toRun =

Class.forName(args[0],

true,

ClassLoader.getSystemClassLoader());

String[] newArgs = scrubArgs(args);

Method mainMethod = findMain(toRun);

mainMethod.invoke(null, new Object[] { newArgs });

}

// . . .

}

This code has the advantage of being perhaps a bit more explicit about what the intent of the code is, as opposed to the slightly more obscure use of the Thread’s context ClassLoader. Other (technical) differences between the two are more profound, however. Class.forName vs ClassLoader.loadClass. There are some subtle differences between these two APIs. The method call CL.loadClass(C), where CL is our ClassLoader and C is the name of the class to load, queries the ClassLoader directly for the class by name. This in turn relies on ClassLoader delegation to ask the bootstrap ClassLoader to determine if the class has already been loaded. Conversely, the method call Class.forName(C, false, CL) uses the VM’s internal class resolution mechanism to do the actual loading. Among other things, this allows Class.forName to support the loading of arrays of Classes as a type; for example, calling CL.loadClass(“[C;”) will result in failure, where doing the same with Class.forName(“[C;”, false, CL) will succeed.

Consequences

As with any discussion, there are consequences to each of the solutions set forth within this white paper. Versioning: The 3-arg Class.forName, Thread.getContextClassLoader, and Thread.setContextClassLoader are Java2/JDK1.2 APIs. This means any Java API or class library that wants to remain compatible or usable with JDK 1.1 will not be able to be loaded. Remember, the VM, during its resolution step of classloading (see [4]), will verify that all methods referenced inside of a class actually exist, and will throw an Exception if this is not the case. How, then can code avoid this ClassLoader trap in Java2 code, while remaining compatible with 1.1 code? One solution is to eliminate your JDK 1.1 compatibility requirement. It sounds a bit draconian, but Java2/JDK 1.2 has been out for approximately a year at the time of this writing, Java2/JDK 1.3 is in the final beta stages. More to the point, almost no new development is being done in JDK 1.1 (except for applets, since 1.1 is as far as most browsers have gone in JDK support). However, for many APIs and/or design teams, this is an unacceptable solution. Too many JDK 1.1-based systems exist to simply write off JDK 1.1 environments entirely, and developing a system that fails to work properly in a JDK 1.2 / Java2 environment is simply unthinkable. Fortunately, a convenient middle ground is possible.

Because Java uses a lazy dynamic-loading system (see [2], [4], or [5] for details), classes aren’t loaded into the VM until the last possible moment. This means it’s possible to use a Strategy-pattern approach towards classloading, based on the version of the VM your code is executing within:

package com.javageeks.lang.classloader;

interface VMClassLoader

{

public Class loadClass(String cls)

throws ClassNotFoundException;

}

public class ClassLoaderHelper

Ted Neward

14

{

private static VMClassLoader vmClassLoader;

static

{

String vmVersion = System.getProperty("java.version");

if (vmVersion.startsWith("1.2"))

{

//System.out.println("Loading 1.2 VMClassLoader");

vmClassLoader = new VMClassLoader()

{

public Class loadClass(String cls)

throws ClassNotFoundException

{

Thread t = Thread.currentThread();

ClassLoader cl = t.getContextClassLoader();

return cl.loadClass(cls);

}

};

}

else if (vmVersion.startsWith("1.1") ||

vmVersion.startsWith("1.0"))

{

//System.out.println("Loading 1.1/1.0 VMClassLoader");

vmClassLoader = new VMClassLoader()

{

public Class loadClass(String cls)

throws ClassNotFoundException

{

return Class.forName(cls);

}

};

}

else

{

// ???

}

}

public static Class loadClass(String cls)

throws ClassNotFoundException

{

return vmClassLoader.loadClass(cls);

}

/**

* Test driver.

*/

public static void main(String[] args)

throws Exception

{

//Class toRun = Class.forName(args[0]);

Class toRun =

ClassLoaderHelper.loadClass(args[0]);

String[] newArgs = scrubArgs(args);

java.lang.reflect.Method mainMethod =

findMain(toRun);

mainMethod.invoke(null, new Object[] { newArgs });

Ted Neward

15

}

private static String[] scrubArgs(String[] args)

{

String[] toReturn = new String[args.length-1];

for (int i=1; i<args.length; i++)

{

toReturn[i-1] = args[i].toLowerCase();

}

return toReturn;

}

private static java.lang.reflect.Method findMain(Class clazz)

throws Exception

{

java.lang.reflect.Method[] methods = clazz.getMethods();

for (int i=0; i<methods.length; i++)

{

if (methods[i].getName().equals("main"))

return methods[i];

}

return null;

}

}

The key here is in the static block of the ClassLoaderHelper class. When loaded in a 1.2 VM, an anonymous instance of VMClassLoader is created, which uses the Thread contextClassLoader methods to obtain the ClassLoader and call loadClass. When loaded into a 1.1 (or 1.0, although this is, as of this writing, untested) VM, the anonymous VMClassLoader instance falls back on Class.forName, since 1.1 VMs don’t have the problem described in this paper.

Running this code within a 1.2 VM yields the following:

> java -version

java version "1.2"

Classic VM (build JDK-1.2-V, native threads)

> java ClassLoaderHelper Echo ONE TWO THREE

Loading 1.2 VMClassLoader

Echo arg0 = one

Echo arg1 = two

Echo arg2 = three

Running this code within a 1.1 VM yields the following:

> java -version

java version "1.1.7"

> java ClassLoaderHelper Echo ONE TWO THREE

Loading 1.1/1.0 VMClassLoader

Echo arg0 = one

Echo arg1 = two

Echo arg2 = three

By using ClassLoaderHelper.loadClass instead of Class.forName, code can continue to support both JDK 1.1 and JDK 1.2 (and beyond) VMs without having to maintain two (or more) separate codebases. (ClassLoaderHelper could also be modified to use the 3-arg version of Class.forName instead of the Thread’s context ClassLoader. However, it would require a ClassLoader instance to be passed in, to avoid making the assumption that it should use the system ClassLoader.)  Using Thread.getContextClassLoader relies on the Thread’s context

ClassLoader to be appropriately set. What if the Thread’s current context ClassLoader isn’t the one expected, but is instead set by an arbitrary third-party package (like RMI or JNDI) In fact, there’s not much you can do to prevent this. Because Thread.setContextClassLoader makes a Security check, however, you can take some small comfort in the fact that only those systems that have “setContextClassLoader” permission will be allowed to modify a Thread’s context ClassLoader. Practically speaking, this means in an enterprise system, you can modify your policy file such that only your codebase is permitted to modify the Thread’s context ClassLoader. This doesn’t prevent Sun-sponsored APIs (like RMI, which is “part” of the runtime library, or JNDI, which is part of the runtime library starting in JDK 1.3) from being able to modify it, but at least you can prevent rogue third-parties from doing so.

 Knowing your loading ClassLoader. In order to use the 3-arg form of Class.forName, callers must have the ClassLoader instance they want to load through available to them in order to pass it; under certain circumstances, simply calling ClassLoader.getSystemClassLoader() here will be wildly inappropriate. For example, a Servlet will usually be loaded under its own ClassLoader, and if the Servlet calls Class.forName with the system ClassLoader as the third argument, code loaded under the Servlet’s ClassLoader won’t be found. This situation can arise more commonly than one might expect—many Servlets are bundled together with supporting code directly in the “servlets” directory, placing the supporting code under the Servlet ClassLoader’s domain. Under those circumstances, using the Thread’s context ClassLoader can be the only appropriate parameter; you can either pass it as the third parameter to the 3-arg form of Class.forName, or else call its loadClass method directly. But, as pointed out in the aforementioned point, using it relies on the context ClassLoader being set correctly by the code that loaded your class. It may seem that callers will always know the ClassLoader they should call through. However, keep in mind that the ExtClassLoader/AppClassLoader pair is not the only situation in which ClassLoaders further “up the tree” are going to look to load code further “down” the ClassLoader tree. For example, sophisticated security mechanisms within a Java application might make use of an instance of URLClassLoader to load code on a per-user-role basis; certain parts of the application, however, will be constant, and therefore installed as an Extension. Those constant classes cannot simply assume that the ClassLoader that loaded them will be the correct ClassLoader to pass into Class.forName (it won’t—we’re now right back to the original problem), nor will simply passing ClassLoader.getSystemClassLoader() be correct, either. Instead, they will have to trust that somebody will set the current Thread’s context ClassLoader to be that custom URLClassLoader instance, and use that to dynamically load the code.

Summary

Java2, with the release of JDK 1.2, subtly changed the nature of classloading. When Sun added the “Extens ion” capability to the language/environment, they split the responsibility for loading Extensions code and “Application” (that is, CLASSPATH-based) code into two separate ClassLoaders. Under “normal” circumstances, this change will be invisible to most Java developers, but those working under dynamic-loading systems need to be aware of this change and what it means for them. Many Java developers may believe that the circumstances described in this paper won’t apply to them. “I’m not making use of any of this”, they mutter to themselves. “Why do I care?” It’s a more relevant concern than readers might wish. Several key Java technologies, most notably RMI and JNDI, make use of the Thread context ClassLoaders for precisely this reason—the core classes for both technologies are loaded high up in the CllassLoader tree, but need to be able to load code stored along the CLASSPATH. Worse yet, as more enterprise systems are built under EJB servers, which may well be installed as Extensions, this problem could become more and more common. As Java2 Security becomes more and more well-understood and implemented in Java projects, this issue will again rear its ugly head, since developers will slowly begin to adopt codebase permissions on a per-ClassLoader basis. Multiple ClassLoaders means the potential for code further up the chain looking for code further down the chain, and we’re right back to where we started with all this.

Fortunately, as JDK 1.1 systems slowly phase out, it should become more and more comfortable to use Thread.currentThread().getContextClassLoader().loadClass() or the 3-arg version of Class.forName() directly; until that time; however, the ClassLoaderHelper class should provide a measure of portability across JVM versions for doing dynamic classloading from within an Extension.

Bibliography/Additional Reading

[1] JDK 1.2 documentation bundle. See http://www.javasoft.com for downloading.

[2] << Liang/Bracha OOPSLA paper >>

[3] Java Language Specification.

[4] Java Virtual Machine Specification, 2nd Edition.

[5] Server-Side Java, by Ted Neward. Manning Publishing, Feb 2000.

[6] Personal communication with Peter Jones of Sun Microsystems; used with permission.

Copyright

This paper, and accompanying source code, is copyright © 2000 by Ted Neward. All rights reserved. Usage for any other purpose

than personal or non-commercial education is expressly prohibited without written consent. Code is copywritten under the Lesser

GNU Public License (LGPL). For questions or concerns, contact author.
SpringBoot+Vue+MySQL 高校学科竞赛平台 完整可运行版(源码+文档) 本项目基于SpringBoot+Vue+MySQL构建高校学科竞赛管理平台,覆盖学生、教师、领队教师、管理员四大角色,实现竞赛发布、报名、刷题、评分、公示等全流程闭环管理。系统架构清晰,技术主流,配套完整源码、数据库脚本、万字论文、开题报告、答辩PPT及部署文档,支持一键运行,适用于毕业设计、课程设计及院系二次开发,真正实现“开箱即用”。 阅读详情

相关推荐

Java Class.forName()无法加载类

NULL 博文链接:https://listen-raining.iteye.com/blog/1894456

关于args.length()的作用和一些用法

String args[]都是函数(或叫方法)的参数而已,和普通的方法参数没什么区别,String表示类型,args表示参数名。 表示在调用这个方法的时候需要给这个方法传递一个字符串数组。 而main方法作为程序的入口,给main方法传递参数的操作比较特殊,因为main方法在其他方法之前执行,所以如果给main方法传递参数需要在命令行或者IDE工具中制定,比如说你执行这样的一个程序 p...

weixin_30344131的博客 8216

LinuxCNC---在PC端显示开发板LinuxCNC界面

  今天在调试开发板时,执行开发板上的linuxcnc指令,总是出现如下报错 LINUXCNC - 2.9.0~pre0 application-specific initialization failed: couldn't connect to display "192.168.137.3:1" Error in startup script: invalid command name "image" while executing "image create photo -file $f/$i

中华田园巨龙 3470

Understanding Class.forName (一)

Understanding Class.forNameLoading Classes Dynamically from within ExtensionsAbstractDynamic loading of Java classes at runtime provides tremendous flexibility in the development of enterprise s

Anders小明的Blog 2636

SAP S4 HANA 新资产会计中的平行分类账估值

在资产会计中,我们可以设置使用折旧区域的平行分类账会计 我们需要根据涉及的会计原则定义折旧区域,在我们的方案中,公司 FR01 是一家国际集团的当地分支机构,公司 FR01 需要按照集团会计准则 IFRS 和当地 GAAP 会计准则报告财务报表。过账到 LG 会计原则(分类帐 2L)-->分类账 2L的 150 欧元损失 -->在 IFRS 折旧区域,我们有 100 欧元的收益,在 LG 折旧区域,我们有 150 欧元的损失,使用平行分类账 0L 和 2L,我们能够根据不同的会计原则进行平行估值。

yanzibing99的博客 1328

关于华为高斯数据库出现Invalid or unsupported by client SCRAM mechanisms定位解决的过程

最近公司有个新项目使用的是高斯数据库,因为我们的项目是直接从别的项目组拿来的,配置都是已经配好的,但是在放到正式环境上之后出现报错。起初我们以为是测试和正式的版本不一致,但是结果是版本一致的。最后这个问题搞了我们几个小时,都没法解决。

Curtisjia的博客 3185

InnoDB 内存结构总览:Change Buffer、AHI 与 Log Buffer

本文系统梳理InnoDB内存结构中的ChangeBuffer、Adaptive Hash Index(AHI)与LogBuffer。ChangeBuffer缓存二级索引页不在内存时的变更,减少随机IO,仅在页加载时合并;聚簇索引修改立即执行,因数据本身不可延后。AHI基于高频等值查询自动构建哈希索引,加速定位,仅支持等值操作。LogBuffer为redo log内存缓冲,配合磁盘日志实现崩溃恢复。三者均服务于性能优化,其中ChangeBuffer与AHI共享BufferPool空间,而LogBuffer独立

bksczm的博客 290

SMR实战指南:从GWAS数据到eQTL分析的完整流程

本文提供了基于汇总数据的孟德尔随机化(SMR)实战指南,详细解析了如何从GWAS汇总数据出发,整合eQTL数据,完成从数据准备、BESD格式转换到最终SMR与HEIDI分析的完整流程。文章重点阐述了核心操作步骤、常见避坑技巧与结果解读,旨在帮助遗传学研究者高效掌握这一分析基因表达与复杂性状潜在因果关系的强大工具。

weixin_29246195的博客 1068

V8 机制、手写核心函数与 TypeScript 类型体操

或固定初始化(如数组先定长、对象先给全字段)保持类型与形状稳定;这些都比"换框架"更基础。只能处理纯数据(丢函数、Date、RegExp、循环引用报错)。生产级深拷贝要处理:原始值短路、循环引用、V8(Chrome / Node 的 JS 引擎)不是"解释一行跑一行"那么简单,它用。图:V8 执行流程——解释执行 + 热点优化,优化失败会 Deopt 回退。JS 内存自动管理,但"自动"不等于"不会漏"。是"固定间隔最多执行一次"。手写 Promise 是"懂异步"的试金石。是"停下后才执行最后一次",

qq_38468358的博客 347

简单说说Python中的pip如何换源

【安装包】:pip install 【升级包】:pip install --upgrade 【卸载包】:pip uninstall 【查看已安装的包】:pip list【搜索包】:pip search (注意:pip search功能在pip 10.0.0之后被弃用,建议使用其他方式搜索包,如访问PyPI官网或使用其他搜索引擎)

一捌柒的博客 2668

86 arduino 电机yl_(八)arduino入门:直流电机控制

一、本节介绍在本实验中,您将学习如何使用驱动芯片L293D和SunFounder Uno板控制小型直流(DC)电机的方向和速度。为了使初学者更容易,我们将让直流电机左右旋转,自动加速和减速。二、材料准备1 *小型直流电机1 * L293D1 * Arduino Uno板1 *面包板1 * USB数据线杜邦线三、原理讲解L293D这是一个非常实用的芯片,可以独立控制两台直流电机。在这个实验中,只有一...

weixin_29163857的博客 3568

Spring Boot 数据源与 MyBatis(-Plus) 自定义配置详解

本文详解 Spring Boot 中单数据源环境下 HikariCP 与 MyBatis-Plus 的自定义配置。通过手动声明 SqlSessionFactory,实现下划线转驼峰、日志输出、一级缓存策略等精细化控制。结合 HikariCP 核心参数调优(如最大连接数、连接生命周期),确保高性能与稳定性。适用于仅需访问单一数据库的场景,避免多数据源复杂性,兼顾性能与可维护性。

BADAO_LIUMANG_QIZHI的博客 202

成功解决 OllamaError: status code 400, message: model ‘llama3.2:latest‘ not found 报错

本文针对Ollama更新后出现的OllamaError: status code 400, message: model 'llama3.2:latest' not found报错,分析了其根本原因——2026年1月Ollama将Llama 3.2模型命名从llama3.2:latest改为meta-llama/Llama-3.2:7b-instruct等新格式。解决方案包括:1)使用新模型名称;2)升级Ollama SDK;3)查询确认本地可用模型;4)批量更新旧项目脚本。通过正确适配新命名规则,

博客 1398

Java EE 进阶:8.MyBatis 操作数据库(入门)(第一弹)

Java EE 进阶:8.MyBatis 操作数据库(入门)(第一弹)

要努力去发光,而不是被照亮~ 133

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

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

【从零理解 Spring AI · 12】MCP 的两种角色:做客户端还是做服务端

上一篇讲了 MCP 的概念:标准协议、三大角色、M+N 替代 M×N。

nice_lcj520的博客 503

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

LeetCode Hot 100 二叉树专题(二)3 题(Java)

本篇文章共 3 题:543. 二叉树的直径、102. 二叉树的层序遍历、108. 将有序数组转换为二叉搜索树。 每道题都统一按「① 题目分析 & 解题思路 → ② 常见解法(附代码)及讲解 → ③ 知识点总结」的顺序组织;代码使用 Java 编写,节点定义沿用 LeetCode 默认的 TreeNode。

2401_88612756的博客 366

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

JDK 下载安装:装完 Java 提示「不是内部或外部命令」?环境变量没配

JDK 是写 Java 程序必须装的东西。它包含运行 Java 的虚拟机(JRE)和编译 Java 的编译器(javac)——装了它,能跑、.java文件能编译成可执行程序。免费,学习和小规模生产都不花钱。

科小怪的博客 636

java框架大全

java框架大全

qq_39326137的博客 183

Java 多态 学习笔记

多态是面向对象编程的重要特性,指同一操作作用于不同对象时产生不同行为。其核心在于“父类引用指向子类对象”,结合方法重写实现运行时动态绑定。多态使代码更灵活、可扩展,如用Person p = new Student();统一处理各类人员注册,无需修改调用逻辑。但多态无法直接调用子类特有方法,需通过instanceof判断并强制转换。编译时看左边(类型),运行时看右边(实际对象),实现解耦与维护便利。

AA_AA114514的博客 363

SecureRandom做随机源,这个Java随机字符串工具类有3个方法

本文分享一款JDK17环境下的Java随机字符串工具类,内置3个开箱即用的方法,全部采用SecureRandom加密安全随机源,不存在弱随机、可预测、取模偏差等问题。工具类支持默认62字符集随机串、纯数字随机串、自定义字符集随机串三种生成模式,支持Unicode码点级别的字符集处理,兼容Emoji等增补字符,边界处理严格,异常信息明确,适合验证码、邀请码、盐值、随机口令、短链码等场景,源码可直接复制使用。

Java后端 | AI智能体应用实战派 | 电脑技能行家 299

IDEA 简介:从零认识 IntelliJ IDEA

IDEA 全称,是由 JetBrains 公司开发的一款主流 Java 集成开发环境(IDE)。它集代码编辑、编译、调试、测试、版本控制、构建管理等功能于一体,被大量 Java 开发者视为日常开发的首选工具。所谓 IDE(Integrated Development Environment,集成开发环境),就是把写代码所需的各类工具整合到同一个界面中。相比只用文本编辑器加命令行编译,IDE 能显著减少重复操作,让开发者把精力集中在业务逻辑上。

ztI10的博客 155

Java实现批量线段相交检测(跨积判定+扫描线优化与踩坑复盘)

【代码】Java实现批量线段相交检测(跨积判定+扫描线优化与踩坑复盘)

m0_64476639的博客 329

TRingBuffer两端都能增删(快递站版)

TRingBuffer 是一个支持两端增删、下标访问且容量动态增长的环形双端队列。它通过无符号索引的永不归零设计,利用减法自动模运算实现空满判断与元素计数,避免了传统环形缓冲浪费格子的问题。内部以票号(索引)标记首尾,扩容时重排元素为连续存储,保证 O(1) 操作与高缓存效率。虽不线程安全,但其高效性使其成为游戏开发中事件队列、命令缓冲等场景的理想选择。

u013768914的博客 301

ubuntu安装hadoop系统

本文详细介绍了基于VMware克隆虚拟机搭建三节点Hadoop分布式集群的全过程:使用同一Ubuntu镜像克隆出master、worker1、worker2三台虚拟机,依次配置主机名、固定IP(如192.168.82.10/11/12)、SSH服务及免密登录,确保节点间网络互通。随后安装Java,下载配置Hadoop并分发至各节点,最终初始化启动集群,验证其存储与计算功能,实现高效的大数据环境部署。

qq_43592674的博客 339
上一篇: Understanding Class.forName (一)
下一篇: Application Class Loader
林仪明
博客等级 码龄25年 313粉丝 61原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值