Spring 多线程异步上传图片、处理水印、缩略图

Spring 多线程异步上传图片、处理水印、缩略图! 阅读详情

点击上方“芋道源码”,选择“设为星标”

管她前浪,还是后浪?

能浪的浪,才是好浪!

每天 10:33 更新文章,每天掉亿点点头发...

源码精品专栏

 

来源:blog.youkuaiyun.com/weixin_43074462/

article/details/101109369


使用环境

  • SpringBoot+FastDfs+thumbnailator

  • fdfs环境自己搞吧

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/ruoyi-vue-pro

  • 视频教程:https://doc.iocoder.cn/video/

thumbnailator

maven依赖:

<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.8</version>
</dependency>

工具类:

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;

@Component
public class PictureUtil {

    /**
     * 水印图片
     */
    private static File markIco = null;

    //开机静态加载水印图片
    static {
        try {
            markIco = new File(new File("").getCanonicalPath() + "/icon.png");
            LogUtil.info(PictureUtil.class, "水印图片加载" + (markIco.exists() ? "成功" : "失败"));
        } catch (Exception e) {
        }
    }

    /**
     * 加水印
     */
    public void photoMark(File sourceFile, File toFile) throws IOException {
        Thumbnails.of(sourceFile)
                .size(600, 450)//尺寸
                .watermark(Positions.BOTTOM_CENTER/*水印位置:中央靠下*/, 
                ImageIO.read(markIco), 0.7f/*质量,越大质量越高(1)*/)
                //.outputQuality(0.8f)
                .toFile(toFile);//保存为哪个文件
    }

    /**
     * 生成图片缩略图
     */
    public void photoSmaller(File sourceFile, File toFile) throws IOException {
        Thumbnails.of(sourceFile)
                .size(200, 150)//尺寸
                //.watermark(Positions.CENTER, ImageIO.read(markIco), 0.1f)
                .outputQuality(0.4f)//缩略图质量
                .toFile(toFile);
    }

    /**
     * 生成视频缩略图(这块还没用到呢)
     */
    public void photoSmallerForVedio(File sourceFile, File toFile) throws IOException {
        Thumbnails.of(sourceFile)
                .size(440, 340)
                .watermark(Positions.BOTTOM_CENTER, ImageIO.read(markIco), 0.1f)
                .outputQuality(0.8f)
                .toFile(toFile);
    }
}

这个插件很好用,只需集成调用即可,我记得我还试过另外几个,需要另外在linux下配置.so文件的依赖等等,查了半天也没弄明白,很麻烦,这个方便。

这个插件又很不好用,必须要先调整尺寸,才能加水印,而且调整尺寸简直是负压缩。压了分辨率图片还能变大那种。但是简单嘛,这块不是重点。

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/yudao-cloud

  • 视频教程:https://doc.iocoder.cn/video/

线程池

使用springboot线程池,方便易用,只需配置和加注解即可。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class PoolConfig {
    @Bean//return new AsyncResult<>(res);
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.initialize();  // 设置核心线程数
        executor.setCorePoolSize(4);  // 设置最大线程数
        executor.setMaxPoolSize(32); // 设置队列容量
        executor.setQueueCapacity(512); // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60); // 设置默认线程名称
        executor.setThreadNamePrefix("ThreadPool-"); // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}

避坑知识点:配置springboot线程池,类上需要@Configuration、@EnableAsync这两个注解,实际调用时,需要遵守一个规则,即在调用的方法的类上必须使用注解@EnableAsync,调用一个带有@Async的方法。

比如A类使用了注解@EnableAsync 在A类中调用B类的有@Async的方法,只有这样多线程才生效,A类内调用A类的@Async方法不生效。可以理解为Controller层使用@EnableAsync注解,Service层方法上标注@Async。这样在Controller层调用的Service方法会从线程池调用线程来执行。

异步逻辑:为什么要用多线程?

37da8160e4912a6cac625b84bb1b7776.png

我画了一张简单的示意图,在这个项目中,客户端一次上传10多张图片,每个图片单独上传,等待所有图片上传返回200后,继续执行操作,如果一步一步处理,客户端需等待服务器处理完所有逻辑,这样浪费没必要的时间。顾使用异步操作,客户端只需上传图片,无需等待服务器处理(我们服务器很辣鸡,一个10M的图可能要搞10多秒,见笑)

业务代码

@ApiOperation("上传业务图片")
@PostMapping("/push/photo/{id}/{name}")
public R pushHousingPhotoMethod(
        @ApiParam("SourceId") @PathVariable Integer id,
        @ApiParam("图片名称不约束,可不填则使用原名,可使用随机码或原名称,但必须带扩展名") @PathVariable(required = false) String name,
        @RequestParam MultipartFile file) throws InterruptedException, ExecutionException, IOException {
    String fileName = file.getOriginalFilename();
    String ext = StringUtils.substring(fileName, fileName.lastIndexOf('.'),fileName.length());
    File tempPhoto = File.createTempFile(UUIDUtil.make32BitUUID(), ext);
    file.transferTo(tempPhoto);//转储临时文件
    service.pushPhoto(id, name, tempPhoto);
    return new R();
}

业务代码里隐藏了一些项目相关的信息,就是某些名改了,嗯。

可以看到,使用StringUtils.substring(fileName, fileName.lastIndexOf(’.’),fileName.length());这句代码,调用apache.common.lang3工具类获取出了扩展名,因为扩展名对图片处理工具类有用,他通过扩展名识别图片格式,所以这个必须有,如代码,生成了一个使用随机码命名,但带有.png扩展名的临时文件,保存在默认临时路径以供处理。File.createTempFile(UUIDUtil.make32BitUUID(), ext);是生成临时文件的方法,UUIDUtil也很简单,我贴出来吧,省着还要找

注意:controller类上需要标注注解@EnableAsync

/**
 * 生成一个32位无横杠的UUID
 */
public synchronized static String make32BitUUID(){
    return UUID.randomUUID().toString().replace("-","");
}

避坑知识点:Spring使用MultipartFile接收文件,但不能直接把MultipartFile传下去处理,而是保存为临时文件,并不是多此一举。因为MultipartFile也是临时文件,他的销毁时间是你这个Controller层方法return的时候。

如果不使用异步,是可以在调用的方法里去处理MultipartFile文件的,但如果使用异步处理,肯定是这边线程还没处理完,那边Controller层已经return了,这个MultipartFile就被删除了,于是你的异步线程就找不到这张图了。那还处理个啥,对吧。所以需要手动保存为自己创建的临时文件,再在线程中处理完把他删掉。

贴Service层Impl实现类代码

@Async
public void pushHousingPhoto(Integer id,String name,File file) throws InterruptedException, ExecutionException, IOException {
    //存储FDFS表id
    Long startTime = System.currentTimeMillis();
    Integer[] numb = fastDfsService.upLoadPhoto(StringUtils.isBlank(name) ? file.getName() : name, file).get();
    SourcePhotosContext context = new SourcePhotosContext();
    context.setSourceId(id);
    context.setNumber(numb[0]);
    context.setNumber2(numb[1]);
    //保存图片关系
    sourcePhotosContextService.insertNew(context);
    Long endTime = System.currentTimeMillis();
    LogUtil.info(this.getClass(),"source [ "+id+" ] 绑定图片 [ "+name+" ] 成功,内部处理耗时 ["+ (endTime-startTime) +"ms ]");
    //return new R();
}

这里的number和number2分别是带水印的原图和缩略图,context是个表,用来存图片和缩略图对应fdfs路径的,就不贴了。可见这个方法上带有注解@Async 所以整个方法会异步执行。

加水印处理写到fdfs的service里了,这样不算规范,可以不要学我:

@Override
public Future<Integer[]> upLoadPhoto(String fileName, MultipartFile file) throws IOException {
    String ext = StringUtils.substring(fileName, fileName.lastIndexOf('.'));
    //创建临时文件
    File sourcePhoto = File.createTempFile(UUIDUtil.make32BitUUID(), ext);
    file.transferTo(sourcePhoto);
    return upLoadPhoto(fileName, sourcePhoto);
}

@Override
public Future<Integer[]> upLoadPhoto(String fileName, File sourcePhoto) throws IOException {
    String ext = StringUtils.substring(fileName, fileName.lastIndexOf('.'));
    //创建临时文件
    File markedPhoto = File.createTempFile(UUIDUtil.make32BitUUID(), ext);
    File smallerPhoto = File.createTempFile(UUIDUtil.make32BitUUID(), ext);
    //加水印 缩图
    pictureUtil.photoMark(sourcePhoto, markedPhoto);
    pictureUtil.photoSmaller(markedPhoto, smallerPhoto);
    //上传
    Integer markedPhotoNumber = upLoadPhotoCtrl(fileName, markedPhoto);
    Integer smallerPhotoNumber = upLoadPhotoCtrl("mini_" + fileName, smallerPhoto);
    //删除临时文件
    sourcePhoto.delete();
    markedPhoto.delete();
    smallerPhoto.delete();
    Integer[] res = new Integer[]{markedPhotoNumber, smallerPhotoNumber};
    return new AsyncResult(res);
}

使用了方法重载,一个调用了另一个,方便以后处理MultipartFile和File格式的图片都能使用,可以见到使用了Future<Integer[]>这个东西作为返回值,完全可以不这么做,正常返回就行。我懒得改了,这也是不断探索多线程处理图片的过程中,遗留下来的东西。

在service中fastDfsService.upLoadPhoto(StringUtils.isBlank(name) ? file.getName() : name, file).get()这句就是得到了这个future的内容,可以去掉.get() 和Future<>。可见这一个小小的异步功能,其实走过了很多弯路。future其实是异步调用方法时,从.get()等待异步处理的结果,等待得到结果后获取内容并执行。现在使用spring线程池处理,已经不需要这样做了。

以上,希望你在实现这个功能时可以少走弯路。

附总体示意图:

aa2259369b13309a91a08949a4e7b522.png

欢迎加入我的知识星球,一起探讨架构,交流源码。加入方式,长按下方二维码噢:

2a4b67ee4108b419630f89e1194b6e6c.png

已在知识星球更新源码解析如下:

23c4a753597b68bfca29b04d69df6b46.jpeg

4d7cedb1bf6c63b0f21357cac6ede41b.jpeg

d265d600fcae502b24b0ff49b9f9ff55.jpeg

d423a27a0c77c47dc90001ab4f47fd4c.jpeg

最近更新《芋道 SpringBoot 2.X 入门》系列,已经 101 余篇,覆盖了 MyBatis、Redis、MongoDB、ES、分库分表、读写分离、SpringMVC、Webflux、权限、WebSocket、Dubbo、RabbitMQ、RocketMQ、Kafka、性能测试等等内容。

提供近 3W 行代码的 SpringBoot 示例,以及超 4W 行代码的电商微服务项目。

获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。

文章有帮助的话,在看,转发吧。
谢谢支持哟 (*^__^*)
Spring Boot 多线程异步上传图片、处理水印、缩略图 我画了一张简单的示意图,在这个项目中,客户端一次上传10多张图片,每个图片单独上传,等待所有图片上传返回200后,继续执行操作,如果一步一步处理,客户端需等待服务器处理完所有逻辑,这样浪费没必要的时间。工具类获取出了扩展名,因为扩展名对图片处理工具类有用,他通过扩展名识别图片格式,所以这个必须有,如代码,生成了一个使用随机码命名,但带有.png扩展名的临时文件,保存在默认临时路径以供处理。文件的,但如果使用异步处理,肯定是这边线程还没处理完,那边Controller层已经return了,这个。 阅读详情

相关推荐

若依实现文件多线程批量上传案例

若依实现文件多线程批量上传案例

猿小白的博客 4809

spring mvc ajax异步上传图片,springMVC + ajaxfileupload异步上传图片预览,裁剪并保存图片...

1、整体效果图: 2、实现原理:(1)利用input的onchange事件异步上传图片到服务器(2)获取上传图片的相对地址,回显到img标签中(3)利用jcrop裁剪图片,提交给后台裁剪的起始坐标,宽度、高度(4)后台裁剪图片并保存3、用到的插件:(1)JCrop图片裁剪插件(2)异步上传图片插件:Ajaxfileupload.js4、实现:(1)jsp关键代码:头像上传选择图片 保存头像控制样...

weixin_34653299的博客 494

基于Springmvc的上传图片并生成缩略图

本资源是基于Springmvc的图片上传案例,并对上传的图片添加了生成缩略图的功能。

Spring多线程异步上传图片处理水印,缩略图

写在前面: 本人代码和知识来源以优快云内各大神的贴为主。 但大神们的资源很细,往往一个功能要翻看很多贴排坑。 我将代码分享出来,并总结涉及到的知识点。 是无门槛完全使用指南。 使用环境: SpringBoot+FastDfs+thumbnailator fdfs环境自己搞吧 thumbnailator: maven依赖: <dependency> <gr...

拒绝八股文从我做起 950

hspice2016安装教程

试装系统:win10 64bit 安装包路径和安装路径最好都不要出现中文,一般选择默认安装在C盘。 1.解压安装包压缩文件。 2.以管理员身份运行hspice_vL-2016.03-2_win.exe。 3.点击“Next”。 4.选择“I accept”,然后点击“Next”。 5.点击“Next”。 6.一般默认安装路径即可,然后点击“Next”。 7.点击“Next”. 8.点击“Next”。 9.正...

谢谢关注“小鱼教你模数电”,各平台同号 1万+

Ubuntu 22.04远程桌面终极指南:从零配置RDP到解决黑屏问题

本文提供了一份Ubuntu 22.04远程桌面配置的终极指南,详细讲解了如何从零开始安装和配置RDP服务,并重点解决了连接后常见的黑屏问题。通过分析会话冲突、修复启动脚本及配置权限策略,帮助用户实现稳定、高效的远程桌面连接,优化分辨率、禁用锁屏,打造无缝的远程工作体验。

sony5的博客 1382

Java实战:Spring多线程异步上传图片、处理水印、缩略图

本文将详细介绍如何使用Spring框架实现多线程异步上传图片、添加水印和生成缩略图。我们将深入探讨Spring异步处理机制,以及如何利用Java并发编程库实现高效的多线程处理。

oandy0的博客 2446

W5500+STM32F103C8T6进行TCP通信(modbus)

一路生花一、w5500资料二、modbus通信三、从机代码四、总结五、参考 一、w5500资料 w5500的资料就放在下面了,单纯的客户端和其他模式上面有教程 https://www.aliyundrive.com/s/enPnnZgNtpE 二、modbus通信 Modbus RTU通信时使用的数据帧结构如下图,而Moubus TCP通信的数据帧和这个稍微不一样,没有crc检验,因为tcp本就是一种可靠传输协议 这里是Modbus TCP数据帧 公共功能码定义 三、从机代码

junseven164的博客 5778

Spring Boot+Vue头像处理实战:多尺寸存储与裁剪压缩方案

在现代Web应用中,图片处理是提升用户体验的关键技术环节。其核心原理涉及文件上传、存储策略、图像算法处理及前端交互等多个层面。从技术价值看,高效的图片处理能显著减少带宽消耗、提升页面加载速度,并适配不同终端显示需求。常见的应用场景包括社交平台用户头像、电商商品图、内容管理系统配图等。本文聚焦用户头像这一高频场景,通过Spring Boot后端结合Thumbnailator库实现图片的智能裁剪与多尺寸压缩,并利用Vue前端配合Cropper.js提供实时预览与交互式裁剪功能,构建了一套完整的“两张大头照”处理

weixin_33725126的博客 377

手把手教你用Xilinx SelectIO IP核搞定ADS42LB69高速ADC的DDR数据采集(附仿真调试技巧)

本文详细介绍了如何使用Xilinx SelectIO IP核实现ADS42LB69高速ADC的DDR数据采集,包括IP核配置、仿真验证和硬件调试技巧。通过精准的时序控制和实战调试方法,解决高速数据采集中的时序对齐问题,提升系统稳定性和可靠性。特别适合FPGA工程师和高速ADC接口设计者参考。

weixin_42533622的博客 153

国科大作业考试资料《人工智能原理与算法》2024新编-第三次作业整理

1. 你的目标是让机器人走出迷宫。机器人面朝北,开始位置在迷宫中间。你可以让机器人转向面朝东、南、西或北。你可以让机器人向前走一段距离,在撞墙之前它会停步。 (1)将问题形式化。状态空间有多大? (2)在迷宫中游走,在两条路或更多路交叉的路口可以转弯。重新形式化这个问题。现在状态空间有多大? (3)从迷宫的任一点出发,我们可以朝四个方向中的任一方向前进直到可以转弯的地方,而且我们只需要这样做。重新对这个问题进行形式化。我们需要记录机器人的方向吗? 2. 传教士和野人问题

MatsumotoChrikk 984

工程化落地实战:从评估、优化到部署的完整体系

在软件开发和算法工程领域,将代码或模型转化为稳定、高效、可维护的生产服务是一个关键挑战。这涉及到从概念验证到工业级交付的系统性过程,其核心在于建立一套完整的工程化体系。该体系通常遵循评估、优化、部署的闭环逻辑。评估环节通过基准测试、性能剖析等手段量化系统健康度,为优化提供数据依据。优化则针对性能瓶颈和资源效率,运用缓存策略、并发编程、算法改进等技术手段提升系统能力。最终,通过容器化、CI/CD流水线及蓝绿发布等部署实践,实现服务的平滑上线与可靠运维。本文聚焦于这一完整链路,深入探讨了如何构建评估体系、实施系

weixin_34341229的博客 353

十五、SAP-物料需求计划(MRP)

业务逻辑、功能讲解、图文解析、章节总结

m0_72403327的博客 1094

【debug log】java启动线程实现异步批量上传文件过程中抛FileNotFoundException异常

前言:本人为还未毕业的实习小菜鸟,出于不泄露公司源码的考虑,以下代码均为简化版示例,其中详细逻辑和异常处理已省略。 初始场景: 现有一批量上传文件的接口 @PostMapping("/imgUpload") public String imgUpload(List<Multipartfile> files) { for(Multipartfile file : ...

ShadL-17的博客 1055

【YOLOv12改进trick】高效多尺度卷积注意力EMCAD_Block模块引入YOLOv12,实现涨点和效率提升,含创新点Python代码

EMCAD引入YOLOv12模块,实现高效多尺度注意力模块引入到YOLOv12中的快速涨点及效率提升

向上生长的程序媛的博客 852

RK3568 低功耗设计全解析:DVFS 策略与 PMIC 电源管理

本文深入解析RK3568处理器的低功耗优化方案。从硬件架构分析入手,阐述四核Cortex-A55的功耗特性及分层电源域设计。重点介绍DVFS动态调压调频技术,包括Linux内核配置方法及场景化策略设计。详细讲解RK809 PMIC的电源管理优化,提供外设电源域控制与休眠唤醒配置的实战案例。通过智能终端应用实例,展示待机功耗从280mA降至65mA的优化效果,并推荐功率测试工具。文章强调需要平衡性能与功耗,结合场景定制策略,并指出AI负载预测等未来优化方向,为RK3568开发者提供系统性的低功耗解决方案。

远程部署调试 运行安装 项目调试 二次开发 项目技术新 持续迭代 部分源码免费分享 2073

ThreadPoolExecutor实现文件上传批量插入数据

ThreadPoolExecutor实现批量插入

qq_36069670的博客 560

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

java 多线程文件传输_利用线程池上传大文件(一)

(文章本人原创,若转载请注明出处)在JDK1.5提供了一个线程池ThreadPoolExecutor,可以处理用户提交过来的线程。如果把要处理的任务比作盖一个大楼,那么每一个建筑工人就相当于一个线程,那么这个ThreadPoolExecutor就好像包工头,它来控制盖这个大楼需要多少个工人,何时招进新工人,何时辞退已经长时间没有事做的工人,等等此类事务。也就是说用户程序不断提交新的线程,Threa...

weixin_35858091的博客 1385

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

前端转后端之spring boot文件上传功能优化(线程池)

今天实现了一个小功能,为自己的小项目奠定了一个小基础,现在这个功能已经优化到了200ms左右,文件数组上传,目前还没有外加ftp服务器进行资源管理。为此记录一下自己的学习路线。 首先介绍一下线程池,我理解的线程池其实挺浅的,只能表面的说出其意义,之前大部分都在写单线程(普通io操作)比如一个文件上传获取 ,刚开始没接触线程池的时候是这样写的,直接遍历然后将文件以文件流进行读写,但是现在了解了多线程以及带有缓存的线程池就要用上了,目前效果还是不错的来了解下各种线程池吧; 1. Executors工厂创建线程

weixin_41443212的博客 802

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

上一篇: Nginx 可视化神器!复杂配置一键生成,监控管理一条龙!
下一篇: Elasticsearch母公司Elastic宣布裁员13%
公众号-芋道源码
博客等级 码龄10年 1631粉丝 377原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值