多线程实现断点续存

大文件上传如何做断点续传?全端+后端结合开发 断点续传(Resumable File Upload)是一种文件上传的技术,它允许在上传过程中出现中断或失败的情况下,能够从中断的位置继续上传,而不需要重新上传整个文件。这在处理大文件或不稳定的网络连接时非常有用。 阅读详情

原理

1.原理
其实很简单,无非是先获取要下的文件大小,然后在磁盘新建一个同样大小的文件,最后开几个线程分别下载文件的不同部分往磁盘写入。:p
2。实现
这只是一个简单的demo版本,存放下载信息的载体可以视情况使用配置文件和数据库(如:Android可以使用自带的sqlite)

一些说明:

  • 1.我为了模拟断点续存用了volatile 标志,每个线程下载4kb*1000后会自动停止并退出,这时候你可打开MP4文件发现后半部分是看不了的,因为还没下载 lol
  • 2.我下载的文件是我自己服务器上的,改下url就能下载了
  • 3.文件名的获取有些粗暴,这个有时间可以说下怎么解析比较好
  • 4.如果是大批多文件下载,可以建个线程池,扔里面下载,这样效率比较高
package servlet;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;


/**
 * Created by Coder on 2017/1/19.
 */

public class FileDownload {
    //线程同步变量 退出线程的标志
    public volatile boolean isExited = false;

    //文件的下载地址
    private String fileUrl;

    //文件的存放路径
    private String filePath;

    //要下载的文件名
    private String filename;

    //文件的长度
    private long length;

    //下载文件的线程的数量
    private static final int threadCount = 4;

    //配置文件
    private Properties properties;

    //文件
    private File downloadFile;
    private File propertiesFile;


    public FileDownload(String url, String filePath){
        this.fileUrl = url;
        this.filePath = filePath;
        properties = new Properties();
    }

    //对下载工作进行初始化
    public void init(){
        HttpURLConnection conn = null;
        RandomAccessFile raf = null;
        try {
            //获取网络文件流
            URL url = new URL(fileUrl);
            conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(3000);
            conn.setRequestMethod("GET");

//            if(conn.getResponseCode() == HttpStatus.sC_OK)
            //获取文件长度
            length = conn.getContentLength();
            //获取文件名,这里是截取URL的最后一个"\"的后面
            String str = conn.getURL().getFile();
            filename = str.substring(str.lastIndexOf('/')+1);

            if(length <= 0){
                return;
            }

            //创建本地文件路径
            File dir = new File(filePath);
            if(! dir.exists()){
                dir.mkdir();
            }

            downloadFile = new File(dir, filename);
          //初始化文件
            if(!downloadFile.exists() || downloadFile.length() != length){
                //将文件设置为要下载文件的大小
                raf = new RandomAccessFile(downloadFile, "rwd");
                raf.setLength(length);
            }

            propertiesFile = new File(dir, filename.substring(0, filename.lastIndexOf('.'))+".properties");
            //初始化配置文件
            if(!propertiesFile.exists() ){
                propertiesFile.createNewFile();
            }
            //第一次初始化配置文件时,往配置文件里写入文件信息
            if(propertiesFile.length() == 0){
                properties.setProperty("fileName", filename);
                properties.setProperty("fileUrl", fileUrl);
                properties.setProperty("filePath", filePath);
                properties.setProperty("fileLength", ""+length);
                for(int i=0; i<threadCount; i++){
                    if(i != threadCount-1){
                        properties.setProperty("thread"+i+"_start", ""+i*(length/threadCount));
                        properties.setProperty("thread"+i+"_end", ""+(i+1)*(length/threadCount));
                    }else{
                        properties.setProperty("thread"+i+"_start", ""+i*(length/threadCount));
                        properties.setProperty("thread"+i+"_end", ""+length);
                    }
                }
                FileOutputStream out = new FileOutputStream(propertiesFile);
                properties.store(out, "init my propertiesFile!!!");
            }
            //载入配置文件
            properties = new Properties();
            properties.load(new FileInputStream(propertiesFile));

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(raf != null){
                    raf.close();
                }
                if(conn != null){
                    conn.disconnect();                  
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    public void download(){
        for(int i=0; i<threadCount; i++){
            System.out.println(properties.toString());
            System.out.println("thread"+i+"_start");
            long start = Long.parseLong(properties.getProperty("thread"+i+"_start"));
            long end = Long.parseLong(properties.getProperty("thread"+i+"_end"));
            if(i != threadCount-1){
                new DownloadThread("thread"+i, start, end).start();
            }else{
                new DownloadThread("thread"+i, start, end).start();
            }
            System.out.println("thread"+i+"已经启动!!!!!");
        }

    }

    public void pause(){
        isExited = !isExited;
    }

    class DownloadThread extends Thread{
        private String threadName;
        private long start;
        private long end;

        public DownloadThread(String threadName, long start, long end){
            this.threadName = threadName;
            this.start = start;
            this.end = end;
            System.out.println(threadName+" start: "+start+" end: "+end);
        }
        @Override
        public void run() {
            HttpURLConnection conn = null;
            BufferedInputStream in = null;
            FileOutputStream out = null;
            RandomAccessFile raf = null;
            try {
                //获取网络文件流
                URL url = new URL(fileUrl);
                conn = (HttpURLConnection)url.openConnection();
                conn.setConnectTimeout(3000);
                conn.setRequestMethod("GET");

                in = new BufferedInputStream(conn.getInputStream());
                in.skip(start);

                raf = new RandomAccessFile(downloadFile, "rwd");
                raf.seek(start);
                byte[] buf = new byte[1024 * 4];
                int len = -1;
                int count = 0;
                while ((len = in.read(buf)) != -1 && !isExited) {
                    if(start+len < end){//还未下载完成
                        raf.write(buf, 0, len);
                        start += len;
                        properties.setProperty(threadName+"_start", ""+start);
                        properties.setProperty(threadName+"_end", ""+end);
                    }else{//此线程要下载的已经下载完成
                        raf.write(buf, 0, (int)(end-start));
                        start = end;
                        properties.setProperty(threadName+"_start", ""+start);
                        properties.setProperty(threadName+"_end", ""+end);
                        break;
                    }
                    System.out.println(threadName+" start:"+start+" end:"+end);
                   count++;
                   if(count == 1000){
                       pause();
                   }
                }
                //将配置文件保存
                out = new FileOutputStream(propertiesFile);
                properties.store(out, "download my file !!");

            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if(raf != null){
                        raf.close();
                    }
                    if(in != null){
                        in.close();                 
                    }
                    if(out != null){
                        out.flush();
                        out.close();
                    }
                    if(conn != null){
                        conn.disconnect();                  
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        FileDownload download = new FileDownload("http://192.168.1.107:8080/news/video/65.mp4", "D:/video/");
        download.init();
        download.download();        
    }

}
网络编程--JAVA之多线程下载 今天,我来针对java中的一些网络编程中的多线程下载来进行简单的解析。首先理解一下多线程下载的原理: - 如上图所示,有三个人A、B、C去下载MP4,当假设服务器的带宽网速是12M/s,那么三个人每人一个线程就平均每条线程可以分到4M/s 但是如果A将占据两条线程,那么现在总共就有4条线程了, 如图: 也就是说12M/s的网速平均每个线程是可以分到3M/s,那么A就分到了6M 阅读详情

相关推荐

用断点续存实现视频快速上传

需求:前台开启多线程,多次调用接口实现上传视频功能。 分析:1.前台将视频切割成多个切片,基本信息(切片大小sliceSize;切片起始位置sliceOffset;上传成功标记flag等)需要存放在本地数据库SQLLite中记录并作出一些处理。 2. 后台先创建一个总视频大小的临时文件,前台每调用一次接口就向临时文件里写入切片视频大小的字节。 代码如下: 控制层: /** * 上传视频 * * @param request * @return */ @PostMapping(valu

weixin_44215804的博客 301

断点续传的原理

文件断点续传是一种机制,允许在网络传输中的文件传输过程中出现断开连接或传输中断的情况下,能够恢复传输并继续传输未完成的部分。其原理如下:1):首先,服务器端和客户端需要支持文件断点续传功能。服务器必须能够接收并处理客户端请求的文件的部分内容,并且客户端必须能够发送和接收文件的部分内容。2):当文件传输开始时,客户端和服务器都会记录已成功传输的字节数或文件的偏移量。这些记录通常保存在服务器端的文件或数据库中。3):如果传输过程中发生中断,

顺其自然~专栏 2210

c/c++线程断点续传实现

c/c++线程断点续传实现 cocos2dx断点续传下载 具体可以去我博客中学习 http://blog.youkuaiyun.com/vpingchangxin/article/details/22309067

什么是断点续传?前端如何实现文件的断点续传

断点的由来是在下载过程中,将一个下载文件分成了多个部分,同时进行多个部分一起的下载,当某个时间点,任务被暂停了,此时下载暂停的位置就是断点了。而我们需要对FileList对象进行修改再提交,在之前的文章中知晓了这种提交的一些注意点,因为FileList对象不能直接更改,所以不能直接通过表单的.submit()方法上传提交,需要结合FormData对象生成一个新的数据,通过Ajax进行上传操作。不过,在显示文件信息的时候,可能这个文件之前之前已经上传过了,为了断点续传,需要判断并在界面上做出提示。

weixin_45525177的博客 1508

Java实现文件的断点续传(HTTP)

java实现文件断点续传

Java断点续传

使用Javaweb已经Java客户端,实现文件的断点续传功能,文档中包括客户端和服务端

java简单实现在线资源多线程下载,断点续存,限制最大正在下载数

为什么要使用多线程下载,断点续存,限制最大正在下载数 多线程下载已经提高了下载的效率,但是当一些特殊情况发生的时候,我们需要对程序进行处理,这样效率会更高。比如,断电断网等造成下载中断,那么我们下一次又要重新开始下载,这样效率底下,所以我们可以考虑使用断点下载。其原理主要是把每次每个线程的下载状况(已经下载的位置)保存到文件,下次读取出来,从上一次下载的位置继续下载,这样就大大提高了下载的效率。当...

jiatai_的博客 969

基于Jira与Confluence的企业知识库AI助手构建实战

检索增强生成(RAG)技术通过结合信息检索与大型语言模型,有效解决了AI在专业领域知识不足的问题。其核心原理是将外部知识库(如企业文档)进行向量化存储,在用户提问时进行语义检索,并将相关上下文注入提示词中,从而生成精准、有据可依的回答。这一技术架构在工程实践中价值显著,它无需重新训练模型即可让AI掌握特定领域的专业知识,大幅提升了回答的准确性与实用性。典型的应用场景包括智能客服、企业内部知识问答以及代码辅助等。本文以开源项目`dev-kostiuk/jira-confluence-ai-context`为例

weixin_42520448的博客 366

Python Tkinter 下载器 多任务下载+多线程下载+多任务断点续存

功能介绍: 这次的下载器特点:多线程 + 多任务 + 断点续存 视频演示: Python Tkinter 系列 - 下载器 界面: 轮子 文件大小 界面:Tkinter下载功能 :request多任务 :threading多线程:ThreadPoolExecutor断点续存:文本txt的增删改查程序左上角图标生成:base64 方法简介: 效果 方法简介

weixin_44500833的博客 2022

AutoDock Vina 对接计算(大批量)

AutoDock Vina是一种用于计算生物分子之间相互作用的计算工具,主要用于蛋白质和小分子(通常是潜在药物分子)之间的对接研究。它可以用于虚拟筛选、药物设计和生物分子结合位点的预测等多个应用领域。

MurphyStar的博客 1万+

自研SSD固件:从零实现固态硬盘底层存储控制系统

本文探讨了自主开发SSD固件的可行性及实现方案。分析表明,虽然NAND Flash控制协议标准化且存在开源参考实现,但开发仍面临FTL设计复杂度高、性能调优等挑战。推荐采用FPGA平台(如Xilinx Zynq-7000)搭配SLC NAND Flash的方案,预计开发周期9-12个月。系统采用分层架构设计,包含主机接口层、FTL层和闪存接口层,核心模块需实现NAND Flash底层驱动、地址映射管理和垃圾回收等功能。文中提供了关键数据结构和基础驱动代码示例,包括页读写、块擦除等操作。该方案着重解决NAND

电脑管家 1881

多线程FTP项目(3)—— socketserver版本多线程FTP项目

多线程FTP项目(3)—— socketserver版本多线程FTP项目 threading 版 ​ 本来是想自己写一个实现多进程的 FTP 项目的,也就是说不使用 socketserver 模块实现多线程 FTP 项目,但是我写到一半调试的时候发现,虽然可以实现多用户同时登录,但是在输入命令之后,客户端很容易被 “远程计算机直接断开连接”。目前还是不清楚出了什么问题,不过看了 socketserver 模块源码后,发现该模块的多线程实现是比较复杂的,所以我觉得出现这个 bug 很大可能是因为

ShiJieDeYinYu的博客 738

Cadence PSpice 模型1:基于自带库新建二极管的PSpice模型图文教程

使用Cadence PSpice进行电路图的仿真时,难免会遇到软件自带库中没有合适的元器件的情况,这就需要设计师自己新建元器件模型,本文详细介绍使用PSpice软件修改自带库的元器件模型的参数以得到自己需要的PSpice模型库的方法。

fydar的博客 4413

网络编程--JAVA之多线程下载后续:断点续存

这篇博客就是接在我上篇博客网络编程–JAVA之多线程下载的基础上来实现的。首先,我来说一下断点续存能解决啥问题: 假如当我们在进行MP4下载时,如果突然出现人为的中断或者意外的中断,那么当我们再次点击下载时,我们是希望下载的进度是接着上次中断的地方继续下载,而不是又重新的下载,这不是我们所希望的,那么断点续存就是解决这个问题的。 接着,我们还是来梳理一下断点续存的思路步骤: 要想继续在中断的位置

等待起飞_鎏的博客 1908

【智能车Code review】——小S与中S道路判断

基本思想: 找到中线的左拐点和右拐点,并且计算出两点之间的空间距离。通过限制空间距离,分为中S和小S。 注意这种情况:当20行以下的中线斜率比较陡,此时可以通过人为限制设定,将第0行的中线设置为拐点。 if (flag_centre_right_point == 0 && flag_centre_left_point == 1 && parameterB >= 0.5 && centre_left_point[0] >= 33) { .

hanhan的博客 6102

C语言关键字static的绝妙用途

为什么要说static妙,它确实是妙,在软件开发或者单片机开发过程中,大家总以为static就是一个静态变量,在变量类型的前面加上就自动清0了,还有就是加上static关键字的,不管是变量还是关键字,在局部变量中,变量仅限于局部可见,在全局区中,static变量或函数仅限于本文件可见,当然还有一个重要的特性被忽略了。。。。       就是static修饰的局部变量 它的数值 是上一次函数调用结

Bruce.yang的嵌入式之旅 5377

大文件上传:切片 + 断点续存 + woker多线程优化

切片上传、断点续存、woker多线程

weixin_66029924的博客 702

还原 Windows 环境变量的默认值

有时候,我们可能需要还原环境变量的默认值,以修复可能的配置问题或恢复系统的正常运行。如果您只想还原某个特定的环境变量,可以跳过删除其他变量的步骤,仅删除需要还原的变量即可。在“环境变量”对话框中,继续向下滚动到“系统变量”部分。请注意,在执行以下步骤之前,您应该备份当前的环境变量设置,以便在需要时可以还原。在删除所有需要还原的环境变量后,点击“确定”按钮关闭“环境变量”对话框。在“用户变量”部分,选择需要还原的变量,然后点击“删除”按钮。在“高级”选项卡下方的“环境变量”部分,点击“环境变量”按钮。

PvDeveloper的博客 6341

断点续存

package com.yang;import java.io.File; import java.io.IOException; import java.io.RandomAccessFile;public class DL extends Thread{private File src; //源文件 private File desc; //目标文件 private long from; /

tiantian_kuaile的博客 499

ROS局部路径规划器插件teb_local_planner流程梳理(上)

在我之前的文章《ROS导航包Navigation中的 Movebase节点路径规划相关流程梳理》中已经介绍过Move_base节点调用局部路径规划器插件的接口函数是computeVelocityCommands,接下来,我们就从这个函数入手梳理一下teb_local_planner功能包的工作流程。

慕羽★的博客 5165

假人有限元模型

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

python jieba wordcloud分词制作词云图

安装: pip install jieba -i https://pypi.tuna.tsinghua.edu.cn/simple 使用: 1、命令行使用 python -m jieba news.txt > cur_news.txt 现有txt文件 出现了一点小问题:无法解析中文的gbk编码。 后面发现即使txt用utf-8保存的也没用的,主要原因是,报错里面看fp.readline(),这个fp应该是一个python读取文件的对象。我们进入__main__.py里面看下这个源码。 看到源

weixin_44500833的博客 1524

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

python多线程下载编程_python支持断点续传的多线程下载示例

#! /usr/bin/env python#coding=utf-8from __future__ import unicode_literalsfrom multiprocessing.dummy import Pool as ThreadPoolimport threadingimport osimport sysimport cPicklefrom collections import n...

weixin_39916511的博客 199

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

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

python 多线程(续)

之前讲了多线程的一篇博客,感觉讲的意犹未尽,其实,多线程非常有意思。因为我们在使用电脑的过程中无时无刻都在多进程和多线程。我们可以接着之前的例子继续讲。请先看我的上一篇博客。 python 多线程就这么简单   从上面例子中发现线程的创建是颇为麻烦的,每创建一个线程都需要创建一个tx(t1、t2、...),如果创建的线程多时候这样极其不方便。下面对通过例子进行继续改进: player.py

雪飞_海 239
上一篇: java如何正确停止一个线程
下一篇: 打造Android中万能BaseAdapter
aNoobCoder
博客等级 码龄10年 2粉丝 52原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值