Java连接redis集群报错,connection refused 和Could not get a resource from the pool

Windows 11 Redis生产级部署:服务注册+可视化管控全闭环 Redis 是一种高性能内存键值数据库,其核心原理是基于单线程事件循环与内存存储实现低延迟读写;在 Windows 11 系统中,由于 NT 内核服务模型、VBS 内存保护、DPI 缩放及防火墙策略等特性,原生 Redis 部署极易出现 Connection refused、服务自停、可视化界面异常等工程问题;技术价值在于构建符合 SCM 规范的稳定 Windows 服务,并实现与 Spring Boot 微服务的无缝集成;典型应用场景包括 Java 开发环境搭建、分布式缓存调试、业务数据结构演示等;本文聚 阅读详情

在使用Jedis进行redis集群操作的时候,出现报错connection refused 和Could not get a resource from the pool代码如下:

@Test
public void testRedis(){
final String redisURL = "192.168.3.3";
final String auth = "pass";
final int port7001 = 5001;
final int port7002 = 5002;
final int port7003 = 5003;
final int port7004 = 5004;
final int port7005 = 5005;
final int port7006 = 5006;

final int MAX_IDLE = 200;
final int MAX_TOTAL = 1024;
final int CONN_TIME_OUT = 1000;//链接server超时
final int SO_TIME_OUT = 1000;//等待response超时
final int MAX_ATTEMPTS = 1;//尝试重新链接次数

GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(MAX_TOTAL);
poolConfig.setMaxIdle(MAX_IDLE);

HostAndPort hostAndPort1 = new HostAndPort(redisURL,port7001);
HostAndPort hostAndPort2 = new HostAndPort(redisURL,port7002);
HostAndPort hostAndPort3 = new HostAndPort(redisURL,port7003);
HostAndPort hostAndPort4 = new HostAndPort(redisURL,port7004);
HostAndPort hostAndPort5 = new HostAndPort(redisURL,port7005);
HostAndPort hostAndPort6 = new HostAndPort(redisURL,port7006);

Set<HostAndPort> hostAndPortSet = new HashSet<>(6);
hostAndPortSet.add(hostAndPort1);
hostAndPortSet.add(hostAndPort2);
hostAndPortSet.add(hostAndPort3);
hostAndPortSet.add(hostAndPort4);
hostAndPortSet.add(hostAndPort5);
hostAndPortSet.add(hostAndPort6);

// public JedisCluster(Set<HostAndPort> jedisClusterNode, int connectionTimeout,
// int soTimeout, int maxAttempts, String password, GenericObjectPoolConfig poolConfig)
JedisCluster jedisCluster = new JedisCluster(hostAndPortSet,CONN_TIME_OUT,SO_TIME_OUT,MAX_ATTEMPTS,auth,poolConfig);

jedisCluster.set("a", "1o");
System.out.println(jedisCluster.get("a"));

//
// public JedisPool(GenericObjectPoolConfig poolConfig, String host, int port, int timeout, String password) {
// this(poolConfig, host, port, timeout, password, 0, (String)null);
// }

}

经过查找资料,最终猜测问题出在redis-cluster/redis**/nodes_**.conf,所以对此文件进行了修改

注:修改时请先关闭集群

修改之前的文件内容如下:

30098db4933f13b02ef2a30a5070617f0ae58fd4 127.0.0.1:5006@15006 slave 0ee3bde15b2caf32df19ef85d874c228be8d9342 0 1513932380250 6 connected
692301fa80af9870bb258c34b553590fbced72ad 127.0.0.1:5001@15001 master - 0 1513932380000 1 connected 0-5460
164295b1736fb5fc244abf0a2e57774d938a7262 127.0.0.1:5002@15002 master - 0 1513932379545 2 connected 5461-10922
0ee3bde15b2caf32df19ef85d874c228be8d9342 127.0.0.1:5003@15003 myself,master - 0 1513932380000 3 connected 10923-16383
657967366913fff237e091320761ea7ef9544893 127.0.0.1:5004@15004 slave 692301fa80af9870bb258c34b553590fbced72ad 0 1513932380049 4 connected
13c976fada6a8537826b2585a5dabad6fd2a4ece 127.0.0.1:5005@15005 slave 164295b1736fb5fc244abf0a2e57774d938a7262 0 1513932380553 5 connected

修改后的内容如下:

30098db4933f13b02ef2a30a5070617f0ae58fd4 192.168.3.3:5006@15006 slave 0ee3bde15b2caf32df19ef85d874c228be8d9342 0 1513932380250 6 connected
692301fa80af9870bb258c34b553590fbced72ad 192.168.3.3:5001@15001 master - 0 1513932380000 1 connected 0-5460
164295b1736fb5fc244abf0a2e57774d938a7262 192.168.3.3:5002@15002 master - 0 1513932379545 2 connected 5461-10922
0ee3bde15b2caf32df19ef85d874c228be8d9342 192.168.3.3:5003@15003 myself,master - 0 1513932380000 3 connected 10923-16383
657967366913fff237e091320761ea7ef9544893 192.168.3.3:5004@15004 slave 692301fa80af9870bb258c34b553590fbced72ad 0 1513932380049 4 connected
13c976fada6a8537826b2585a5dabad6fd2a4ece 192.168.3.3:5005@15005 slave 164295b1736fb5fc244abf0a2e57774d938a7262 0 1513932380553 5 connected

资料来源:https://www.cnblogs.com/mengjinluohua/p/6193962.html
PS:此博主最终的解决方法是重做集群,不过我并没有重做集群,只是修改了一下所有节点的nodes**_conf文件并重启,也可以解决问题,目前来看并没有什么不妥,如果有问题再回来修改 ×——×

Theia云IDE+Kubernetes实战:DigitalOcean上快速部署生产级Web IDE 云IDE是将开发环境作为服务交付的技术范式,其核心在于环境一致性、弹性伸缩与零客户端依赖。基于Kubernetes的云IDE架构,通过容器化封装、声明式编排与服务网格化治理,显著降低多团队协作中的环境差异与配置漂移风险。Theia作为模块化Web IDE框架,凭借前后端解耦、插件沙箱与多工作区云原生支持,成为企业级云开发平台的理想底座;结合DigitalOcean Kubernetes(DOKS)的极简集群交付能力与Helm对应用生命周期的契约化管理,可实现从零到可用IDE的15分钟快速落地。本文聚焦真实场 阅读详情

相关推荐

Spring Boot集成Nacos的五大核心配置与避坑指南

Nacos作为主流微服务配置中心与服务发现组件,其本质是分布式协同基础设施,需兼顾配置管理、服务注册、元数据一致性与安全治理。理解其启动时机(bootstrap上下文优先)、命名空间隔离、dataId加载顺序、动态刷新机制及客户端容灾策略,是保障系统稳定的关键。尤其在Spring Boot项目中,错误地将Nacos视为‘增强版配置文件’,忽略namespace、group、refresh-scope等核心机制,极易引发跨环境配置污染、服务注册失败或热更新失效等问题。本文聚焦Nacos在Spring Clou

diaohong5075的博客 498

常见JedisConnectionException异常分析

常见JedisConnectionException异常分析- 转自: https://blog.youkuaiyun.com/qq7389/article/details/79479776 在使用redis的过程中,偶然遇到JedisConnectionException。所以想记个笔记,发现网上已经有了博客,所以引用一下,记一下笔记。感谢上面这位友人。 一. 当我们执行如下JedisPool 类实例的getResource() 时抛出can’t get a resource 异常。 异常代码如下: redis.c

无尽_easy的博客 2130

部署失败排查指南:从日志分析到问题定位的实战技巧

在软件开发和运维领域,日志分析是诊断系统问题的核心技术手段。其原理在于通过解析应用程序、服务器或容器运行时产生的记录信息,追踪代码执行路径和系统状态变化,从而定位故障根源。这项技术的核心价值在于能将模糊的“部署失败”告警转化为具体的、可操作的修复步骤,极大提升问题解决效率。在应用场景上,无论是传统的Java Web应用部署,还是现代的Docker容器与Kubernetes集群环境,高效的日志排查都是保障服务稳定性的关键。例如,面对常见的“部署失败,请查看日志”提示,开发者需要掌握从海量信息中快速定位异常堆栈

weixin_34099526的博客 412

java 连接 redis集群时报错:Could not get a resource from the pool

由于弄这个的时候浪费了太多的时间,所以才记录下这个错,给大伙参考下 检查了一下,配置啥的都没问题的,但在redis集群机器上就可以,错误如下: Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool ...

weixin_34184158的博客 356

若依RuoYi容器化部署实战:Docker Compose生产级交付方案

容器化是现代Java应用实现环境一致性、部署可复现与运维自动化的基石。其核心原理在于通过声明式配置(如docker-compose.yml)将服务依赖、网络拓扑、资源配置固化为代码,从而消除手动部署中常见的配置漂移、环境差异与单点故障。技术价值体现在提升交付稳定性、加速故障恢复、强化安全隔离,并天然支撑CI/CD与可观测性建设。典型应用场景包括前后端分离架构的微服务治理、多环境(开发/测试/生产)快速同步,以及云边协同下的轻量级私有化交付。本文聚焦若依(RuoYi)这一主流Java快速开发平台,深入解析其容

weixin_30333885的博客 385

Azure DevOps YAML流水线实战:构建-测试-部署全链路落地指南

CI/CD流水线是现代软件交付的核心基础设施,其本质是将代码变更自动转化为可验证、可审计、可回滚的生产就绪状态。实现这一目标的关键在于标准化流程定义(YAML Pipeline)、前置质量门禁(自动化测试集成)与环境一致性保障(多环境部署策略)。Azure DevOps凭借深度Git集成、原生YAML支持和丰富任务生态,成为企业级CI/CD落地的高成熟度平台。本文聚焦真实工程场景,详解如何从零搭建具备编译加速、分层测试门禁、蓝绿部署与可观测性输出的生产级流水线,并覆盖Agent选型、变量安全、缓存优化等高频

culh2177的博客 419

Redis遇到过的问题 (Could not get a resource from the pool )

其中查看所有连接的展示的列表内容我在下方标出,注意看下idle这个字段,代表的空闲时间,单位是秒,这时可以看到idle的时间非常长,所以我这边确定程序获取获取大量的redis连接资源并且没有释放。否则,断开与 Redis 的连接。需要注意的是redisTemplate使用的是自动管理连接池,按道理来说调用完之后会自动释放连接,但是当redis开启了事务的时候,就需要手动释放连接,所以解决方案有两种。这么常用的方法,基于习惯,Java 在 jdk1.7 之后为我们提供了一个很好的方法。

wppwpp1的专栏 2472

Hermes Agent本质:可编程工作流中枢与MCP协议实践指南

智能体(Agent)是当前AI工程化落地的核心范式,其核心在于将大语言模型(LLM)与外部工具协同调度的能力。Model Context Protocol(MCP)作为标准化工具接入协议,通过JSON-RPC抽象函数接口,解耦模型推理与工具执行,显著提升智能体的可维护性与安全性。相比传统LangChain等框架的手动封装,MCP支持Stdio/HTTP双模式、声明式配置与热插拔能力,使开发者能聚焦业务逻辑而非适配胶水代码。在DevOps、自动化代码审查、智能客服等场景中,基于Hermes Agent构建的M

dflkg8956的专栏 356

已解决redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool异常的正确解决方法,亲测

已解决redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool异常的正确解决方法,亲测有效!!!

小明的Java问道之路 15万+

正确解决JedisExhaustedPoolException: Could not get a resource since the pool is exhausted异常的有效解决方法

正确解决JedisExhaustedPoolException: Could not get a resource since the pool is exhausted异常的有效解决方法

wbajsjhhhhh的博客 3110

系统变慢崩溃排查:从指标到根因的实用路径

系统性能问题往往表现为响应变慢、偶发崩溃或重启后恢复,背后可能是入口层连接耗尽、服务层线程池阻塞或数据层慢查询堆积。要快速定位瓶颈,需掌握可观测性指标的真正含义——CPU使用率、内存水位、磁盘IO、网络延迟和错误率各有其“欺骗性”,例如CPU低不代表不忙,磁盘写满前就已开始影响性能。通过成功率与P50/P95/P99耗时分布,结合线程状态、连接池等待和慢请求特征,才能从现象走向根因。隔离外部依赖、统一超时与重试策略、记录优化基线,是长期稳定的关键。本文以系统级视角,梳理从混沌到稳定的排查流程,给出可落地的命

weixin_30843121的博客 270

使用JedisPool连接Redis报错( Could not get a resource from the pool和 Connection refused)

在使用JedisPool连接Redis的时候出现以下异常: Exception in thread &quot;main&quot; redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool at redis.clients.util.Pool.getResource(Pool.ja...

wlk_328909605的博客 3086

别再搞混了!MATLAB通信仿真中EbN0转SNR的保姆级公式推导与避坑指南

本文深入解析MATLAB通信仿真中EbN0与SNR转换的核心公式,揭示数字仿真与理论系统的关键差异。通过真实案例展示错误参数设置导致的隐蔽问题,并提供完整的参数自查清单和正确实现代码,帮助工程师和学生避免常见错误,确保仿真结果准确可靠。

weixin_28746223的博客 348

Spring Boot服务启动依赖连接失败:从快速崩溃到优雅容错的实战指南

在分布式系统和微服务架构中,服务启动时对外部组件的依赖连接是基础且关键的环节。其核心原理在于,许多现代框架(如Spring Boot)默认采用“快速失败”策略,以确保服务不在不健康状态下运行。然而,不当的配置(如连接池无限等待、超时设置不合理)会导致服务陷入“假死”而非明确失败,严重影响系统可用性。从技术价值看,正确处理启动依赖问题能极大提升系统的鲁棒性和可观测性。典型的应用场景包括服务与数据库、Redis缓存、配置中心及消息队列的初始连接。本文聚焦于Spring Boot应用,深入探讨如何通过配置调优、健

weixin_34038293的博客 315

告别第三方应用!用Android原生API搭建Miracast投屏接收器

本文深入探讨如何利用Android原生API开发Miracast接收器,绕过第三方依赖,实现高效的屏幕共享。通过Wi-Fi P2P直连、反射调用隐藏API和RTSP会话协商等核心技术,为开发者提供了一套完整的Miracast接收端解决方案,适用于多屏协同场景。

weixin_29174141的博客 392

嵌入式学习的书单推荐

以上是一些优秀的嵌入式学习书单推荐。选择适合自己的学习材料对于学习嵌入式系统非常重要。每一本书籍都有其独特的优势和特点,读者可以根据自己的学习目标和兴趣选择合适的书籍。同时,我们也要注意不断实践和探索,结合实际项目和项目经验,不断提升自己的嵌入式技术水平。希望本文的推荐能够帮助大家在嵌入式学习的道路上取得更好的成果。

新程序圆 1980

liunx版本的

services:ports:volumes:network_mode: "host" # 添加此行(必须)kibana:ports:ELASTICSEARCH_HOSTS: http://192.168.1.145:9200 # 具体ip(必须)network_mode: "host" # # 添加此行(必须)

m0_45209551的博客 1193

机械臂开发必备:KDL库正逆解与动力学实战指南

在机器人算法领域,运动学与动力学计算是机械臂控制、仿真与轨迹规划的核心基础。正运动学描述关节空间到笛卡尔空间的映射,逆运动学则需要求解复杂的非线性方程,工程实现时常面临数值稳定性与调试效率的挑战。KDL(Kinematics and Dynamics Library)作为ROS生态中广泛使用的开源库,提供了统一的模型描述与高效求解器,将正逆解、雅可比矩阵及动力学参数计算封装为简洁接口,大幅降低开发门槛。无论是机械臂的笛卡尔空间轨迹跟踪,还是基于动力学模型的前馈控制,KDL都展现出强大的工程价值。本文从运动学

weixin_33860528的博客 2506

达梦数据库接入MCP协议的实战指南与安全架构

MCP(Model Control Protocol)作为AI Agent与后端能力交互的核心协议,其标准化调用依赖于数据库对SQL方言、元数据语义、权限模型和网络协议的深度适配。国产数据库如达梦虽兼容JDBC,但因Oracle系权限体系、ROWNUM分页机制、SYSOBJECTS视图访问限制等特性,无法直接满足MCP的`get_schema`、`execute_sql`等标准能力要求。`dm-mcp-server`正是为解决这一断层而生——它并非简单驱动封装,而是集协议网关、方言翻译、权限裁剪于一体的中间

weixin_33853827的博客 393

ENVI基于Landsat影像构建郑州市2000-2019年遥感生态指数RSEI

本文基于landsat5、landsat7、landsat8三种传感器的影像,使用ENVI软件构建郑州市2000-2019年遥感生态指数RSEI。内含ENVI详细操作、使用的公式以及构建结果。

Lexicopperfield的博客 1万+

配置 SAP Fiori 服务的 ICF 节点:从 SICF 激活到访问链路打通的完整实践

在SAP Fiori项目实施中,ICF节点配置是关键前置条件却常被忽视。ICF(Internet Communication Framework)作为HTTP请求入口,需要通过SICF事务码激活相关服务节点,否则即使应用开发完善,用户仍可能遇到页面无法访问等问题。典型问题表现为:磁贴可点击但页面空白、资源加载失败等。激活路径主要涉及三组节点:bsp分支下的管理入口、ui5_ui5分支下的应用资源,以及public/bc下的公共资源。项目实施中需特别注意同名服务在不同分支下的差异化作用,确保完整链路通畅。IC

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 264

零基础学会flink,保姆级超详细教学

本文提供了一个三周学会Apache Flink的详细学习路线,从环境搭建到项目实战,适合零基础开发者快速掌握Flink流处理技术。 学习路线概览: 环境搭建(JDK11、Maven、IntelliJ IDEA和Flink集群) 基础入门(WordCount程序) 核心API学习(DataStream算子、时间窗口、状态管理) 高级功能(Table API/SQL、Kafka连接器) 综合项目实战(实时订单统计/用户行为分析) 第一天重点: 详细演示了开发环境配置(JDK11安装验证、Maven配置、IDEA

korry24的博客 289

利用恒源云云端GPU高效训练YOLOv11模型全流程:从环境搭建到模型部署,让你摆脱硬件束缚

记住,云端GPU的核心优势是“弹性算力+一键环境”,只要把握好这一工具特性,再结合YOLOv11的高性能模型架构,你也能在计算机视觉领域快速落地项目。接下来,我们从工具准备到模型部署,一步步带你实现高效训练,真正帮你解决资源与效率的核心痛点。凭借其在目标检测、实例分割任务上的卓越性能,成为众多开发者的首选。据统计,使用云端GPU训练YOLOv11,在处理百万级数据集时,训练效率较本地普通GPU提升。在安防监控中,YOLOv11可实时检测人员、车辆异常行为,某园区采用该方案后,异常事件识别准确率达。

LXY_LOVE36的博客 213

手把手搭建永久在线的开源CRM系统

CRM系统是企业客户关系管理的核心基础设施,其自主可控性直接决定数据主权与业务连续性。基于Node.js、MySQL 8.0和Vue的技术栈,开源CRM框架支持本地化部署、免订阅依赖与全量数据导出,具备高兼容性与低运维门槛。技术价值体现在摆脱SaaS厂商锁定、规避API下线风险、保障敏感信息不出域,并适配中小团队真实负载场景。典型应用场景包括销售线索全周期追踪、BI直连分析、私有云/边缘设备(如树莓派)轻量部署。本文聚焦DeskcommCRM这一符合第三范式设计、无遥测上报、支持MySQL 8.0 JSON

weixin_34221276的博客 499

ML.NET在工业上位机中的深度应用:如何用C#实现10ms级预测推理?

模型要“够用就好”:工业场景的规律往往不复杂,别迷信深度学习,FastTree、线性模型足够应付80%的场景,且速度快3-5倍;预处理“能省就省”:离线做90%的特征工程,实时只处理动态变化的10%,这是突破10ms的关键;代码“贴近硬件”:用struct、数组池、SIMD等“非托管技巧”写C#,避免GC成为实时性瓶颈;测试“模拟极端”:在目标工控机上用100%负载(同时跑PLC通信、运动控制、视觉检测)测试推理延迟,确保极端情况下仍达标。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 742

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

上一篇: 数据库优化
下一篇: python3使用openpyxl导出巨大量数据到excel文件
雕花の刺猬
博客等级 码龄10年 45粉丝 28原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值