我去,你竟然还在用 try–catch-fin

拔掉网线后TCP连接状态变化与检测机制深度解析 TCP作为面向连接的传输层协议,通过内核维护的连接状态机实现可靠数据传输。其核心原理基于三次握手建立连接和四次挥手断开连接,通过序列号确认和超时重传机制保证数据可靠性。在网络编程中,TCP的连接状态管理直接影响应用程序的健壮性,特别是在网络异常场景下。当物理链路中断(如拔网线)时,操作系统需要依赖重传机制和Keepalive参数来检测连接失效,Linux系统默认重传超时可达30分钟。为提升系统容错能力,工程师需要结合应用层心跳机制、socket超时设置和连接池验证等技术,实现快速故障检测。本文通过TCP连接 阅读详情

现在复工复产的行业越来越多了,疫情估计会踩着春天的尾巴离开。同也因为这次疫情,让我们更深刻的认识到,只有新颖的、实用的、高效快捷的东西才会被留下来,随之而改变的就是我们的行业模式。我们开始寻找新的东西,留下那些有思想有技术的工作人员,只有有内涵,能创新,紧跟网络时代的脚步,了解最新的网络资源,认清当前的趋势走向的人,才是公司真正需要的人员。

来说说我们公司的吧,这次 review 的代码仍然是小王的,他编写的大部分代码都很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他没用 try-with-resources 时,还是忍不住破口大骂:“我擦,小王,你丫的竟然还在用 try–catch-finally!”

来看看小王写的代码吧。

public class Trycatchfinally {
    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("/牛逼.txt"));
            String str = null;
            while ((str =br.readLine()) != null) {
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
复制代码

咦,感觉这段代码很完美无缺啊,try–catch-finally 用得中规中矩,尤其是文件名 牛逼.txt 很亮。不用写注释都能明白这段代码是干嘛的:在 try 块中读取文件中的内容,并一行一行地打印到控制台。如果文件找不到或者出现 IO 读写错误,就在 catch 中捕获并打印错误的堆栈信息。最后,在 finally 中关闭缓冲字符读取器对象 BufferedReader,有效杜绝了资源未被关闭的情况下造成的严重性能后果。

在 Java 7 之前,try–catch-finally 的确是确保资源会被及时关闭的最佳方法,无论程序是否会抛出异常。

但是呢,有经验的读者会从上面这段代码中发现 2 个严重的问题:

1)文件名“牛逼.txt”包含了中文,需要通过 java.net.URLDecoder 类的 decode() 方法对其转义,否则这段代码在运行时铁定要抛出文件找不到的异常。

2)如果直接通过 new FileReader("牛逼.txt") 创建 FileReader 对象,“牛逼.txt”需要和项目的 src 在同一级目录下,否则同样会抛出文件找不到的异常。但大多数情况下,(配置)文件会放在 resources 目录下,便于编译后文件出现在 classes 目录下,见下图。

 

为了解决以上 2 个问题,我们需要对代码进行优化:

public class TrycatchfinallyDecoder {
    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            String path = TrycatchfinallyDecoder.class.getResource("/牛逼.txt").getFile();
            String decodePath = URLDecoder.decode(path,"utf-8");
            br = new BufferedReader(new FileReader(decodePath));

            String str = null;
            while ((str =br.readLine()) != null) {
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
复制代码

运行这段代码,程序就可以将文件中的内容正确输出到控制台。但如果你对“整洁”这个词心生向往的话,会感觉这段代码非常臃肿,尤其是 finally 中的代码,就好像一个灌了 12 瓶雪花啤酒的大肚腩。

网上看到一幅 Python 程序员调侃 Java 程序员的神图,直接 copy 过来(侵删),逗你一乐:

 

况且,try–catch-finally 至始至终存在一个严重的隐患:try 中的 br.readLine() 有可能会抛出 IOException,finally 中的 br.close() 也有可能会抛出 IOException。假如两处都不幸地抛出了 IOException,那程序的调试任务就变得复杂了起来,到底是哪一处出了错误,就需要花一番功夫,这是我们不愿意看到的结果。

为了模拟上述情况,我们来自定义一个类 MyfinallyReadLineThrow,它有两个方法,分别是 readLine() 和 close(),方法体都是主动抛出异常。

class MyfinallyReadLineThrow {
    public void close() throws Exception {
        throw new Exception("close");
    }

    public void readLine() throws Exception {
        throw new Exception("readLine");
    }
}
复制代码

然后我们在 main() 方法中使用 try-finally 的方式调用 MyfinallyReadLineThrow 的 readLine() 和 close() 方法:

public class TryfinallyCustomReadLineThrow {
    public static void main(String[] args) throws Exception {
        MyfinallyReadLineThrow myThrow = null;
        try {
            myThrow = new MyfinallyReadLineThrow();
            myThrow.readLine();
        } finally {
            myThrow.close();
        }
    }
}
复制代码

运行上述代码后,错误堆栈如下所示:

Exception in thread "main" java.lang.Exception: close
	at com.cmower.dzone.trycatchfinally.MyfinallyOutThrow.close(TryfinallyCustomOutThrow.java:17)
	at com.cmower.dzone.trycatchfinally.TryfinallyCustomOutThrow.main(TryfinallyCustomOutThrow.java:10)
复制代码

readLine() 方法的异常信息竟然被 close() 方法的堆栈信息吃了,这必然会让我们误以为要调查的目标是 close() 方法而不是 readLine()——尽管它也是应该怀疑的对象。

但自从有了 try-with-resources,这些问题就迎刃而解了,只要需要释放的资源(比如 BufferedReader)实现了 AutoCloseable 接口。有了解决方案之后,我们来对之前的 finally 代码块进行瘦身。

try (BufferedReader br = new BufferedReader(new FileReader(decodePath));) {
    String str = null;
    while ((str =br.readLine()) != null) {
        System.out.println(str);
    }
} catch (IOException e) {
    e.printStackTrace();
}
复制代码

你瞧,finally 代码块消失了,取而代之的是把要释放的资源写在 try 后的 () 中。如果有多个资源(BufferedReader 和 PrintWriter)需要释放的话,可以直接在 () 中添加。

try (BufferedReader br = new BufferedReader(new FileReader(decodePath));
     PrintWriter writer = new PrintWriter(new File(writePath))) {
    String str = null;
    while ((str =br.readLine()) != null) {
        writer.print(str);
    }
} catch (IOException e) {
    e.printStackTrace();
}
复制代码

如果你想释放自定义资源的话,只要让它实现 AutoCloseable 接口,并提供 close() 方法即可。

public class TrywithresourcesCustom {
    public static void main(String[] args) {
        try (MyResource resource = new MyResource();) {
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class MyResource implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("关闭自定义资源");
    }
}
复制代码

代码运行后输出的结果如下所示:

关闭自定义资源
复制代码

是不是很神奇?我们在 try () 中只是 new 了一个 MyResource 的对象,其他什么也没干,但偏偏 close() 方法中的输出语句执行了。想要知道为什么吗?来看看反编译后的字节码吧。

class MyResource implements AutoCloseable {
    MyResource() {
    }

    public void close() throws Exception {
        System.out.println("关闭自定义资源");
    }
}

public class TrywithresourcesCustom {
    public TrywithresourcesCustom() {
    }

    public static void main(String[] args) {
        try {
            MyResource resource = new MyResource();
            resource.close();
        } catch (Exception var2) {
            var2.printStackTrace();
        }

    }
}
复制代码

咦,编译器竟然主动为 try-with-resources 进行了变身,在 try 中调用了 close() 方法。

接下来,我们在自定义类中再添加一个 out() 方法,

class MyResourceOut implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("关闭自定义资源");
    }

    public void out() throws Exception{
        System.out.println("沉默王二,一枚有趣的程序员");
    }
}
复制代码

这次,我们在 try 中调用一下 out() 方法:

public class TrywithresourcesCustomOut {
    public static void main(String[] args) {
        try (MyResourceOut resource = new MyResourceOut();) {
            resource.out();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
复制代码

再来看一下反编译的字节码:

public class TrywithresourcesCustomOut {
    public TrywithresourcesCustomOut() {
    }

    public static void main(String[] args) {
        try {
            MyResourceOut resource = new MyResourceOut();

            try {
                resource.out();
            } catch (Throwable var5) {
                try {
                    resource.close();
                } catch (Throwable var4) {
                    var5.addSuppressed(var4);
                }

                throw var5;
            }

            resource.close();
        } catch (Exception var6) {
            var6.printStackTrace();
        }

    }
}
复制代码

这次,catch 块中主动调用了 resource.close(),并且有一段很关键的代码 var5.addSuppressed(var4)。它有什么用处呢?当一个异常被抛出的时候,可能有其他异常因为该异常而被抑制住,从而无法正常抛出。这时可以通过 addSuppressed() 方法把这些被抑制的方法记录下来。被抑制的异常会出现在抛出的异常的堆栈信息中,也可以通过 getSuppressed() 方法来获取这些异常。这样做的好处是不会丢失任何异常,方便我们开发人员进行调试。

哇,有没有想到我们之前的那个例子——在 try-finally 中,readLine() 方法的异常信息竟然被 close() 方法的堆栈信息吃了。现在有了 try-with-resources,再来看看作用和 readLine() 方法一致的 out() 方法会不会被 close() 吃掉。

在 close() 和 out() 方法中直接抛出异常:

class MyResourceOutThrow implements AutoCloseable {
    @Override
    public void close() throws Exception {
        throw  new Exception("close()");
    }

    public void out() throws Exception{
        throw new Exception("out()");
    }
}
复制代码

调用这 2 个方法:

public class TrywithresourcesCustomOutThrow {
    public static void main(String[] args) {
        try (MyResourceOutThrow resource = new MyResourceOutThrow();) {
            resource.out();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
复制代码

程序输出的结果如下所示:

java.lang.Exception: out()
	at com.cmower.dzone.trycatchfinally.MyResourceOutThrow.out(TrywithresourcesCustomOutThrow.java:20)
	at com.cmower.dzone.trycatchfinally.TrywithresourcesCustomOutThrow.main(TrywithresourcesCustomOutThrow.java:6)
	Suppressed: java.lang.Exception: close()
		at com.cmower.dzone.trycatchfinally.MyResourceOutThrow.close(TrywithresourcesCustomOutThrow.java:16)
		at com.cmower.dzone.trycatchfinally.TrywithresourcesCustomOutThrow.main(TrywithresourcesCustomOutThrow.java:5)
复制代码

瞧,这次不会了,out() 的异常堆栈信息打印出来了,并且 close() 方法的堆栈信息上加了一个关键字 Suppressed。一目了然,不错不错,我喜欢。

总结一下,在处理必须关闭的资源时,始终有限考虑使用 try-with-resources,而不是 try–catch-finally。前者产生的代码更加简洁、清晰,产生的异常信息也更靠谱。答应我好不好?别再用 try–catch-finally 了。

鸣谢

好了,我亲爱的读者朋友,以上就是本文的全部内容了,是不是感觉又学到了新知识?对以上相关资料或是对架构,面试,算法,大数据等最新网络资源感兴趣的读者朋友们,可以在评论区发表自己的言论,有什么疑问也可以私信小编进行解答。

 

腾讯混元API上手指南:Python零基础+OpenAI兼容模式实战 大模型API调用是当前AI工程落地的核心能力,其本质是HTTP协议封装、鉴权机制、流式响应处理与成本计量的系统性实践。理解token计费逻辑、错误码归因和网关熔断原理,直接决定服务稳定性与运维效率。在OpenAI生态广泛普及的背景下,腾讯混元API凭借兼容模式降低迁移门槛,但system角色处理、function calling参数结构及流式chunk边界等关键差异,常导致50%以上POC失败。本文聚焦Python技术栈,结合CrazyRouter网关与keyring密钥管理,提供从零配置到生产压测的全链路 阅读详情

相关推荐

GPT-4o稳定性工程实战:四层评估与7个可落地优化

大语言模型的稳定性并非简单指API不报错,而是涵盖基础设施、模型推理、应用逻辑与业务价值的多维动态平衡。其核心原理在于识别并控制输入分布偏移、长尾延迟、提示鲁棒性及上下文衰减等关键扰动因素。技术价值体现在降低人工接管率、提升任务完成率与会话满意度,广泛应用于智能客服、跨境电商、在线教育等高并发、强交互场景。本文基于GPT-4o真实压测数据,系统拆解分层稳定性验证方法,并提供BFF网关、HTTP/2流式响应、响应格式校验等可立即实施的工程实践。

weixin_33901926的博客 336

Try-Catch-Finlly语句执行顺序

先执行try,出现错误执行catch,程序最终都会执行finlly: try { System.out.println("try的输出"); return "try的返回"; } catch (Exception e) { System.out.println("catch的输出"); ...

laozengsky的博客 758

【信息科学与工程学】计算机科学与自动化——第二十四篇 编译器10——编译原理与词法分析02

链接时优化:全局DCE(579)、LTO(580)安全编译:CFI(581、586)、ASan(582)、UBSan(583)、MSan(584)、TSan(585)、CET(587)、PAC(588)、MTE(589)、SFI(590)、Wasm沙箱(591)侧信道与秘密:侧信道缓解(592)、常量时间(593)、秘密清理(594)内存安全:ASLR(595)、栈保护(596)、整数溢出检测(597)、除零检测(598)、空指针检测(599)、数组边界检查(600)至此编号达到600。

weixin_49199313的博客 194

详解捕获异常的try-catch-finlly语句

Java中处理异常有两种方式,一种是throws抛出异常,另一种是try-catch-finally捕获异常。今天要详细介绍一下捕获异常。try-catch语句的语法格式try { //此处为抛出具体异常的代码 }catch (ExceptionType1 e) { //抛出异常ExceptionType1时要执行的代码 }catch (ExceptionType2 e) {

菜鸟的博客 6160

10X Genomics数据实战:手把手教你用Seurat处理单细胞PBMC数据(附完整代码)

本文详细介绍了如何使用Seurat处理10X Genomics的单细胞PBMC数据,从数据获取、质控到降维分析和细胞分群的全流程。通过实战代码演示,帮助研究者掌握单细胞RNA测序数据分析的核心技术,提升对细胞异质性的理解。

weixin_29053577的博客 252

【加密社】私钥碰撞器,秒杀市面上的碰撞器

基于上述的逻辑和代码,开发了ETH挖掘器(图1.1)这里有个亮点是:1.很多开发者在判断地址是否有效的环节上,用的是查询余额,其实这是不对的,查询余额你可能只能查询对应代币的余额,例如usdt,eth等但是如果用查询交易次数就不一样了,你只要是交易过,我就认为是有效钱包,这样的速度比查询余额要快,也要更准确。2.rpc节点可配置。

加密社的博客 1577

JDK1.7新特性之try-with-resources和catch多种异常

try-with-resources语句是一个声明一个或多个资源的

lavimer 1万+

LVGL仪表盘实战:5分钟用lv_meter打造汽车仪表UI(附完整代码)

本文详细介绍了如何使用LVGL的lv_meter组件在5分钟内构建专业汽车仪表盘UI。从环境配置、刻度定制到指针动画和性能优化,提供完整代码示例和实战技巧,帮助开发者快速实现嵌入式设备上的高效仪表盘设计。

k5l6m的博客 417

关于try/catch...finally的性能

最近在网上找了一下,针对C++,下表看性能影响不是很大,关键在于对exception的基类的定义,建议都从std::exception开始Execution Speed with and without Exception Handling w/o EHw/EH%Borland78 sec83 sec6%

kangchb的专栏 884

大唐杯5G考前冲刺篇(回顾全文重点必看)

大唐杯习题复习指南

nimo观察者 1万+

【NodeRed】node-red-contrib-opcua实现PLC读写

在之前的博文【Node-RED】node-red-contrib-opcua-server模块使用(1)中,我们介绍了用node-red-contrib-opcua-server模块实现OPCUA服务端的,以及二次开发的内容。本节博文中我们采用官方社区自带的node-red-contrib-opcua组件开展对OPCUA客户端的介绍,详细阐述用该组件中OpcUa-Client节点实现客户端对PLC的读写,以及实现过程中遇到的问题。由于官方社区中并没有找到该组件的介绍实例,这也是本博文编写的第1个原因。

weixin_48618536的博客 957

前端老司机 try-catch 的使用

try catch 的用途 在程序逻辑中,需要在易出现问题的逻辑代码片段上,加持try-catch方法。 这样做可以抛出错误,但是不会影响整个程序运转。 try { // 你的逻辑代码片段 } catch (e) { // 错误处理代码片段 } ...

安海军 6002

基于Qt C++开发一款国产化的福昕风格PDF编辑工具

QString text = QInputDialog::getText(this, "文本批注", "输入批注内容:", QLineEdit::Normal, "", &ok);QString savePath = QFileDialog::getSaveFileName(this, "保存加密PDF", "", "PDF文件 (*.pdf)");QAction* zoomInAct = new QAction(QIcon::fromTheme("zoom-in"), "放大", this);

寒寒豆豆软件公司的博客 236

(异常,throw和throws,自定义异常)2020.10.30

目录异常throw和throws自定义异常 异常 理解: 1.在程序执行过程中,出现了错误,导致程序停止执行。 2.是一个对象,封装了错误信息,包括:位置、异常名、异常原因 3.处理异常的机制 java.lang包中。 异常体系机制: 根类:Throwable 两个子类:   Error:错误,指的是非常严重的问题,不应该试图去捕获。   Exception:异常,指的是不太严重的问题,应该试图捕获。     —RuntimeException:运行时异常 异常的默认处理机制:  程序在执行某一行时,出现了

hxc2u的博客 226

Open3D——RANSAC拟合球面【2026最新版】

RANSAC三维点云球面拟合,博客长期更新,本文最新更新时间为:2026年3月5日。

点云侠的博客 4083

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

前端面试锦集

基本面试: 做过最满意的项目是什么?项目背景?为什么要做这件事情?最终达到什么效果?你处于什么样的角色,起到了什么方面的作用?在项目中遇到什么技术问题?具体是如何解决的? 如果再做这个项目,你会在哪些方面进行改善? 基础扎实: IT行业,哪些发展好的同学都是具备扎实基础知识,如果理解计算机基础会更好,因为我们面临很多非前端计算问题的。 主动思考: 被动完成任务成长会很慢的,需要有自己的想法,而不是仅仅是完成任务的。 自动学习: 前端领域知识淘汰速度很快,需要经常学习新知识。 追溯深度: 遇到问题是多研究背.

Front小思的博客 6724

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

android 面试题

ContextImpl.startActivity → Instrumentation.execStartActivity → AMS.startActivity → 校验权限、创建 ActivityRecord、Pause 当前 Activity → ApplicationThread.scheduleTransaction → ActivityThread.H → LaunchActivityItem → performLaunchActivity(创建 Activity、调用 onCreate)。

qq_25657125的博客 388

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

将 FIT 框架 Python CLI 工具发布到 PyPI:完整打包、上传与验证流程

> 导读:本文以 FIT 框架官方命令行工具 `fit-plugin-cli`(即 `fit_cli`)为具体发布对象,完整讲解如何将 Python 工程构建为发布包并上传至 PyPI 正式仓库与 TestPyPI 测试仓库的端到端流程,同时结合当前仓库中真实的 [pyproject.toml](https://link.gitcode.com/i/abcab1e962a7e384d00a4f3b

gitblog_00022的博客 428

Simple-WebSocket-Server扩展开发:如何自定义消息处理器和中间件

Simple-WebSocket-Server是一个轻量级、跨平台的C++ WebSocket库,基于C++11、Boost.Asio和OpenSSL构建,支持WS和WSS协议。本文将详细介绍如何扩展该库,实现自定义消息处理器和中间件,帮助开发者快速构建功能强大的WebSocket应用。 ## 核心概念:消息处理器与中间件 ### 什么是消息处理器? 消息处理器是处理WebSocket消息的

gitblog_00923的博客 400

面试题汇总

高频率面试题

weixin_43766298的博客 867

面试问题总结

文章目录1.abstract和interface异同2.构造方法3.final关键字作用4.重写和重载的区别4.1重载4.2重写5.this关键字6.封装的作用,实现封装的步骤7.封装中的getter和setter方法分别作用7.1setter方法7.2getter方法8.Mybatis-plus与Spring Data JPA9.装箱和拆箱9.1装箱9.2拆箱10.ArrayList底层原理11.反射12.Filter13.$与#的区别14.js中的DOM对象与jQuery中的DOM区别15.四大元注解1

肥猫不是猫 1109

21种AI智能体(Agent)设计模式-A组:执行与任务编排模式-LangChain4j实现例子

本文介绍了基于LangChain4j框架实现的21种AI智能体设计模式中的执行与任务编排模式,重点演示了提示链(Prompt Chaining)模式的实现方法。该模式通过将复杂问题拆解为分类、信息抽取和结果生成三个步骤,形成链式处理流程。文章提供了Maven项目配置示例(包括LangChain4j、Hutool等依赖),并展示了各步骤的Java接口定义(Classifier、Extractor、Generator)和结构化输出类(ClassifyResult、ExtractResult)。该实现利用JSON

penngo的专栏 243

Golang基础面试题汇总

channel、goroutine、slice、map、反射、内存、GC、Musql、Redis、ELK、K8s、Http、Https

weixin_41760738的博客 5696

阿里巴巴Java开发手册 梳理笔记 - finally 块必须对资源对象、流对象进行关闭

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34195142的博客 811

技术大佬:我去,你竟然还在用 try–catch-finally

二哥,你之前那篇 我去 switch 的文章也特么太有趣了,读完后意犹未尽啊,要不要再写一篇啊?虽然用的是 Java 13 的语法,对旧版本不太友好。但谁能保证 Java 不会再来一次重大更新呢,就像 Java 8 那样,活生生地把 Java 6 拍死在了沙滩上。Java 8 是香,但早晚要升级,我挺你,二哥,别在乎那些反对的声音。 这是读者 Alice 上周特意给我发来的信息,真令我动容。的...

沉默王二 1万+
上一篇: 开发十年,分享此套架构体系致和曾经的自己一样迷茫的开发者!
下一篇: 安排!强烈安利10个让你爽到爆的IDEA必备插件!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值