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

WordCount实例:深入了解RecordWriterOutput和RecordWriter RecordWriterOutput和RecordWriter是大数据处理中常用的组件,它们在WordCount等MapReduce程序中起着重要作用。RecordWriter是RecordWriterOutput的具体实现之一,它负责将键值对写入到文件系统中的某个具体文件中。在WordCount程序中,我们会使用TextOutputFormat.TextRecordWriter作为RecordWriter的实现。在这个示例中,RecordWriter继承自RecordWriterOutput,并实现了。 阅读详情
这一篇紧接上一篇博客《 MapReduce-XML处理-定制InputFormat及定制RecordReader》,上一篇是说明InputFormat和RecordReader,这里说明OutputFormat以及RecordWriter的定制,下面是
这次测试的要求:
输入数据:
<configuration>
  <property>
    <name>hadoop.kms.authentication.type</name>
    <value>simple</value>
  </property>
  <property>
    <name>hadoop.kms.authentication.kerberos.keytab</name>
    <value>${user.home}/kms.keytab</value>
  </property>
  <property>
    <name>hadoop.kms.authentication.kerberos.principal</name>
    <value>HTTP/localhost</value>
  </property>
  <property>
    <name>hadoop.kms.authentication.kerberos.name.rules</name>
    <value>DEFAULT</value>
  </property>
</configuration>
实现的结果:把上述XML文件中的value的值倒序,然后按照XML标签的格式输出,如下:
<name>hadoop.kms.authentication.kerberos.keytab</name>
<value>batyek.smk/}emoh.resu{$</value>
<name>hadoop.kms.authentication.kerberos.name.rules</name>
<value>TLUAFED</value>
<name>hadoop.kms.authentication.kerberos.principal</name>
<value>tsohlacol/PTTH</value>
<name>hadoop.kms.authentication.type</name>
<value>elpmis</value>
由于代码量过多,这里就不贴出上一篇说明InputFormat和RecordReader的代码了,如果要做完整的测试到上一篇找代码
《MapReduce-xml文件的处理-定制InputFormat及定制RecordReader》。InputFormat、RecordReader、mapper的代码在这
里就不贴出来了。
定制步骤:
扩展OutputFormat和RecordWriter这两类或其子类,其功能是:
OutputFormat用于验证数据接收器的属性,RecordWriter用于将reduce对象的输出结果导入数据接收器中。
首先扩展OutputFormat类其要实现的内容为:
1.public abstract class OutputFormat<K, V>
K,V为定义reduce输入键和值的类型
2.public abstract RecordWriter<K, V> getRecordWriter(TaskAttemptContext context ) throws IOException, InterruptedException;
创建一个RecordWriter实例将数据写入到目标
3.public abstract void checkOutputSpecs(JobContext context ) throws IOException, InterruptedException;
验证与MapReduce作业相关联的输出信息是否下确
4.public abstract OutputCommitter getOutputCommitter(TaskAttemptContext context ) throws IOException, InterruptedException;
获取相关OutputCommitter。当所有任务成功和作业完成后,OutputCommitters负责在最后将结果输出
然后扩展RecordWriter类,其实现的内容为:
1.public abstract class RecordWriter<K, V>
K,V为定义reduce输入键和值的类型
2.public abstract void write(K key, V value ) throws IOException, InterruptedException;
将一个逻辑键/值对写到接收器。
3.public abstract void close(TaskAttemptContext context ) throws IOException, InterruptedException;
清理任何与目标数据接收器相关的资源

定制OutputFormat:这里是扩展OutputFormat的子类FileOutputFormat

import java.io.DataOutputStream;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.GzipCodec;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.ReflectionUtils;

public class XMLOutputFormat extends FileOutputFormat<Text, Text> {
	@Override
	public RecordWriter<Text, Text> getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException {
		/**
		 * 为创建FSDataOutputStream做准备,判断是否设置了输出压缩
		 * 如果有提取扩展名
		 */
		Configuration conf = job.getConfiguration();
		boolean isCompressed = getCompressOutput(job);
		CompressionCodec codec = null;
		String extension = "";
		if (isCompressed) {
			Class<? extends CompressionCodec> codecClass = getOutputCompressorClass(job, GzipCodec.class);
			codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf);
			extension = codec.getDefaultExtension();
		}
		Path file = getDefaultWorkFile(job, extension);
		FileSystem fs = file.getFileSystem(conf);
		/**
		 * 创建RecordWriter,并把准备好的输出流传入RecordWriter以便其输出定制格式换
		 * key,value到指定的文件中
		 */
		if (!isCompressed) {
			FSDataOutputStream fileOut = fs.create(file, false);
			return new XMLRecordWriter(fileOut);
		} else {
			FSDataOutputStream fileOut = fs.create(file, false);
			return new XMLRecordWriter(new DataOutputStream( codec.createOutputStream(fileOut)));
		}
	}
}
定制RecordWriter:

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;

public class XMLRecordWriter extends RecordWriter<Text, Text> {
	protected DataOutputStream out;
	private static final String utf8 = "UTF-8";
	private static final byte[] newline;
	private String nameTag;
	private String valueTag;
	private Text key_ = new Text();
	private Text value_ = new Text();
    static {
      try {
    	  /**
    	   * 定义换行符
    	   */
        newline = "\n".getBytes(utf8);
      } catch (UnsupportedEncodingException uee) {
        throw new IllegalArgumentException("can't find " + utf8 + " encoding");
      }
    }
	@Override
	public synchronized void close(TaskAttemptContext arg0) throws IOException,
			InterruptedException {
		out.close();
	}
	/**
	 * 实现输出定制的核心方法,在reduce调用write方法后,根据传入的key,value
	 * 来做相应形式的输出
	 */
	@Override
	public synchronized void write(Text key, Text value) throws IOException,
			InterruptedException {
		boolean nullKey = key == null; 
		boolean nullValue = value == null;
		/**
		 * 判断key,value是否都为空如果都为空则不输出
		 */
		if (nullKey && nullValue) {
			return;
		}
		/**
		 * 如果key不为空怎么输出
		 */
		if (!nullKey) {
			nameTag = "<name>" + key.toString() +"</name>";
			key_.set(nameTag.getBytes());
			writeObject(key_);
		}
		if (!(nullKey || nullValue)) {
			out.write(newline);
		}
		/**
		 * 如果value不为空怎么输出
		 */
		if (!nullValue) {
			valueTag = "<value>" + value.toString() + "</value>";
			value_.set(valueTag.getBytes());
			writeObject(value_);
		}
		out.write(newline);
	}
	/**
	 * 调用以下方法把对象写入HDFS
	 * @param o
	 * @throws IOException
	 */
	private void writeObject(Object o) throws IOException {
		if (o instanceof Text) {
			Text to = (Text) o;
			out.write(to.getBytes(), 0, to.getLength());
		} else {
			out.write(o.toString().getBytes(utf8));
		}
	}
	public XMLRecordWriter(DataOutputStream out ) {
		this.out = out;
	}
}
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();
	private StringBuffer sb = new StringBuffer();
	@Override
	protected void reduce(Text key, Iterable<Text> value, Context context)
			throws IOException, InterruptedException {
		for(Text val: value) {
			//倒序的处理也可以放到RecordWriter中去实现
			sb.append(val.toString());
			val_.set(sb.reverse().toString());
			context.write(key, val_);
			sb.delete(0, sb.length());
		}
	}
}
启动函数:

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》的一个扩展,这里没有贴出Mapper,InputFormat以及RecordReader的代码,如果要运行出结果map端的实现代码请参考上一篇代码。下一篇会说明mapreduce中join的的实现。

java 中自定义OutputFormat的实例详解 主要介绍了java 中 自定义OutputFormat的实例详解的相关资料,这里提供实例帮助大家学习理解这部分内容,希望通过本文能帮助到大家,需要的朋友可以参考下 立即下载

相关推荐

基于Codex与Skills的学术研究自动化全流程实战指南

还在为海量文献下载、整理、阅读和综述写作而头疼吗?面对堆积如山的PDF,你是否感到无从下手?从选题、文献检索、到写作、绘图、润色,再到应对AI检测和审稿意见,学术研究的每一步都充满挑战。本文将为你带来一套堪称“王炸组合”的解决方案: Codex + Skills 。这不是简单的工具介绍,而是一套从零开始,覆盖学术研究全流程的保姆级实战教程。我们将手把手教你如何安装、配置,并利用强大的Skills(技能)自动化处理文献下载管理、高效撰写综述、生成专业图表、智能润色降重,直至应对审稿。无论你是科研新手还是希望提

weixin_29041195的博客 779

RecordWriter核心设计实现

根据创建得到的RecordWriter组件的数量,构建出RecordWriter代理(到底是哪个)RecordSerializer是RecordWriter组件的核心之一,负责将StreamRecord(数据元素,也就是理解意义上的“砖”)序列化成二进制(粒度更细的“沙子”),临时暂存到ByteBuffer(缓冲区,也就是理解意义上的“拖拉机”)上。RecordWriter定义了获取指定InputChannel所对应的BufferBuilder的抽象方法,而它的2个抽象实现子类为其提供了具体的实现逻辑。

墨玉浮白的博客 854

广工计组实验f2一位全加器

一位全加器实验

weixin_63692154的博客 2849

大数据框架之Hadoop:MapReduce(三)MapReduce框架原理——OutputFormat数据输出

OutputFormat数据输出

yiluohan0307的专栏 1732

AlertManager的使用(邮件和微信告警)

一、AlertManager概述 Prometheus 包含一个报警模块,就是我们的 AlertManager,Alertmanager 主要用于接收 Prometheus 发送的告警信息,它支持丰富的告警通知渠道,而且很容易做到告警信息进行去重,降噪,分组等,是一款前卫的告警通知系统。 Alertmanager是一个独立的告警模块,接收Prometheus等客户端发来的警报,之后通过分组、删除重复等处理,并将它们通过路由发送给正确的接收器;告警方式可以按照不同的规则发送给不同的模块负责人,Alertman

weixin_45880055的博客 2万+

交换芯片数据通路四大核心微架构深度解析

数据通路是交换芯片性能的物理根基,决定着低延迟、高吞吐与突发承载能力。其本质是在硅片约束下对带宽、时序、功耗与统计复用的系统性权衡。Crossbar提供确定性低延迟但受RC延迟与功耗制约;VOQ通过虚拟队列隔离输出争抢,却引入仲裁复杂度与内存开销;Shared Buffer依托统计复用提升缓存利用率,但面临碎片化与管理策略挑战;Cell Fabric以固定长度cell重构交换粒度,在AI与金融等小包敏感场景实现尾延迟稳定。这些架构并非替代关系,而是面向不同网络不确定性(如流量不对称性、突发强度、包长分布)的

weixin_32667955的博客 190

MapReduce之RecordWriter理解

RecordWriter:其实主要就是负责将task的key/value结果写入内存或者磁盘   一 方法分析 1.1 write:写key/value键值对 1.2 close: 关闭RecordWriter   二 RecordWriter运行流程分析 2.1 Map Task Record Writer运行流程分析 #Map Task#runNewMapper会根据是否当前程

happy19870612's blog 2368

BQ25713寄存器配置全解析:从基础原理到笔记本充电实战

在电源管理系统中,寄存器配置是实现精细化控制的核心技术。其原理是通过I2C等总线向芯片内部特定地址写入二进制代码,直接设定其工作参数与行为逻辑,从而实现对电压、电流、功率及保护阈值的底层控制。这项技术的价值在于,它能将通用电源管理芯片灵活适配于千差万别的具体应用,是提升系统性能、可靠性与能效的关键。在便携设备、嵌入式系统等场景中,精准的寄存器配置决定了充电效率、动态响应和故障保护能力。本文聚焦于**BQ25713**这款经典充电管理芯片,深入剖析其**ChargeOption**、**ProchotOpti

weixin_42713608的博客 293

MapReduce快速入门系列(12) | MapReduce之OutputFormat

前面我们讲解了MapTask,ReduceTask和MapReduce运行机制。,那么这篇文章博主继续为大家讲解OutputFormat数据输出。 目录一. OutputFormat接口实现类1.1 文本输出TextOutputFormat1.2 SequenceFileOutputFormat1.3 ==自定义OutputFormat==二. 自定义OutputFormat的使用场景和步骤2...

不温卜火 5739

基于ESP32的智能厨房控制系统开发

随着智能家居技术的发展,越来越多的家庭开始将传统的厨房设备进行智能化改造,以提高烹饪效率和生活质量。智能厨房控制系统是物联网(IoT)应用的重要组成部分,它将家居设备、传感器和网络结合起来,提供便捷的控制与监测功能,使厨房的烹饪过程更加智能、便捷和安全。基于ESP32的智能厨房控制系统不仅能够实现远程控制和监控,还能实现温度、湿度、烹饪状态的实时反馈,甚至具备智能化的推荐和自动化控制能力。ESP32是一款功能强大、集成度高的嵌入式开发平台,具有Wi-Fi和蓝牙双模通信能力,广泛应用于物联网设备的开发。

2201_76125393的博客 659

【论文汇总】Diffusion Models视频生成/视频编辑/可控视频生成/跨模态视频生成

本文总结了Diffusion Models视频生成领域相关的工作,目前共收录142篇,持续更新中。

沉迷单车的追风少年 1678

MapReduce-XML处理-自定义OutputFormat以及自定义RecordWriter

友情提示:更多有关大数据、人工智能方面技术文章请关注博主个人微信公众号:高级大数据架构师! 这一篇紧接上一篇博客《MapReduce-XML处理-自定义InputFormat及自定义RecordReader》,上一篇是说明InputFormat和RecordReader,这里说明OutputFormat以及RecordWriter的定制,下面是这次测试的要求:输入数据:&lt;configura...

小宁哥博客 477

【Bug已解决】Codex CLI 报 stream disconnected before completion 解决方案

方案适用场景推荐指数更新根证书库社区验证的最常见根因⭐⭐⭐⭐⭐检查系统时间虚拟机/容器等特殊运行环境⭐⭐⭐⭐核对 base_url 配置排除证书问题后的下一步排查⭐⭐⭐⭐更换网络环境测试怀疑本地网络设备存在干扰⭐⭐⭐升级到最新版本已知版本缺陷的场景⭐⭐⭐⭐报错虽然表现形式很像网络连接问题,但社区排查的多个真实案例表明,很大一部分情况的根因其实是本机系统的 TLS 证书信任链异常或系统时间不准确,而不是单纯的网络质量问题。优先检查并更新系统根证书库,这是社区验证过的高频根因。

一键难忘的博客 8084

RecordWriter 类详解

RecordWriter 类详解【updating…】 1. 源码 package org.apache.hadoop.mapreduce; import java.io.IOException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification....

说文科技,做有态度的研究。 1620

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

Hadoop(十七) mapreduce Outputformat输出格式

1、使用场景 为了实现控制最终文件的输出路径和输出格式,可以自定义OutputFormat。例如:要在一个MapReduce程序中根据数据的不同输出两类结果到不同的目录,这类灵活的输出需求可以通过自定义OutputFormat来实现。2、自定义OUtputFormat步骤 (1)自定义一个类继承FileOutputFormat。(2)改写RecordWriter,具体改写输出数据的方法write()。数据准备,有订单数据如下:ordersource.txt。

技术博客 787

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

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

Spark - 继承 FileOutputFormat 实现向 HDFS 地址追加文件

Spark 继承 FileOutputFormat 实现向 HDFS 追加存储文件需求。

BITDDD小栈 995

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

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

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

这一篇说明如何自定义InputFormat以及RecordReader这两个组件,通过使用mapreduce处理xml文件格式的文件来说明其用法,这一个例子来自《hadoop硬实战》一书的技术点12讲解的用法,如果有说明得不清楚的可以自行进行查阅 下面就来说说这个实例要达到的目的以下是输入数据:       hadoop.kms.authentication.type     sim

Qi.zheng 3038

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中的OutputFormat

既然有InputFormat,那么自然就会有OutputFormat,本文主要介绍MapReduce中的OutputFormat。关注专栏《from zero to hero(Hadoop篇)》查看相关系列的文章~ ...

象在舞的技术专栏 1113

【学习历程】13 MapReduce之自定义outputFormat

一、需求       现在有一些订单的评论数据,需要将订单的好评与其他评论(中评、差评)进行区分开来,将最终的数据分开到不同的文件夹下面去,数据内容如下图,其中数据第九个字段表示好评,中评,差评。0:好评,1:中评,2:差评 二、分析       关键点是要在一个mapreduce程序中根据数据的不同,输出两类结果到不同目录,这类灵活的输出需求可以通过自定义outputformat来实现

Aries1Chan的博客 277

学习笔记:MapReduce的几种输出格式类总结

引 MapReduce输出格式类图。 一. OutputFormat及其子类 1. OutputFormat类 本类主要用于描述输出数据的格式,它能够将用户提供的 key/value 对写入特定格式的文件中。主要涉及以下两个方法: RecordWriter&lt;K, V&gt; getRecordWriter(TaskAttemptContext var1):根据TaskAttemptCon...

敲烂键盘为止 1906

关于mapreduce解析xml的方法

mapreduce的TextInputFormat很方便的处理行行的文本,但遇到xml的时候就很纠结了,曾经采用分隔数据重写FileInputFormat(网上有资料),可以解决此问题,但会获取很多噪音数据。 后来想到以起始结束来获取数据,重写FileInputFormat没有这个技术能力,呵呵。 后来一直找资料,看了一篇http://www.linezing.com/blog/?p=489,...

空中的鱼 349

Hadoop内置的数据输入\输出格式与RecordReader\RecordWriter(九)

理论和源代码分析:一,数据输入格式(InputFormat)用于描述MapReduce的作业 数据输入规范。MapReduce框架依靠数据输入格式完成输入 规范检查(比如输入文件的目录的检查),对数据文件进行 输入分块(InputSplit),以及提供从输入分块中 将数据逐一 读出,并转换为,Map过程的输入键值对等功能。最常用的数据输入格式:TextInputFormat和KeyValue

young_so_nice的博客 3679

35 MAPREDUCE自定义outputFormat

需求 现有一些原始日志需要做增强解析处理,流程: 1、从原始日志文件中读取数据。 2、根据日志中的一个URL字段到外部知识库中获取信息增强到原始日志。 3、如果成功增强,则输出到增强结果目录;如果增强失败,则抽取原始数据中URL字段输出到待爬清单目录。 分析 程序的关键点是要在一个mapreduce程序中根据数据的不同输出两类结果到不同目录,这类灵活的输出需求可以通过自定义outputformat...

阿甘兄 634

MapReduce框架原理-OutputFormat

目录 一、OutputFormat概述 二、自定义OutputFormat 自定义OutputFormat的详细流程: 三、案例实操 案例一:存储数据到MySQL中 案例二:存储数据到HDFS本地指定文件夹中 一、OutputFormat概述 OutputFormat主要是用来指定MR程序的最终的输出数据格式 。 默认使用的是TextOutputFormat,默认是将数据一行写一条数据,并且把数据放到指定的输出目录下,以 part-r-xxxxx数字开头。并且默认情况下有几个R

zyd_994264926326的博客 484
上一篇: MapReduce-XML处理-定制InputFormat及定制RecordReader
下一篇: MapReduce-Join操作-初体验
doegoo
博客等级 码龄14年 79粉丝 91原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值