Hadoop(三) HDFS 使用

4.4使用Java API操作HDFS 4.4 阅读详情

目录

准备工作

HDFS API的使用

org.apache.hadoop.fs.FileSystem

org.apache.hadoop.fs.Path

org.apache.hadoop.fs.FsStatus

org.apache.hadoop.fs.FileStatus

org.apache.hadoop.fs.FSDataInputStream

org.apache.hadoop.fs.FSDataOutputStream

示例

常用客户端命令


准备工作

使用开发工具为idea

1.需要将hadoop的hdfs-site.xml, core-site.xml这两个配置文件拷贝到项目的resources目录下

2.需要在maven中引入

<dependency> 
    <groupId>org.apache.hadoop</groupId> 
    <artifactId>hadoop-client</artifactId> 
    <version>2.7.3</version> 
</dependency>

HDFS API的使用

org.apache.hadoop.fs.FileSystem

抽象类,定义了文件系统访问的一般步骤。涉及到具体要访问什么样的文件系统,由其子类实现
比方说分布式文件系统,本地文件系统等等,其子类如下

org.apache.hadoop.fs.Path

用于创建一个路径,来表示一个文件或目录。可以是普通的文件路径,也可以是URI

org.apache.hadoop.fs.FsStatus

表示文件系统的存储空间使用情况

org.apache.hadoop.fs.FileStatus

表示文件的相关属性

org.apache.hadoop.fs.FSDataInputStream

读入HDFS系统的文件接口

org.apache.hadoop.fs.FSDataOutputStream

向HDFS系统写入文件

示例

@Test
    // 读数据
    public void test() throws IOException {
        /**
         * 加载配置文件
         *
         * * 底层会加载一堆的配置文件:
         *          *
         *          * core-default.xml
         *          * hdfs-default.xml
         *          * mapred-default.xml
         *          * yarn-default.xml
         *
         * * 当前这个hdfs-site.xml文件就放置在这个项目中的src下。也就是classpath路径下。
         *          * 所以 FS在初始化的时候,会把hdfs-site.xml这个文件中的name-value对解析到conf中
         *          * 但是:
         *          * 1、如果hdfs-site.xml 不在src下, 看是否能加载???  不能
         *          * 2、如果文件名不叫做 hdfs-default.xml 或者 hdsf-site.xml  看是否能自动加载???  不能
         *          * 得出的结论:
         *          * 如果需要项目代码自动加载配置文件中的信息,那么就必须把配置文件改成-default.xml或者-site.xml的名称
         *          * 而且必须放置在src下
         *          *
         *          * 那如果不叫这个名,或者不在src下,也需要加载这些配置文件中的参数:
         *          * 必须使用conf对象提供的一些方法去手动加载
         *          conf.set("dfs.replication", "2"); #注意所有的值都是以字符串的形式传入
         */
        Configuration conf = new Configuration();

        //代码入口点,初始化hdfs文件系统
        FileSystem fs = FileSystem.get(conf);

        //通过fs读数据
        Path p = new Path("/user/centos/user");
        FSDataInputStream fis = fs.open(p);

        // 读取文件
        int len = 0;
        byte[] buff = new byte[1024];
        while((len = fis.read(buff)) != -1) {
            System.out.println(new String(buff,0,len));
        }

    }

    @Test
    //出现 winutil问题
    // 写入文件
    // 对hdfs的操作会更改namenode信息时,就会涉及到权限问题
    //* 更改操作用户有两种方式:
    //         * 1、直接设置运行的用户名为hadoop
    //         * VM arguments ;   -D HADOOP_USER_NAME=admin
    //         * 2、在代码中进行声明
    //         * System.setProperty("HADOOP_USER_NAME", "admin");

    public void test2() throws Exception{
        // 设置操作的用户名,防止出现权限问题
        System.setProperty("HADOOP_USER_NAME", "centos");
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(conf);
        Path p = new Path("/user/centos/t4.txt");
        FSDataOutputStream out = fs.create(p);
        out.write("the people's republic of china".getBytes());
        out.flush();
        out.close();
    }

    @Test
    // 向已经存在的文件,追加新内容
    public void test3() throws Exception{
        System.setProperty("HADOOP_USER_NAME", "centos");
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(conf);
        Path p = new Path("/user/centos/t4.txt");
        FSDataOutputStream append = fs.append(p);
        append.write("\n i love this computer! it's has big power.".getBytes());
        append.flush();
        append.close();
    }

    @Test
    // 删除文件
    public void test4() throws Exception {
        System.setProperty("HADOOP_USER_NAME", "centos");
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(conf);
        Path p = new Path("/user/centos/tt");

        // recursive 这个参数设为为true, 递归的删除它的子目录
        // 为false时如果该目录下有内容会报错
        fs.delete(p, true);
        fs.close();
    }

    @Test
    // 把hdfs内的文件复制到本地,或者说是下载文件
    public void test5() throws Exception {
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(conf);
        Path p = new Path("/user/centos/t4.txt");
        FSDataInputStream in = fs.open(p);

        FileOutputStream out = new FileOutputStream("g:/mr/tt.txt");
        IOUtils.copyBytes(in, out, 1024);
        in.close();
        out.close();
        fs.close();
    }

    @Test
    /**
     * 递归列出指定目录内的内容
     */
    public void test6() throws Exception {
        System.setProperty("HADOOP_USER_NAME", "centos");
        Configuration conf = new Configuration();

        FileSystem fs = FileSystem.get(conf);
        listDF(fs, new Path("/"));
        fs.close();
    }

    public void listDF(FileSystem fs, Path path) throws IOException {
        FileStatus[] statuses = fs.listStatus(path);
        for(FileStatus status : statuses) {
            if(status.isFile()) {
                System.out.println(status.getPath());
            } else {
                listDF(fs, status.getPath());
            }

        }
    }


    @Test
    /**
     * 测试配置的优先级
     * 1)客户端代码中设置的值 >(2)classpath下的用户自定义配置文件 >(3)然后是服务器的默认配置
     */
    public void test7() throws IOException {
        System.setProperty("HADOOP_USER_NAME", "centos");
        Configuration conf = new Configuration();
        conf.set("dfs.replication", "2");
        FileSystem fs = FileSystem.get(conf);
        Path p = new Path("/user/centos/t10.txt");
        FSDataOutputStream out = fs.create(p);
        out.write("the people's republic of china".getBytes());
        out.flush();
        out.close();
    }

    @Test
    /**
     * 列出指定目录下的文件及其块信息
     */
    public void test8() throws IOException {
        System.setProperty("HADOOP_USER_NAME", "centos");
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(conf);

        Path path = new Path("/user/centos");
        RemoteIterator<LocatedFileStatus> fsInfo = fs.listFiles(path, true);

        while(fsInfo.hasNext()) {
            LocatedFileStatus file = fsInfo.next();
            System.out.println("path:" + file.getPath());
            System.out.println("name:" + file.getPath().getName());
            System.out.println("len: " + file.getLen());
            System.out.println("replication:" + file.getReplication());

            BlockLocation[] blockLocations = file.getBlockLocations();

            for(BlockLocation bl : blockLocations) {
                System.out.println("hosts:" + Arrays.toString(bl.getHosts()));
            }
            System.out.println("============================");
        }

        Path path2 = new Path("/user/centos/t4.txt");
        System.out.println(fs.getFileStatus(path2).getLen());
        System.out.println(fs.getFileStatus(path2).getReplication());
        System.out.println(fs.getFileStatus(path2).getBlockSize());

    }

@Test
    /**
     * 统计hdfs中文件大小小于blocksize的文件占比
     */
    public void test12()   {
        // fs.getFileStatus(path2).getLen(); 可以直接使用这个查看文件的大小
        // fileStatus.getBlockSize() 这个返回的是这个文件的所设定的块大小
        System.setProperty("HADOOP_USER_NAEM", "centos");
        Configuration conf = new Configuration();

        try {
            FileSystem fs = FileSystem.get(conf);
            FileStatus[] fileStatuses = fs.listStatus(new Path("/"));
            Queue<FileStatus> queue = new LinkedList<>();
            queue.addAll(Arrays.asList(fileStatuses));
            // 统计有多少个文件块
            int countBlock1 = 0;
            // 统计少于文件块大小的块
            int countBlock2 = 0;
            FileStatus fileStatus = null;

            while ((fileStatus = queue.poll()) != null) {
                try {
                    if (fileStatus.isDirectory()) {
                        queue.addAll(Arrays.asList(fs.listStatus(fileStatus.getPath())));
                    } else if (fileStatus.isFile()) {
                        System.out.println("file name: " + fileStatus.getPath() + ", size: " + fileStatus.getLen()/(1024*1024) + " mb");
                        BlockLocation[] fileBlockLocations = fs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen());

                        for(BlockLocation bl : fileBlockLocations) {
                            countBlock1 ++;
                            if(bl.getLength() < fileStatus.getBlockSize()) {
                                countBlock2++;
                            }
                        }
                    }
                } catch (Exception e) {

                }
            }

            System.out.println("scale: " + (double)countBlock2 / countBlock1);

        } catch (Exception e) {

        }


    }

    @Test
    /**
     * 统计系统中文件的平均副本数
     */
    public void test13() {
        System.setProperty("HADOOP_USER_NAME", "centos");
        Configuration conf = new Configuration();
        int totalFile = 0;
        int totalReplication = 0;
        try {
            FileSystem fs = FileSystem.get(conf);
            // 刚开始因为,hadoop的用户名设置错误,导致这里获取不到信息
            RemoteIterator<LocatedFileStatus> listStatusIter = fs.listFiles(new Path("/"), true);
            while(listStatusIter.hasNext()) {

                LocatedFileStatus fileStatus = listStatusIter.next();
                if(fileStatus.isFile()) {
                    totalFile++;
                    totalReplication += fileStatus.getReplication();
                }
            }


        } catch (Exception e) {

        } finally {
            if(totalFile != 0)
                System.out.println("average replication : " + totalReplication / totalFile);
        }

    }

    @Test
    /**
     * 统计系统中文件的平均block
     */
    public void test14() {
        System.setProperty("HADOOP_USER_NAME", "centos");
        Configuration conf = new Configuration();
        int totalFile = 0;
        int totalBlock = 0;
        try {
            FileSystem fs = FileSystem.get(conf);
            RemoteIterator<LocatedFileStatus> fileStatusIter = fs.listFiles(new Path("/"), true);
            while(fileStatusIter.hasNext()) {
                LocatedFileStatus fileStatus = fileStatusIter.next();
                if(fileStatus.isFile()) {
                    totalBlock += fileStatus.getBlockLocations().length;
                    System.out.println(fileStatus.getBlockLocations().length);
                    totalFile ++;
                }

            }
        } catch (Exception e) {

        } finally {
            if(totalFile != 0) {
                System.out.println("average block " + (double)totalBlock / totalFile);
            }
        }
    }

    /**
     * 统计HDFS整个文件系统中的不足指定数据块大小的数据块的比例
     *
     *
     */
    @Test
    public void test15() {
        System.setProperty("HADOOP_USER_NAME", "centos");
        Configuration conf = new Configuration();
        int totalBlock = 0;
        int count = 0;
        try {
            FileSystem fs = FileSystem.get(conf);


            RemoteIterator<LocatedFileStatus> fileStatusIter = fs.listFiles(new Path("/"), true);
            while(fileStatusIter.hasNext()) {
                LocatedFileStatus fileStatus = fileStatusIter.next();
                if(fileStatus.isFile()) {
                    totalBlock += fileStatus.getBlockLocations().length;

                    for(BlockLocation bl : fileStatus.getBlockLocations()) {
                        if(bl.getLength() < fileStatus.getBlockSize()) {
                            count ++;
                        }
                    }
                }
            }
        } catch (Exception e) {

        } finally {
            System.out.println((double)count / totalBlock);
        }
    }

 

常用客户端命令

0.直接在命令行,输入hadoop, hadoop fs, hdfs fs
  都会给出相应的命令提示

1. hadoop fs 与 hdfs dfs 等价
   列出hdfs 文件操作的所有相关命令
   
2. hadoop fs -help command-name
   列出某个命令的帮助信息
   
3. hadoop fs -ls direct-path
    列出某个目录内下的内容
	
4. hadoop fs -mkdir /data
   在hdfs上创建目录
   
5. hadoop fs -moveFromLocal source dest
    将本地文件移到hdfs上
	
	hadoop fs -copyFromLocal source dest
	将本地文件拷贝到hdfs上
	
	hadoop fs -copyToLocal source dest
	 拷贝hdfs文件到本地
	 
	hadoop fs -cp source dest
	在hdfs上拷贝文件到系统的其他目录
	
	hadoop fs -mv source dest
	在hdfs上移动文件到系统的其他目录
	
	hadoop fs -get source dest
	下载hdfs文件到本地
	
	hadoop fs -getmerge source dest
	下载多个hdfs文件到本地,且只生成一个文件
	
	hadoop fs -put source dest 
	上传本地文件到hdfs
	
	hadoop fs -rm filename
	删除hdfs上的某个文件
	
	hadoop fs -rmdir direct-name
	删除文件夹
	
	
	
6. hadoop fs -cat /centos/hello.txt
   查看hdfs上的文件
   
7. hadoop fs -appendToFile source dest
   追加文件到原有的文件
   如果目标文件不存在会创建
   
9. hadoop fs -tail /centos/hello
   显示一个文件末尾
   
10. hadoop fs -chmode 777 /centos/hello
   修改权限
   
11. hadoop fs -chown root:root /centos/hello
   修改文件所有者
   
12. hadoop fs -df -h path
   统计hdfs 文件系统可用空间信息
   
13. hadoop fs -du -h path
   统计文件夹大小信息

 

Hadoop 三大组件之HDFS hadoop三大组件之HDFS分布式文件存储 阅读详情

相关推荐

Hadoop(三)HDFS 原理

HDFS核心的设计思想   HDFS 集群中,主要的角色有 NameNode 和 DataNode 两大角色 (SecondaryNamenode 和 Client);   NameNode 负责管理文件系统的元数据,并响应 Client 的请求;   DataNode 负责存储用户的文件块(block),进行读写文件,并向 NameNode 发送心跳信息。   文件会按照固定的大小切分成块(block),每一个 block 的默认大小为 128M;   每一个 block 都会存在多个副本,形成备份存在于

qq_41620635的博客 3888

Hadoop学习篇(二)——HDFS编程操作1

在前两篇文章中,我们已经介绍了HDFS的理论基础以及命令行的基本操作。 但是,在实际中我们使用HDFS的平台时,是不可能全部进行命令行操作的。一定是要与编程结合起来进行的。所以,本篇将介绍HDFS相关的一些编程操作。 上篇链接: Hadoop学习篇(二)——HDFS Hadoop学习篇(二)——HDFS实践操作 Hadoop学习篇(二)——HDFS编程操作1 说明:如涉及到侵权,请及时联系我,并在第一时间删除文章。 2.3 HDFS编程操作 HDFS有很多常用的Java API,这里我们用Java API模

qq_17732621的博客 691

解析Hadoop三大核心组件:HDFS、MapReduce和YARN

在大数据时代,Hadoop作为一种开源的分布式计算框架,已经成为处理大规模数据的首选工具。它采用了分布式存储和计算的方式,能够高效地处理海量数据。Hadoop的核心由三大组件组成:HDFS、MapReduce和YARN。本文将为您逐一介绍这三个组件。

阿莫夕林的博客 1万+

使用java API 操作

了解HDFS Java API掌握使用Java API操作HDFS

m0_63560941的博客 1539

QT使用openssl实现RSA加解密

使用openssl生成公私钥,随后用QT对相应的信息进行RSA加解密

weixin_42098322的博客 3871

计算机考研408复试题汇总

TCP连接是全双工的,两端都可以先挥手 其中一端完成数据发送任务后,发送一个FIN包来终止,另一端针对这个FIN包回复确认包, 直到另一端也发送请求终止数据包FIN,另一端作出确认应答,并且还要发送一个ACK=1表示确认号有效,如果没有收到这个就可以进行重传.

ca1m4n的博客 1万+

php通过shell调用Hadoop的方法

1.php代码(index.php) body{background-color:red} --> --> --> <?php header('Content-type: text/html; charset=UTF8'); #phpinfo(); $jiaoben = $_GET['jiaoben']; echo "执行Hadoop的log信息:"; $ret= syst

lzq123_1的专栏 2534

Linux内核4.14版本——drm框架分析(1)——drm简介

本文介绍了DRM架构的发展历史、驱动框架以及简单示例,旨在帮助读者了解DRM架构的形成、功能流程实现。

phmatthaus的专栏 2575

Hadoop HDFS (3) JAVA访问HDFS

现在我们来深入了解一下Hadoop的FileSystem类。这个类是用来跟Hadoop的文件系统进行交互的。虽然我们这里主要是针对HDFS,但是我们还是应该让我们的代码只使用抽象类FileSystem,这样我们的代码就可以跟任何一个Hadoop的文件系统交互了。在写测试代码时,我们可以用本地文件系统测试,部署时使用HDFS,只需配置一下,不需要修改代码了。 在Hadoop 1.x以后的版本中引入

Norris的专栏 5408

使用机器学习算法预测黄金价格

在本文中,我们将使用线性回归、XGBoost和LSTM这三种不同的机器学习算法来预测黄金价格。接下来,我们使用线性回归、XGBoost和LSTM分别建立了模型,并进行了训练和预测。这些机器学习算法可以帮助我们对黄金价格进行预测,但请注意,市场价格受多种因素影响,因此预测结果可能并不完全准确。接下来,我们需要对数据进行一些预处理,以便用于机器学习模型的训练和测试。我们将使用80%的数据作为训练集,20%的数据作为测试集。最后,我们将绘制每个模型的预测结果,并将其与实际价格进行比较,以评估模型的性能。

QromMatlab的博客 1322

关于Sybase ASE数据库的license以及试用版过期的问题的解决方案

当用户从Sybase官网上下载了ASE15.0.2以后,如果选择了安装Express Edition或者Developer Edition,基本上不会碰到什么问题,除了有些功能受限以下。 但大多数可能选择了Enterprise Edition for Evaluation类型,即企业版试用。都会碰到这样的问题,即一个月以后,license过期,无法启动server。于是很郁闷,可能大部分人,会选...

iihero@CSDN 794

Hadoop三大组件之HDFS入门

一切皆文件,学好仓库才能入门啊

qq_43325476的博客 2231

机床上位机实战:CNC设备数据采集+工艺参数存储全流程(附C#代码+SQL设计)

如果能正常输出转速和状态,说明通信通了——这步是基础,没通的话别往下走,先查CNC的IP对不对、Modbus功能有没有开、地址是不是错了(我当初卡了2小时,发现是Fanuc的Modbus从站地址设成了2,不是默认1)。这篇文章就把整个开发过程拆透:从CNC通信协议选型,到数据采集代码落地,再到工艺参数的数据库设计,连中间踩过的“Fanuc系统寄存器地址对应错”“断连后数据补传”这些坑都给大家说清楚,新手跟着做也能跑通。工艺参数要跟“工单”和“设备”绑定,不然查的时候不知道是哪个工单、哪台设备的参数。

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

Hadoop(三)HDFS

Hadoop(三)HDFS

ks_1998的博客 2127

如何学习总线技术

如何学习总线技术 以形象生动的比喻来描绘了总线技术的基本思想,指出了总线的基本分类和总线传输的基本原理,以及在学习过程中应当掌握的最基本的知识,对初学者有起到抛砖引入的作用。 0引言   如果一座只能容一个人来往的独木桥,两端的人都想要过桥,为了不拥挤、阻塞,那我们就得采取有效的办法。比如规定某段时间哪端的人过桥,另一端的人就等着该他过桥的时间段的到来,同时也还可以规定人多时要按先来后到或年

ce123的技术博客 8532

YOLOv5_DeepSORT_Pytorch训练自己的多目标跟踪模型

1 准备 环境配置:https://blog.csdn.net/weixin_50008473/article/details/115250986?spm=1001.2014.3001.5501 YOLOv5_DeepSORT_Pytorch代码地址: https://github.com/mikel-brostrom/Yolov5_DeepSort_Pytorch DeepSORT论文:https://arxiv.org/pdf/1703.07402.pdf 2 训练目标检测模型 训练自己的目标检测模

weixin_50008473的博客 1万+

Hadoop三大组件之——HDFS概述

HDFS的概述 HDFS产生背景 HDFS(Hadoop Distributed File System 分布式文件系统),源自于Goole于2003年10月发表的GFS论文,是GFS的克隆版,具有如下特点: (1)易于扩展的分布式文件系统 (2)运行在大量的普通廉价机器上 (3)为大量用户提供性能不错的文件存取服务 HDFS优点 (1)高容错性:数据自动保存多个副本(一般默认三个),副本丢失后,...

渐行渐近的岁月的博客 1803

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

Hadoop三大组件之HDFS

本文着重讲解了HDFS的一些简单操作以及浅显的说明了下HDFS在存储数据时的一些工作原理。

qq_22610595的博客 1536

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...

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

Hadoop三大框架之HDFS

随着数据量越来越大,在一个操作系统存不下所有的数据,那么就分配到更多的操作系统管理的磁盘中,但是不方便管理和维护,需要一种系统来管理多台机器上的文件,这就是分布式文件管理系统。HDFS是分布式文件管理系统中的一种。HDFS(Hadoop Distributed File System)是一个文件系统,用于存储文件,通过目录树来定位为文件。它是分布式的,由很多服务器联合起来实现其功能,集群中的服务器有各自的角色。使用场景:适合一次写入、多次读出的场景。

five小点心的博客 2417

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

【Hadoop】HDFS (三)

safemode。

大数据爱好者的博客 949

Hadoop三大组件之HDFS(二)

Hadoop 分布式文件系统 (HDFS) 提供了灵活且高效的文件管理方式,类似于 Linux 文件系统。本文将介绍常用的 HDFS 操作命令,帮助您更好地掌握 HDFS 的基本操作。会在 /user/username 目录下创建一个名为 myfolder 的新目录。选项可以使 Hadoop 递归地检查该文件夹中的所有文件和子文件夹并将其一并删除。选项,Hadoop 将不会删除文件夹(即使文件夹为空),因为。HDFS 的目录结构与 Linux 类似,顶层目录为。只处理单个文件的删除,与Linux略有不同。

m0_58076578的博客 1万+

hadoop系列三 ——HDFS操作

hdfs命令行客户端的常用操作命令 0、查看hdfs中的目录信息 hadoop fs -ls /hdfs路径 1、上传文件到hdfs中 hadoop fs -put /本地文件 /aaa hadoop fs -copyFromLocal /本地文件 /hdfs路径 ## copyFromLocal等价于 put hadoop fs -moveFromLocal /本地文件 /hdfs路...

heartless_killer的博客 308

Hadoop(三)——核心之一HDFS

上篇讲述了Hadoop分布式集群环境的搭建,其实重要是HDFS分布式文件系统的搭建,MapReduce主要是需要我们程序员来进行编写算法来进行逻辑运算的。这篇就重点来讲述一下HDFS(HadoopDistribute File System,也就是Hadoop分布式文件系统)。     一、HDFS的主要设计理念:     1、存储超大文件,这里的“超大文件”是指几百MB、GB甚至TB,PB级别的

学会改变自己——才能突破 5984

Hadoop三大核心之一HDFS

Hadoop三大核心有HDFS,MapReduce,YARN,下面我们先介绍一下分布式文件系统HDFS HDFS Hadoop Distributed File System 易于扩展的分布式文件系统,运行在大量普通机器上,提供容错机制,为大量用户提供性能不错的文件存取服务。 HDFS的设计目标是: 1.自动快速检测应对硬件错误 2.流式访问数据 3.移动计算比移动数据更加划算 4.简单一致性模型...

qq_38052208的博客 535

Hadoop(三):HDFS

1.概述 1.HDFS产出背景及定义 1.HDFS产生背景:随着数据量越来越大,在一个操作系统存不下所有的数据,那么就分配到更多的操作系统管理的磁盘中,但是不方便管理和维护,迫切需要一种系统来管理多台机器上的文件,这就是分布式文件管理系统。HDFS只是分布式文件管理系统中的一种 2.HDFS定义:HDFS(Hadoop Distributed File System),它是一个文件系统,用于存储文件,通过目录树来定位文件;...

weixin_44800710的博客 1730
上一篇: Hadoop(二) HDFS 底层原理解析
下一篇: Hadoop(四) MapReduce 原理
奋斗的周周
博客等级 码龄12年 73粉丝 41原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值