MapReduce-XML处理-定制InputFormat及定制RecordReader

基于Hadoop的网站流量日志分析系统设计与实现 网站流量日志分析是大数据领域最常见的应用场景之一。面对海量Nginx/Apache日志,传统工具难以高效处理,而Hadoop生态提供了完整的解决方案:HDFS负责分布式存储原始日志,MapReduce实现清洗、解析与指标统计,YARN进行资源调度,Hive则支持辅助查询校验。通过合理设计分层架构与统计口径,可有效提取PV、UV、热门页面等运营指标,并利用Combiner、自定义Partitioner等手段优化数据倾斜与Shuffle性能。该技术路线不仅适用于课程设计与毕业设计,也是理解大数据离线批处理流程的 阅读详情
这一篇说明如何自定义InputFormat以及RecordReader这两个组件,通过使用mapreduce处理xml文件格式的文件来说明其用法,这一个例子来自《hadoop硬实战》一书的技术点12讲解的用法,如果有说明得不清楚的可以自行进行查阅
下面就来说说这个实例要达到的目的以下是输入数据:
<configuration>
  <property>
    <name>hadoop.kms.authentication.type</name>
    <value>simple</value>
    <description>
      Authentication type for the KMS. Can be either &quot;simple&quot;
      or &quot;kerberos&quot;.
    </description>
  </property>
  <property>
    <name>hadoop.kms.authentication.kerberos.keytab</name>
    <value>${user.home}/kms.keytab</value>
    <description>
      Path to the keytab with credentials for the configured Kerberos principal.
    </description>
  </property>
  <property>
    <name>hadoop.kms.authentication.kerberos.principal</name>
    <value>HTTP/localhost</value>
    <description>
      The Kerberos principal to use for the HTTP endpoint.
      The principal must start with 'HTTP/' as per the Kerberos HTTP SPNEGO specification.
    </description>
  </property>
  <property>
    <name>hadoop.kms.authentication.kerberos.name.rules</name>
    <value>DEFAULT</value>
    <description>
      Rules used to resolve Kerberos principal names.
    </description>
  </property>
</configuration>
实现的结果:<name>标签中的数据提取出来做为key,把<value>标签中的提取出来做为值进行键值对的输出
hadoop.kms.authentication.kerberos.keytab       ${user.home}/kms.keytab
hadoop.kms.authentication.kerberos.name.rules   DEFAULT
hadoop.kms.authentication.kerberos.principal    HTTP/localhost
hadoop.kms.authentication.type  simple

实现步骤:
1.定制InputFormat实现方法:实现InputFormat接口,或者继承InputFormat的子类,主要实现以下两个方法:
List<InputSplit> getSplits(), 获取由输入文件计算出输入分片(InputSplit),解决数据或文件分割成片问题。
RecordReader<K,V> createRecordReader(),创建RecordReader,从InputSplit中读取数据,解决读取分片中数据问题

2.定制RecordReader实现方法:实现RecordReader接口(旧版API)继承RecordReader类(新版API),下面以新版API为例实现以下方法:

  public abstract void initialize(InputSplit split, TaskAttemptContext context ) throws IOException, InterruptedException;
  public abstract boolean nextKeyValue() throws IOException, InterruptedException;
  public abstract KEYIN getCurrentKey() throws IOException, InterruptedException;
  public abstract VALUEIN getCurrentValue() throws IOException, InterruptedException;
  public abstract float getProgress() throws IOException, InterruptedException;
  public abstract void close() throws IOException;
其中nextKeyValue(),getCurrentKey(),getCurrentValue()方法会在Mapper换执行过程中反复调用直到该MAP任务所分到的分片被完全的处理,hadoop1.2.1的源码如下:
public void run(Context context) throws IOException, InterruptedException {
    setup(context);
    try {
    //map通过这里反复调用RecordReader的方法
    while (context.nextKeyValue()) {
    //context.getCurrentKey()在MapContext的方法中调用相关RecordReader的方法
    /**
    * @Override
  * public KEYIN getCurrentKey() throws IOException, InterruptedException {
    * return reader.getCurrentKey();
  * }
    */
        map(context.getCurrentKey(), context.getCurrentValue(), context);
      }
    } finally {
      cleanup(context);
    }
  }

最核心的就是处理好迭代多行文本的内容的逻辑,每次迭代通过调用nextKeyValue()方法来判断是否还有可读的文本行,直接设置当前的Key和Value,分别在方法getCurrentKey()和getCurrentValue()中返回对应的值。在实现的代码中会有相应注释说明。

定制InputFormat:

import java.io.IOException;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class XMLInputFormat extends TextInputFormat {
	private static final Logger log = LoggerFactory.getLogger(XMLInputFormat.class);
	@Override
	public RecordReader<LongWritable, Text> createRecordReader(
			InputSplit inputSplit, TaskAttemptContext context) {
		try {
			return new XMLRecordReader(inputSplit, context.getConfiguration());
		} catch (IOException e) {
			log.warn("Error while creating XmlRecordReader", e);
			return null;
		}
	}
	@Override
	protected boolean isSplitable(JobContext context, Path file) {
		// TODO Auto-generated method stub
		return super.isSplitable(context, file);
	}
}
定义RecordReader:(这是xml文件处理的关键)

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

public class XMLRecordReader extends RecordReader<LongWritable, Text> {
	private long start;
	private long end;
	private FSDataInputStream fsin;
	private DataOutputBuffer buffer = new DataOutputBuffer();
	private byte[] startTag;
	private byte[] endTag;
	private LongWritable currentKey;
	private Text currentValue;
	public static final String START_TAG_KEY = "xmlinput.start";
	public static final String END_TAG_KEY = "xmlinput.end";
	public XMLRecordReader() {
	}
	/**
	 * 初始化读取资源以及相关的参数也可以放到initialize()方法中去执行
	 * @param inputSplit
	 * @param context
	 * @throws IOException
	 */
	public XMLRecordReader(InputSplit inputSplit, Configuration context) throws IOException {
		/**
		 * 获取开传入的开始和结束标签
		 */
		startTag = context.get(START_TAG_KEY).getBytes("UTF-8");
		endTag = context.get(END_TAG_KEY).getBytes("UTF-8");
		FileSplit fileSplit = (FileSplit) inputSplit;
		/**
		 * 获取分片的开始位置和结束的位置
		 */
		start = fileSplit.getStart();
		end = start + fileSplit.getLength();
		Path file = fileSplit.getPath();
		FileSystem fs = file.getFileSystem(context);
		/**
		 * 根据分片打开一个HDFS的文件输入流
		 */
		fsin = fs.open(fileSplit.getPath());
		/**
		 * 定位到分片开始的位置
		 */
		fsin.seek(start);
	}
	@Override
	public void close() throws IOException {
		fsin.close();
	}
	@Override
	public LongWritable getCurrentKey() throws IOException, InterruptedException {
		return currentKey;
	}
	@Override
	public Text getCurrentValue() throws IOException, InterruptedException {
		return currentValue;
	}
	@Override
	public float getProgress() throws IOException, InterruptedException {
		return fsin.getPos() - start / (float) end - start;
	}
	@Override
	public void initialize(InputSplit inputSplit, TaskAttemptContext context)
			throws IOException, InterruptedException {
		/*startTag = context.getConfiguration().get(START_TAG_KEY).getBytes("UTF-8");
		endTag = context.getConfiguration().get(END_TAG_KEY).getBytes("UTF-8");
		FileSplit fileSplit = (FileSplit) inputSplit;
		start = fileSplit.getStart();
		end = start + fileSplit.getLength();
		Path file = fileSplit.getPath();
		FileSystem fs = file.getFileSystem(context.getConfiguration());
		fsin = fs.open(fileSplit.getPath());
		fsin.seek(start);*/
	}
	@Override
	public boolean nextKeyValue() throws IOException, InterruptedException {
		currentKey = new LongWritable();
		currentValue = new Text();
		return next(currentKey, currentValue);
	}
	private boolean next(LongWritable key, Text value) throws IOException {
		/**
		 *  通过readUntilMatch方法查找xml段开始的标签,直到找到了,才开始
		 *  写xml片段到buffer中去,如readUntilMatch的第二个参数为false则不查找的过
		 *  程中写入数据到buffer,如果为true的话就边查找边写入
		 */
		if( fsin.getPos() < end && readUntilMatch(startTag, false)) {
			//进入代码段则说明找到了开始标签,现在fsin的指针指在找到的开始标签的
			//最后一位上,所以向buffer中写入开始标签
			buffer.write(startTag);
			try {
				/**
				 * 在fsin中去查找结束标签边查找边记录直到找到结束标签为止
				 */
				if(readUntilMatch(endTag, true)) {
					/**
					 * 找到标签后把结束标签的指针位置的偏移量赋值给key
					 * 把buffer中记录的整个xml完整片断赋值给value
					 */
					key.set(fsin.getPos());
					value.set(buffer.getData(), 0, buffer.getLength());
					return true;
				}
			} finally {
				buffer.reset();
			}
		}
		return false;
	}
	/**
	 * 读取xml文件匹配标签的方法
	 * @param startTag
	 * @param isWrite
	 * @return
	 * @throws IOException
	 */
	private boolean readUntilMatch(byte[] startTag, boolean isWrite) throws IOException {
		int i = 0;
		while(true) {
			/**
			 * 从输入文件只读取一个Byte的数据
			 */
			int b = fsin.read();
			if( b == -1) {
				return false;
			}
			/**
			 *  如果在查找开始标签则不记录查找过程,
			 *  在查找结束标签时才记录查找过程。
			 */
			if(isWrite) {
				buffer.write(b);
			}
			/**
			 * 判断时否找到指定的标签来判断函数结束的时间点
			 */
			if(b == startTag[i]) {
				i ++;
				if( i >= startTag.length) {
					return true;
				}
			} else {
				i = 0;
			}
			// see if we've passed the stop point:
			if (!isWrite && i == 0 && fsin.getPos() >= end) {
				return false;
			}
		}
	}
}
map阶段:

import static javax.xml.stream.XMLStreamConstants.CHARACTERS;
import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class XMLMapper extends Mapper<LongWritable, Text, Text, Text>{
	/**
	 *  从XMLRecordReader可以知道传入的value为指定的包含开始标签和结束标签
	 *  的一个片断
	 */
	@Override
	protected void map(LongWritable key, Text value, Context context)
			throws IOException, InterruptedException {
		String content = value.toString();
		System.out.println("--content--");
		try {
			//把value的值转化为一个XML的输入流,以便后继的处理
			XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(
					new ByteArrayInputStream(content.getBytes()));
			String propertyName = "";
			String propertyValue = "";
			String currentElement = "";
			/**
			 * 定义处理业务可以通过下面的main函数来看这段程序的实现的功能
			 */
			while (reader.hasNext()) {
				int code = reader.next();
				switch (code) {
				case START_ELEMENT:
					currentElement = reader.getLocalName();
					break;
				case CHARACTERS:
					if (currentElement.equalsIgnoreCase("name")) {
						propertyName += reader.getText();
					} else if (currentElement.equalsIgnoreCase("value")) {
						propertyValue += reader.getText();
					}
					break;
				}
			}
			reader.close();
			context.write(new Text(propertyName.trim()), new Text(propertyValue.trim()));
		} catch (XMLStreamException e) {
			e.printStackTrace();
		} catch (FactoryConfigurationError e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		String content = "<property><name>seven</name><value>24</value></property>";
		System.out.println("--content--");
		try {
			XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(
					new ByteArrayInputStream(content.getBytes()));
			String propertyName = "";
			String propertyValue = "";
			String currentElement = "";
			while (reader.hasNext()) {
				int code = reader.next();
				switch (code) {
				case START_ELEMENT:
					currentElement = reader.getLocalName();
					break;
				case CHARACTERS:
					if (currentElement.equalsIgnoreCase("name")) {
						propertyName += reader.getText();
					} else if (currentElement.equalsIgnoreCase("value")) {
						propertyValue += reader.getText();
					}
					break;
				}
			}
			reader.close();
			System.out.println(propertyName + " " + propertyValue);
		} catch (XMLStreamException e) {
			e.printStackTrace();
		} catch (FactoryConfigurationError e) {
			e.printStackTrace();
		}
	}
}
reduce阶段:

import java.io.IOException;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

public class XMLReducer extends Reducer<Text, Text, Text, Text>{
	private Text val_ = new Text();
	@Override
	protected void reduce(Text key, Iterable<Text> value, Context context)
			throws IOException, InterruptedException {
		for(Text val: value) {
			val_.set(val.toString());
			context.write(key, val_);
		}
	}
}
启动函数:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class JobMain {
	public static void main(String[] args) throws Exception{
		Configuration configuration = new Configuration();
		configuration.set("key.value.separator.in.input.line", " ");
		configuration.set("xmlinput.start", "<property>");
		configuration.set("xmlinput.end", "</property>");
		Job job = new Job(configuration, "xmlread-job");
		job.setJarByClass(JobMain.class);
		job.setMapperClass(XMLMapper.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);
		job.setInputFormatClass(XMLInputFormat.class);
		job.setNumReduceTasks(1);
		job.setReducerClass(XMLReducer.class);
		//job.setOutputFormatClass(XMLOutputFormat.class);
		FileInputFormat.addInputPath(job, new Path(args[0]));
		Path output = new Path(args[1]);
		FileOutputFormat.setOutputPath(job, output);
		output.getFileSystem(configuration).delete(output, true);
		System.exit(job.waitForCompletion(true) ? 0: 1);
	}
}
运行结果:


结论:

这里通过mapreduce对xml输入文件的处理说了InputFormat以及RecordReader的定制,下一篇将基于这个实例说明OutputFormat以及RecordWriter的定制,实例将把最后结果 输出为xml格式的文件,可参见《MapReduce-XML处理-定制OutputFormat及定制RecordWriter》。

XML_MR_Reader:使用 XML InputFormat Map Reduce XML_MR_Reader 使用 XML InputFormat 映射 Reduce。 这是一段代码,用于清理 Wiki XML 数据集并将其转换为带分隔符的文本。 从维基百科档案中提取电影数据进行分析。 提供了 Sample.xml。 如果您的 XML 结构发生变化,请查看 WikiMR 驱动程序以进行更改。 玩得开心!!! 立即下载

相关推荐

生物信息学名词解释 | K-mer (长度为k的短序列)

K-mer 何谓K-mer 所谓Kmer,即为一段长度为k的DNA片段,是由测序reads剪切一部分得到的。k为一个奇数,k=几,就为几mer。 比如:我的测序reads长度为100bp,我将这100bp打断成17bp的短片段,打断后的17bp段片段就叫17mer,可以获得(100-17+1)条k-mer序列。 Table1 k-mers for GTAGAGCTGT. k k-mers 1 G,T,A,G,A,G,C,T,G,T 3 GTA,TAG,AGA,GAG,AGC,GCT,CT

qq_50637636的博客 2万+

ranger-kms安装

使install.properties生效,在$RANGER_HOME/ranger-kms/ews/webapp/WEB-INF/classes/conf下生成kms-site.xml和dbks-site.xml具体配置文件。hadoop.security.key.provider.path 指定的是密钥提供者的类路径,是 Hadoop 通用安全配置的一部分。之后授权给hadoop权限,需要mkdir /etc/ranger 之后chown hadoop.hadoop /etc/ranger。

蘑菇丁的专栏 1133

汽车CAN总线硬件电路原理

汽车CAN总线硬件电路原理

飞行动力的博客 1万+

Hadoop KMS 透明加密配置以及测试

转载来自: http://blog.csdn.net/linlinv3/article/details/44963429 http://blog.csdn.net/yunduanyou/article/details/76461223 背景介绍     越来越多的用户关注安全问题,都在寻找一种有效的,方便的加密方式。hadoop提供了几种不同形式的加密,最底层的加密,加密所有

那又怎样?的博客 7043

MCU 微控制器,在实际项目中如何选型(以 STM32为例)

1.MCU 选型需要考虑的一些因素 2.案例:传感器设备的 MCU 选型

创享 AIOT 的专栏 1万+

使用PlotNeuralNet绘制深度学习网络图的基本操作

使用PlotNeuralNet绘制深度学习网络图的基本操作

weixin_46877907的博客 2115

大数据安全之 KMS 原理、配置、使用(含加密、证书等原理介绍,及Kerberos 集成)

摘要:Hadoop数据安全包括静态数据(HDFS透明加密)和传输数据安全。HDFS加密区域(EncryptionZone)实现透明加密,通过KMS(Key Management Server)管理密钥体系,包含EZK(加密区域密钥)和DEK(数据加密密钥)。配置过程涉及keystore创建、Kerberos认证设置及KMS服务部署。使用流程包括:1)创建加密区域和密钥;2)向加密区域写入数据(自动加密);3)读取数据(自动解密)。验证表明文件内容在磁盘上加密存储,通过HDFS命令可正常读取,实现了透明的数据

weixin_39724712的博客 1759

FPGA数据采集避坑指南:3PA1030 ADC的时钟相位、量程标志OVR与输出使能OE到底怎么用?

本文深入解析FPGA与3PA1030 ADC协同设计中的关键问题,包括时钟相位优化、OVR超量程监控和OE输出使能配置。通过实战案例和代码示例,详细探讨如何避免常见设计陷阱,提升数据采集系统的信噪比和稳定性,特别适合AD和FPGA开发者参考。

weixin_42620340的博客 1914

MapReduce处理xml文件(使用旧API)

1)MapReduce项目引入jar包:hadoop-streaming-2.6.5.jar 2)main函数主要代码段:JobConf jobconf = new JobConf(new Configuration(), MreMroParser.class); jobconf.setJobName("xmlParser"); //这里标记使用流式输入 jobconf.set("stream.r

bloncar的博客 1566

全局子程序 参数调用

为什么要子程序: 为了实现程序结构化,我们尽量使用不同功能的功能块来实现一些特定的功能, 子程序接口: 使用过程的注意事项,尤其是数组使用时的注意事项 从一个主程序中可以将参数传递到局部或全局子程序和函数中。 怎样传递参数有 2 种方式: 作为 IN 参数 变量值在主程序中保持不变。 这种传递方式也称为“ 值传递 (Call by Value)”。 作为 OUT 参数 子程序读取并更改该值,然后将新值写回到主程序中。 这种传递方式也称为“Call by Reference”。 举例说明 1 DEF MY

Eric_Yang1024的博客 1102

机器学习算法 —— LightGBM

本次我们选择英雄联盟数据集进行LightGBM的场景体验。英雄联盟是2009年美国拳头游戏开发的MOBA竞技网游,在每局比赛中蓝队与红队在同一个地图进行作战,游戏的目标是破坏敌方队伍的防御塔,进而摧毁敌方的水晶枢纽,拿下比赛的胜利。现在共有9881场英雄联盟韩服钻石段位以上的排位比赛数据,数据提供了在十分钟时的游戏状态,包括击杀数、死亡数、金币数量、经验值、等级……参考项目:机器学习系列入门系列[七]:基于英雄联盟数据集的LightGBM的分类预测。

ZShiJ的博客 712

Hadoop KMS 使用

Hadoop KMS配置 以hdfs的单机环境为例说明搭建过程 1. hdfs配置 1) 下载hadoop 2.6以上的版本,解压之后,配置HADOOP_HOME export HADOOP_HOME=/root/hadoop-2.7.4 export PATH=${PATH}:${HADOOP_HOME}/bin 2) 配置core-site.xml与hdfs-site.xml c...

mnasd的博客 2121

silero-vad 训练自己的数据

silero-vad 训练自己的数据

jacke121的专栏 821

MapReduce-XML处理-自定义InputFormat及自定义RecordReader

友情提示:更多有关大数据、人工智能方面技术文章请关注博主个人微信公众号:高级大数据架构师! 这一篇说明如何自定义InputFormat以及RecordReader这两个组件,通过使用mapreduce处理xml文件格式的文件来说明其用法,这一个例子来自《hadoop硬实战》一书的技术点12讲解的用法,如果有说明得不清楚的可以自行进行查阅下面就来说说这个实例要达到的目的以下是输入数据:&lt;co...

小宁哥博客 844

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

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

streaming api_XML的Streaming API简介(StAX)

StAX概述 自成立以来,用于XML处理的Java API(JAXP)提供了两种处理XML的方法-文档对象模型(DOM)方法(使用标准对象模型表示XML文档)和XML简单API(SAX)方法,该方法使用应用程序提供的事件处理程序来处理XML。 在JSR-173:XML的流API(StAX)中提出了这些方法的流替代方法。 它的最终版本于2004年3月发布,并成为JAXP 1.4的一部分(将包...

cusi77914的博客 469

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

KMS密钥管理服务(Hadoop)

为什么80%的码农都做不了架构师?>>> ...

weixin_34377065的博客 3132

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

用户认证——Kerberos集成Hadoop的配置

Hadoop Kerberos配置

zhangzhagn_的博客 3815

Hadoop开启Kerberos安全模式

Hadoop开启Kerberos安全模式, 基于已经安装好的Hadoop的2.7.1环境, 在此基础上开启Kerberos安全模式。 1.安装规划 已经安装好Hadoop的环境 10.43.159.7 zdh-7 hdfsone/zdh1234 Kerberos服务器 10.43.159.11 zdh-11 kerberos server 2.创建用户的k...

木木与呆呆的专栏 3585

大数据Hadoop系列之Hadoop Web控制台添加身份验证

1. 背景介绍 本文档介绍如何配置Hadoop HTTP Web控制台以要求用户身份验证。 默认情况下,Hadoop HTTP Web控制台(ResourceManager,NameNode,NodeManagers和DataNodes)允许访问而无需任何形式的身份验证。 可以将Hadoop HTTP Web控制台配置为使用HTTP SPNEGO协议(Firefox和Internet Explorer等浏览器支持)进行Kerberos身份验证。 此外,Hadoop HTTP Web控制台支持相当于Hado

m0_67392409的博客 2193

【大数据】Hadoop-Kms 安装及相关详细配置,看完你就会了

Hadoop KMS是基于Hadoop的KeyProvider API的加密密钥管理服务器,它提供了使用REST API通过HTTP进行通信的客户端和服务器组件。客户端是一个KeyProvider实现,使用KMS HTTP REST API与KMS交互。KMS及其客户端具有内置的安全性,它们支持HTTP SPNEGO Kerberos身份验证和HTTPS安全传输。KMS是一个Java Jetty web应用程序。KMS与Hadoop结合,可以实现HDFS客户端透明的数据加密传输以及细粒度的权限控制。

如切如磋,如琢如磨,臻于至善。 1833

Yarn模式下Mapreduce的内存参数理解以及xml参数配置

一、概述 MapReduce主要靠yarn进行资源分配,因此,进行MapReduce作业时,可以通过调节对应的yarn和hive参数优化MapReduce作业。Container是一个逻辑上的yarn资源容器; Container就是一个yarn的java进程,在Mapreduce中的AM,MapTask,ReduceTask都作为Container在Yarn的框架上执行,你可以在RM的网页上【8088端口】看到Container的状态。 二、yarn资源管理及设置 Yarn的ResourceM..

虎啸千峰的博客 1997

MapReduce-XML处理-定制OutputFormat及定制RecordWriter

这一篇紧接上一篇博客《MapReduce-XML处理-定制InputFormat及定制RecordReader》,上一篇是说明InputFormat和RecordReader,这里说明OutputFormat以及RecordWriter的定制,下面是 这次测试的要求: 输入数据:       hadoop.kms.authentication.type     simple

Qi.zheng 1884

[ Hadoop 3.2.1 官方文档 ] Hadoop 开启 Kerberos 安全模式

一. 介绍 本文档介绍了如何在安全模式下为Hadoop配置身份验证。将Hadoop配置为以安全模式运行时,每个Hadoop服务和每个用户都必须通过Kerberos进行身份验证。 必须正确配置所有服务主机的正向和反向主机查找,以允许服务彼此进行身份验证。可以使用DNS或etc/hosts文件配置主机查找。建议在尝试以安全模式配置Hadoop服务之前,具备Kerberos和DNS的相关知识。 Hadoop的安全功能包括身份验证,服务级别授权,Web身份验证和数据机密性。 二. 验证 2.1.固定用户帐户 启用服

张伯毅的专栏 6600

Hadoop 的三种运行模式_本地模式_伪分布式模式

演示的版本是:2.7.2 官方文档  Hadoop运行模式 Hadoop运行模式包括:本地模式、伪分布式模式以及完全分布式模式。 Hadoop官方网站:http://hadoop.apache.org/ 1、本地运行模式 a)  官方Grep案例 其实就是按照给定的条件找到符合条件的单词。 $ mkdir input //1、创建在hadoop-2.7.2文件下面...

底层码农 1万+

自定义MapReduce的InputFormat,提取指定开始与结束限定符间的内容

在编写MapReduce程序时,常用的TextInputFormat是以换行符作为Record分隔符的,即该行的内容作为MapReduce中map方法中的value,而该行头在文件中的偏移值作为key。但是在实际应用中,我们在提取日志内容时,有可能遇到一条Record包含多行的情况,并且要提取字段开始限定符到结束限定符的情况

没事看看书 2435
上一篇: Found interface org.apache.hadoop.mapreduce.TaskAttemptContext, but class was expected
下一篇: MapReduce-XML处理-定制OutputFormat及定制RecordWriter
doegoo
博客等级 码龄14年 79粉丝 91原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值