import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public final class RedisUtil {
@Autowired
private RedisTemplate<String,Object> redisTemplate;
// =============================common============================
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间(秒)
* @return
*/
public Boolean expire(String key, Long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public Long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public Boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public Boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public Boolean set(String key, Object value, Long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
*
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public Long incr(String key, Long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public Long decr(String key, Long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public Boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public Boolean hmset(String key, Map<String, Object> map, Long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public Boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public Boolean hset(String key, String item, Object value, Long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public Boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* 根据key获取Set中的所有值
*
* @param key 键
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public Boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public Long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
/**
* 将set数据放入缓存
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public Long sSetAndTime(String key, Long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public Long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public Long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
// ===============================list=================================
public Object leftPop(String key){
try {
return redisTemplate.opsForList().leftPop(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Object rightPop(String key){
try {
return redisTemplate.opsForList().rightPop(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Object leftPush(String key,Object o){
try {
return redisTemplate.opsForList().leftPush(key,o);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Object rightPush(String key,Object o){
try {
return redisTemplate.opsForList().rightPush(key,o);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Object leftPushAll(String key,Collection collection){
try {
return redisTemplate.opsForList().leftPushAll(key,collection);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Object rightPushAll(String key,Collection collection){
try {
return redisTemplate.opsForList().rightPushAll(key,collection);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lrange(String key, Long start, Long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public Long lsize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key, Long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public Boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public Boolean lSet(String key, Object value, Long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public Boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public Boolean lSet(String key, List<Object> value, Long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public Boolean lUpdateIndex(String key, Long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public Long lRemove(String key, Long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
}
相关推荐
基于RedisTemplate的实践优雅地封装缓存工具类
通过封装 Redis 工具类,我们可以更高效地使用 Redis,同时提高代码的可读性和可维护性。本文介绍的 Redis 工具类涵盖了缓存设置、获取、删除、原子性操作等核心功能,适用于大多数业务场景。返回值:返回失效时间(秒),-1 表示永久有效,0 表示未设置失效时间。简化操作:封装 Redis 的常用操作,如缓存设置、获取、删除等。增强功能:支持原子性操作和批量操作,满足复杂业务需求。原子性操作:支持原子性操作,如比较并删除(CAD)。批量操作:支持批量删除缓存,提高操作效率。
RedisTest
@Test public void test44() { Map<String, Object> map = new HashMap<String, Object>(); // map.put("powerConsumption", 80); // map.put("reportStatus", 2); // ...
基于 RedisTemplate 实现的 RedisUtil 工具类
RedisUtil 代码如下 import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; impor..
自定义RedisUtil工具类,不使用RedisTemplate的原生方法,而是自己根据RedisTemplate中的原生方法进行封装,创造出新的方法
文章目录自定义RedisUtil工具类,不使用RedisTemplate的原生方法,而是自己根据RedisTemplate中的原生方法进行封装,创造出新的方法1.RedisUtil工具类的样貌2.RedisUtil工具类的一些常见方法的代码3.测试RedisUtil工具类,以及一个非常难调的空指针错误4.在Redis服务器中查看测试结果 自定义RedisUtil工具类,不使用RedisTemplate的原生方法,而是自己根据RedisTemplate中的原生方法进行封装,创造出新的方法 1.RedisUti
Langfuse落地教程:从Docker部署到项目接入,掌控LLM调用链路
大模型应用开发中,调用链路的透明度直接决定调试效率与成本控制。可观测性技术通过记录每次请求的输入、输出、模型参数与Token消耗,帮助开发者快速定位问题。Langfuse作为开源LLM可观测性平台,将Trace、Prompt版本管理、评分等能力集成于一体,支持Docker Compose自托管部署,并提供Python/JS SDK与REST API。借助部署后的控制台,团队能够直观追踪RAG检索、Agent工具调用等复杂流程中的每一步耗时与资源占用,实现从黑盒调用到全链路可视化的转变。无论是本地调试、线上排
以GD32F103C8T6为例的核心板原理图PCB绘制学习笔记简单总结
重点在supplier part是立创商城的编号,可以搜到。
Redis入门:四、配置RedisTemplate以及编写工具类
一、配置RedisTemplate 1、需要的依赖 <!--导入lombok插件,方便编写实体类会用到--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--导入redis依赖--> <dependency> <group
4路QSFP28接口能玩出什么花样?基于璞致VU13P开发板的100G网络测试方案
本文详细介绍了基于璞致PZ-VU13P-KFB开发板构建100G网络测试方案的实战指南。该方案充分利用板载Xilinx Virtex UltraScale+ FPGA的强大算力与4路QSFP28接口,涵盖从光模块选型、Aurora协议配置、开源Corundum方案部署,到误码率测试及散热优化的全链路流程,为高速网络设备研发与验证提供了可靠的硬件平台。
redisTemplate注入失败问题,NullPointerException(内含工具类)
存储java对象集合到redis的List结构中的需求,redisTemplate注入失败问题,NullPointerException(内含工具类)
深入探讨 VQ-VAE:理解变分量化自动编码器
VQ-VAE代表"Variational Quantized Variational Autoencoder",是一种生成模型,通常用于处理高维数据,如图像和音频。它的设计灵感来自于变分自动编码器(VAE)和量化方法,结合了它们的优点,使得 VQ-VAE 能够生成高质量的数据,并在数据表示上引入离散性。VQ-VAE 是一种强大的生成模型,结合了变分自动编码器和量化方法的优点。它在图像和音频生成、数据压缩和生成性对抗网络等领域具有广泛的应用。
Mixer-First Receiver适用于宽带阵列应用的接收机技术1
Mixer-First Receiver适用于宽带阵列应用的接收机技术1技术的背景单元级数字化阵列传统链路到Mixer-First链路的逻辑考虑三种场景小结 技术的背景 在文章《吊打全球的顶级毫米波数字阵列项目-MIDAS》中提到了DARPA在MIDAS项目中在毫米波实现宽带单元级数字化阵列用到了一个关键的叫做N-Path filter的技术,而这个技术同样出现在了《让微波射频工程师颤抖的芯片-MATRICs》的MATRICs芯片中。 为什么DARPA的各个合作研究机构选择这种技术?这篇来自Universi
SpringBoot 集成 Redis(附通用的Redis工具类)
SpringBoot 集成 Redis 一、Jedis Jedis 是 Redis 官方推荐的 java 连接开发工具,是使用 Java 操作 Redis 的中间件。 对应依赖: <!-- https://mvnrepository.com/artifact/redis.clients/jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis&
STM32_HAL库—PWM产生指定个数
(一)CubeMX设置: 1. 晶振配置(72M) 2. 引脚配置 3. 中断配置 4. 配置及实现方式 由上推出公式: 机器周期: (72MHz / 36) = 2MHz = 0.5us PWM周期: 0.5 * 100 = 50us = 20kHz 5. 主函数调用PWM函数 HAL_TIM_PWM_Start_IT(&htim3, TIM_CHANNEL_2); //此处一句后可直接进入中断 6. PWM溢出回调函数 void HAL_TIM_PWM_PulseFinished
SpringBoot整合Redis及Redis工具类封装
Maven依赖 SpringBoot采用的版本 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version&g...
9、硬件工程师笔试面试知识器件篇——三极管(2025版本)
本文全面介绍了三极管的基础知识与应用,包括其结构、类型、工作原理、工作状态、功能、应用场景及特性参数。详细探讨了三极管在信号放大、无线通信、音频设备及医疗设备中的具体应用,并深入分析了设计放大电路时如何平衡增益与噪声、优化偏置电路以提高稳定性、使用负反馈改善性能等关键问题。此外,文章还涵盖了高频电路设计、温度补偿策略、电磁干扰防护等实用内容,为硬件工程师提供了全面的技术参考和设计指导。
影像技术实战02:FFmpeg 镜头切分误检、漏检问题排查与基于场景变化的稳定分镜方案
本文介绍了基于FFmpeg的镜头切分技术在实际应用中的常见问题及解决方案。文章首先指出单纯使用select='gt(scene,0.4)'命令进行镜头检测存在误检、漏检等问题,包括黑场、字幕变化被误判为镜头切换,以及相似场景切换被漏检等情况。随后提出了一套四层架构的稳定解决方案:1)用FFmpeg提取候选镜头变化点;2)解析变化点时间和分数;3)通过后处理过滤异常点;4)按时间点切割视频片段并生成报告。文中详细展示了Python实现代码,包括场景点检测、时间间隔过滤等功能模块,为视频剪辑、影视解说等场景提供
提升工作幸福指数工具类 实用redisKey管理工具类
问题:实际工作中经常遇到要使用redis配合的业务场景,那么就避免不了定义redis的key,在实际业务中为了区分key经常需要对key进行业务拼接,如 user:info:id:123 。 遇到上述情况常规方案 伪代码如下: // 定义常量redisKey public static final String USER_INFO_ID= "user:info:id:"; // 将常量与变量拼接 String redisKey =USER_INFO_ID+"123"; // 使用拼接好的redis..
Outlook Express 6 (OE6) for Win7/Win8/Win10
英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。
Redis | 19.自定义RedisTemplate
文章目录0.前言1.序列化1.1.继承Serializable接口序列化对象1.2.数据转换成json字符串2.自定义RedisTemplate3.自定义RedisUtil 0.前言 对应视频: 26、自定义RedisTemplate 项目名字:spring-boot-redis 1.序列化 Redis只能存储json而无法直接存对象(session除外) 如果需要存储对象,则需要先将对象进行序列化 1.1.继承Serializable接口序列化对象 序列化方式是jdk序列化 可以看到这里存进Redi
NTscan扫描工具
ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。
霍尼韦尔SoftMaster使用说明
霍尼韦尔SoftMaster使用说明
redisTemplate存储hash结构时,如果value不是String类型怎么解决
2019独角兽企业重金招聘Python工程师标准>>> ...
深度学习工具包 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');```[](https://bitdeli.com/free "Bitdeli Badge")
RedisUtil工具类
给大家共享一个用redisTemplate操作Redis的小工具类,需要的直接拿去用即可! import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.springframework.data.redis.core.Red...
java --spring boot 框架集成redis缓存
首先需要主要 ,redis 集成到spring boot 中有好多不同种类的框架, 网上好多解决的有3中, 一种是 完全注解 方式, 如:需要在主程序中用:@EnableCaching 服务层用:@Cacheable和 @CacheEvict @Cacheable :当redis缓存中没有对应的数据时,向数据库查询,并将查询结果新增到redis缓存; @CacheEvict:此方法执行后,删除对应的redis缓存; 这里不详细讲解。 二种:Jedis 1:这是一个框架需要引用到...
SpringBoot整合Redis
最近学习了一下redis,并与SpringBoot进行了整合,在此与大家分享。 一、Redis 关于Redis的解释网上有很多,我在这里不做出多余解释,大家可以自行搜索,我在这里要提到的是,Redis与SpringBoot整合有两种方式,第一种是使用Jedis,它是Redis官方推荐的面向Java的操作Redis的客户端,第二种是使用RedisTemplate,它是SpringDat...
springboot项目集成Redis
springboot项目集成Redis
Redis学习笔记(四)——整合SpringBoot
每次学习到新的知识,最期待的一步就是整合SpringBoot,这真的很令人兴奋!废话少说,我们赶快开始进行SpringBoot整合Redis的学习!
使用shpringboot2.X 集成 redis 6.X
1,虚拟机的redis,要保证端口开放, cmd 打开,输入 telnet 端口 地址 , 如果win10 不能使用telnet 命令, 打开搜索“启动或关闭Windows功能” ,勾选telnet 2,打开虚拟机的端口 1.先查看防火墙是否开启的状态,以及开放端口的情况: systemctl status firewalld.service(查看防火墙开启还是关闭) sudo firewall-cmd --list-all(可以查看端口开放情况) 2.使用以下命令来开启或者关闭虚拟机的...
1292



被折叠的 条评论
为什么被折叠?



