直接复制https://blog.csdn.net/liuxinghao/article/details/39958957
这篇博文列举了两种基础的方法,区别在于输入数据的形式,
一种是矩阵形式;一种是(横坐标,纵坐标,值)的形式
同时这篇博文提到关于矩阵运算的应用:
两种实现的reduce阶段,计算最后结果时,都是直接使用内存存储数据、计算结果,所以当数据量很大的时候(通常都会很大,否则不会用分布式处理),极易造成内存溢出,所以,对于大矩阵的运算,还需要其他的转换方式,比如行列相乘运算、分块矩阵运算、基于最小粒度相乘的算法等方式。另外,因为这两份代码都是demo,所以代码中缺少过滤错误数据的部分。
本文使用的第二种
自己建了两个数组,大小为2
∗
∗
3、 33
你需要做的就是把 输入文件放进去
配置文件复制到工程src文件件下
复制粘贴
package org.apache.hadoop.examples;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
/**
* @author liuxinghao
* @version 1.0 Created on 2014年10月10日
*/
public class SparseMatrixMultiply {
public static class SMMapper extends Mapper<LongWritable, Text, Text, Text> {
private String flag = null;
private int m = 2;// 矩阵A的行数
private int p = 3;// 矩阵B的列数
@Override
protected void setup(Context context) throws IOException,
InterruptedException {
FileSplit split = (FileSplit) context.getInputSplit();
flag = split.getPath().getName();
}
@Override
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String[] val = value.toString().split(",");
if ("t1".equals(flag)) {
for (int i = 1; i <= p; i++) {
context.write(new Text(val[0] + "," + i), new Text("a,"
+ val[1] + "," + val[2]));
}
} else if ("t2".equals(flag)) {
for (int i = 1; i <= m; i++) {
context.write(new Text(i + "," + val[1]), new Text("b,"
+ val[0] + "," + val[2]));
}
}
}
}
public static class SMReducer extends
Reducer<Text, Text, Text, IntWritable> {
@Override
protected void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
Map<String, String> mapA = new HashMap<String, String>();
Map<String, String> mapB = new HashMap<String, String>();
for (Text value : values) {
String[] val = value.toString().split(",");
if ("a".equals(val[0])) {
mapA.put(val[1], val[2]);
} else if ("b".equals(val[0])) {
mapB.put(val[1], val[2]);
}
}
int result = 0;
// 可能在mapA中存在在mapB中不存在的key,或相反情况
// 因为,数据定义的时候使用的是稀疏矩阵的定义
// 所以,这种只存在于一个map中的key,说明其对应元素为0,不影响结果
Iterator<String> mKeys = mapA.keySet().iterator();
while (mKeys.hasNext()) {
String mkey = mKeys.next();
if (mapB.get(mkey) == null) {// 因为mkey取的是mapA的key集合,所以只需要判断mapB是否存在即可。
continue;
}
result += Integer.parseInt(mapA.get(mkey))
* Integer.parseInt(mapB.get(mkey));
}
context.write(key, new IntWritable(result));
}
}
public static void main(String[] args) throws IOException,
ClassNotFoundException, InterruptedException {
String input1 = "hdfs:/matrix/t1";
String input2 = "hdfs:/matrix/t2";
String output = "hdfs:/matrix/out";
Configuration conf = new Configuration();
conf.addResource("classpath:/core-site.xml");
conf.addResource("classpath:/hdfs-site.xml");
Job job = Job.getInstance(conf, "SparseMatrixMultiply");
job.setJarByClass(SparseMatrixMultiply.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setMapperClass(SMMapper.class);
job.setReducerClass(SMReducer.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.setInputPaths(job, new Path(input1), new Path(input2));// 加载2个输入数据集
Path outputPath = new Path(output);
outputPath.getFileSystem(conf).delete(outputPath, true);
FileOutputFormat.setOutputPath(job, outputPath);
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
日志文件:
18/03/25 04:24:15 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
18/03/25 04:24:17 INFO Configuration.deprecation: session.id is deprecated. Instead, use dfs.metrics.session-id
18/03/25 04:24:17 INFO jvm.JvmMetrics: Initializing JVM Metrics with processName=JobTracker, sessionId=
18/03/25 04:24:17 WARN mapreduce.JobResourceUploader: Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this.
18/03/25 04:24:17 WARN mapreduce.JobResourceUploader: No job jar file set. User classes may not be found. See Job or Job#setJar(String).
18/03/25 04:24:17 INFO input.FileInputFormat: Total input paths to process : 2
18/03/25 04:24:17 INFO mapreduce.JobSubmitter: number of splits:2
18/03/25 04:24:18 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_local1549038765_0001
18/03/25 04:24:18 INFO mapreduce.Job: The url to track the job: http://localhost:8080/
18/03/25 04:24:18 INFO mapreduce.Job: Running job: job_local1549038765_0001
18/03/25 04:24:18 INFO mapred.LocalJobRunner: OutputCommitter set in config null
18/03/25 04:24:18 INFO output.FileOutputCommitter: File Output Committer Algorithm version is 1
18/03/25 04:24:18 INFO mapred.LocalJobRunner: OutputCommitter is org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter
18/03/25 04:24:18 INFO mapred.LocalJobRunner: Waiting for map tasks
18/03/25 04:24:18 INFO mapred.LocalJobRunner: Starting task: attempt_local1549038765_0001_m_000000_0
18/03/25 04:24:18 INFO output.FileOutputCommitter: File Output Committer Algorithm version is 1
18/03/25 04:24:18 INFO mapred.Task: Using ResourceCalculatorProcessTree : [ ]
18/03/25 04:24:18 INFO mapred.MapTask: Processing split: hdfs://master:9000/matrix/t2:0+54
18/03/25 04:24:18 INFO mapred.MapTask: (EQUATOR) 0 kvi 26214396(104857584)
18/03/25 04:24:18 INFO mapred.MapTask: mapreduce.task.io.sort.mb: 100
18/03/25 04:24:18 INFO mapred.MapTask: soft limit at 83886080
18/03/25 04:24:18 INFO mapred.MapTask: bufstart = 0; bufvoid = 104857600
18/03/25 04:24:18 INFO mapred.MapTask: kvstart = 26214396; length = 6553600
18/03/25 04:24:18 INFO mapred.MapTask: Map output collector class = org.apache.hadoop.mapred.MapTask$MapOutputBuffer
18/03/25 04:24:19 INFO mapred.LocalJobRunner:
18/03/25 04:24:19 INFO mapred.MapTask: Starting flush of map output
18/03/25 04:24:19 INFO mapred.MapTask: Spilling map output
18/03/25 04:24:19 INFO mapred.MapTask: bufstart = 0; bufend = 180; bufvoid = 104857600
18/03/25 04:24:19 INFO mapred.MapTask: kvstart = 26214396(104857584); kvend = 26214328(104857312); length = 69/6553600
18/03/25 04:24:19 INFO mapred.MapTask: Finished spill 0
18/03/25 04:24:19 INFO mapred.Task: Task:attempt_local1549038765_0001_m_000000_0 is done. And is in the process of committing
18/03/25 04:24:19 INFO mapred.LocalJobRunner: map
18/03/25 04:24:19 INFO mapred.Task: Task 'attempt_local1549038765_0001_m_000000_0' done.
18/03/25 04:24:19 INFO mapred.LocalJobRunner: Finishing task: attempt_local1549038765_0001_m_000000_0
18/03/25 04:24:19 INFO mapred.LocalJobRunner: Starting task: attempt_local1549038765_0001_m_000001_0
18/03/25 04:24:19 INFO output.FileOutputCommitter: File Output Committer Algorithm version is 1
18/03/25 04:24:19 INFO mapred.Task: Using ResourceCalculatorProcessTree : [ ]
18/03/25 04:24:19 INFO mapreduce.Job: Job job_local1549038765_0001 running in uber mode : false
18/03/25 04:24:19 INFO mapred.MapTask: Processing split: hdfs://master:9000/matrix/t1:0+36
18/03/25 04:24:19 INFO mapreduce.Job: map 100% reduce 0%
18/03/25 04:24:19 INFO mapred.MapTask: (EQUATOR) 0 kvi 26214396(104857584)
18/03/25 04:24:19 INFO mapred.MapTask: mapreduce.task.io.sort.mb: 100
18/03/25 04:24:19 INFO mapred.MapTask: soft limit at 83886080
18/03/25 04:24:19 INFO mapred.MapTask: bufstart = 0; bufvoid = 104857600
18/03/25 04:24:19 INFO mapred.MapTask: kvstart = 26214396; length = 6553600
18/03/25 04:24:19 INFO mapred.MapTask: Map output collector class = org.apache.hadoop.mapred.MapTask$MapOutputBuffer
18/03/25 04:24:19 INFO mapred.LocalJobRunner:
18/03/25 04:24:19 INFO mapred.MapTask: Starting flush of map output
18/03/25 04:24:19 INFO mapred.MapTask: Spilling map output
18/03/25 04:24:19 INFO mapred.MapTask: bufstart = 0; bufend = 180; bufvoid = 104857600
18/03/25 04:24:19 INFO mapred.MapTask: kvstart = 26214396(104857584); kvend = 26214328(104857312); length = 69/6553600
18/03/25 04:24:19 INFO mapred.MapTask: Finished spill 0
18/03/25 04:24:19 INFO mapred.Task: Task:attempt_local1549038765_0001_m_000001_0 is done. And is in the process of committing
18/03/25 04:24:19 INFO mapred.LocalJobRunner: map
18/03/25 04:24:19 INFO mapred.Task: Task 'attempt_local1549038765_0001_m_000001_0' done.
18/03/25 04:24:19 INFO mapred.LocalJobRunner: Finishing task: attempt_local1549038765_0001_m_000001_0
18/03/25 04:24:19 INFO mapred.LocalJobRunner: map task executor complete.
18/03/25 04:24:19 INFO mapred.LocalJobRunner: Waiting for reduce tasks
18/03/25 04:24:19 INFO mapred.LocalJobRunner: Starting task: attempt_local1549038765_0001_r_000000_0
18/03/25 04:24:19 INFO output.FileOutputCommitter: File Output Committer Algorithm version is 1
18/03/25 04:24:19 INFO mapred.Task: Using ResourceCalculatorProcessTree : [ ]
18/03/25 04:24:19 INFO mapred.ReduceTask: Using ShuffleConsumerPlugin: org.apache.hadoop.mapreduce.task.reduce.Shuffle@1bc75a85
18/03/25 04:24:20 INFO reduce.MergeManagerImpl: MergerManager: memoryLimit=322594400, maxSingleShuffleLimit=80648600, mergeThreshold=212912320, ioSortFactor=10, memToMemMergeOutputsThreshold=10
18/03/25 04:24:20 INFO reduce.EventFetcher: attempt_local1549038765_0001_r_000000_0 Thread started: EventFetcher for fetching Map Completion Events
18/03/25 04:24:20 INFO reduce.LocalFetcher: localfetcher#1 about to shuffle output of map attempt_local1549038765_0001_m_000001_0 decomp: 218 len: 222 to MEMORY
18/03/25 04:24:20 INFO reduce.InMemoryMapOutput: Read 218 bytes from map-output for attempt_local1549038765_0001_m_000001_0
18/03/25 04:24:20 INFO reduce.MergeManagerImpl: closeInMemoryFile -> map-output of size: 218, inMemoryMapOutputs.size() -> 1, commitMemory -> 0, usedMemory ->218
18/03/25 04:24:20 INFO reduce.LocalFetcher: localfetcher#1 about to shuffle output of map attempt_local1549038765_0001_m_000000_0 decomp: 218 len: 222 to MEMORY
18/03/25 04:24:20 INFO reduce.InMemoryMapOutput: Read 218 bytes from map-output for attempt_local1549038765_0001_m_000000_0
18/03/25 04:24:20 INFO reduce.MergeManagerImpl: closeInMemoryFile -> map-output of size: 218, inMemoryMapOutputs.size() -> 2, commitMemory -> 218, usedMemory ->436
18/03/25 04:24:20 INFO reduce.EventFetcher: EventFetcher is interrupted.. Returning
18/03/25 04:24:20 INFO mapred.LocalJobRunner: 2 / 2 copied.
18/03/25 04:24:20 INFO reduce.MergeManagerImpl: finalMerge called with 2 in-memory map-outputs and 0 on-disk map-outputs
18/03/25 04:24:20 INFO mapred.Merger: Merging 2 sorted segments
18/03/25 04:24:20 INFO mapred.Merger: Down to the last merge-pass, with 2 segments left of total size: 424 bytes
18/03/25 04:24:20 INFO reduce.MergeManagerImpl: Merged 2 segments, 436 bytes to disk to satisfy reduce memory limit
18/03/25 04:24:20 INFO reduce.MergeManagerImpl: Merging 1 files, 438 bytes from disk
18/03/25 04:24:20 INFO reduce.MergeManagerImpl: Merging 0 segments, 0 bytes from memory into reduce
18/03/25 04:24:20 INFO mapred.Merger: Merging 1 sorted segments
18/03/25 04:24:20 INFO mapred.Merger: Down to the last merge-pass, with 1 segments left of total size: 428 bytes
18/03/25 04:24:20 INFO mapred.LocalJobRunner: 2 / 2 copied.
18/03/25 04:24:20 INFO Configuration.deprecation: mapred.skip.on is deprecated. Instead, use mapreduce.job.skiprecords
18/03/25 04:24:20 INFO mapred.Task: Task:attempt_local1549038765_0001_r_000000_0 is done. And is in the process of committing
18/03/25 04:24:20 INFO mapred.LocalJobRunner: 2 / 2 copied.
18/03/25 04:24:20 INFO mapred.Task: Task attempt_local1549038765_0001_r_000000_0 is allowed to commit now
18/03/25 04:24:20 INFO output.FileOutputCommitter: Saved output of task 'attempt_local1549038765_0001_r_000000_0' to hdfs://master:9000/matrix/out/_temporary/0/task_local1549038765_0001_r_000000
18/03/25 04:24:20 INFO mapred.LocalJobRunner: reduce > reduce
18/03/25 04:24:20 INFO mapred.Task: Task 'attempt_local1549038765_0001_r_000000_0' done.
18/03/25 04:24:20 INFO mapred.LocalJobRunner: Finishing task: attempt_local1549038765_0001_r_000000_0
18/03/25 04:24:20 INFO mapred.LocalJobRunner: reduce task executor complete.
18/03/25 04:24:21 INFO mapreduce.Job: map 100% reduce 100%
18/03/25 04:24:21 INFO mapreduce.Job: Job job_local1549038765_0001 completed successfully
18/03/25 04:24:21 INFO mapreduce.Job: Counters: 35
File System Counters
FILE: Number of bytes read=2139
FILE: Number of bytes written=875557
FILE: Number of read operations=0
FILE: Number of large read operations=0
FILE: Number of write operations=0
HDFS: Number of bytes read=234
HDFS: Number of bytes written=42
HDFS: Number of read operations=28
HDFS: Number of large read operations=0
HDFS: Number of write operations=8
Map-Reduce Framework
Map input records=15
Map output records=36
Map output bytes=360
Map output materialized bytes=444
Input split bytes=186
Combine input records=0
Combine output records=0
Reduce input groups=6
Reduce shuffle bytes=444
Reduce input records=36
Reduce output records=6
Spilled Records=72
Shuffled Maps =2
Failed Shuffles=0
Merged Map outputs=2
GC time elapsed (ms)=19
Total committed heap usage (bytes)=907542528
Shuffle Errors
BAD_ID=0
CONNECTION=0
IO_ERROR=0
WRONG_LENGTH=0
WRONG_MAP=0
WRONG_REDUCE=0
File Input Format Counters
Bytes Read=90
File Output Format Counters
Bytes Written=42