MapReduce实现线性回归
1. 软件版本号:
Hadoop2.6.0(IDEA中源代码编译使用CDH5.7.3,相应Hadoop2.6.0),集群使用原生Hadoop2.6.4。JDK1.8,Intellij IDEA 14 。
源代码能够在https://github.com/fansy1990/linear_regression 下载。
2. 实现思路:
2.1 Shuffle Data(打乱数据):
採用的思路是:在Mapper端输出随机值作为key,输出当前记录作为value,在Reducer端直接遍历每一个key的全部values,直接输出value以及NullWritable.get就可以。
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
if(randN <= 0) { // 假设randN 比0小。那么不再次打乱数据
context.write(randFloatKey,value);
return ;
}
if(++countI >= randN){// 假设randN等于1。那么每次随机的值都是不一样的
randFloatKey.set(random.nextFloat());
countI =0;
}
context.write(randFloatKey,value);
}
2.2 Linear Regression(线性回归):
theta0 = theta0 -alpha*(h(x)-y)x
theta1 = theta1 -alpha*(h(x)-y)x
当中,h(x)= theta0 + theta1 * x ;同一时候。须要注意这里的更新是同步更新,其核心代码例如以下所看到的:
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
float[] xy = Utils.str2float(value.toString().split(splitter));
float x = xy[0];
float y = xy[1];
// 同步更新 theta0 and theta1
lastTheta0 = theta0;
theta0 -= alpha *(theta0+theta1* x - y) * x; // 保持theta0 和theta1 不变
theta1 -= alpha *(lastTheta0 + theta1 * x -y) * x;// 保持theta0 和theta1 不变
}
protected void cleanup(Context context) throws IOException, InterruptedException {
theta0_1.set(theta0 + splitter + theta1);
context.write(theta0_1,NullWritable.get());
}
conf.setLong("mapreduce.input.fileinputformat.split.maxsize",700L);// 获取多个mapper;
job.setNumReduceTasks(0);
2.3 Combine Theta (合并參数值):
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
float[] xy = Utils.str2float(value.toString().split(splitter));
for(int i =0;i<thetas.size() ;i++){
// error = (theta0 + theta1 * x - y) ^2
thetaErrors[i] += (thetas.get(i)[0]+ thetas.get(i)[1] * xy[0] -xy[1]) *
(thetas.get(i)[0]+ thetas.get(i)[1] * xy[0] -xy[1]) ;
thetaNumbers[i]+= 1;
}
}
protected void cleanup(Context context) throws IOException, InterruptedException {
for(int i =0;i<thetas.size() ;i++){
theta.set(thetas.get(i));
floatAndLong.set(thetaErrors[i],thetaNumbers[i]);
context.write(theta,floatAndLong);
}
}
protected void reduce(FloatAndFloat key, Iterable<FloatAndLong> values, Context context) throws IOException, InterruptedException {
float sumF = 0.0f;
long sumL = 0L ;
for(FloatAndLong value:values){
sumF +=value.getSumFloat();
sumL += value.getSumLong();
}
theta_error.add(new float[]{key.getTheta0(),key.getTheta1(), (float)Math.sqrt((double)sumF / sumL)});
logger.info("theta:{}, error:{}", new Object[]{key.toString(),Math.sqrt(sumF/sumL)});
}
protected void cleanup(Context context) throws IOException, InterruptedException {
// 怎样加权?
// 方式1:假设误差越小。那么说明权重应该越大;
// 方式2:直接平均值
float [] theta_all = new float[2];
if("average".equals(method)){
// theta_all = theta_error.get(0);
for(int i=0;i< theta_error.size();i++){
theta_all[0] += theta_error.get(i)[0];
theta_all[1] += theta_error.get(i)[1];
}
theta_all[0] /= theta_error.size();
theta_all[1] /= theta_error.size();
} else {
float sumErrors = 0.0f;
for(float[] d:theta_error){
sumErrors += 1/d[2];
}
for(float[] d: theta_error){
theta_all[0] += d[0] * 1/d[2] /sumErrors;
theta_all[1] += d[1] * 1/d[2] /sumErrors;
}
}
context.write(new FloatAndFloat(theta_all),NullWritable.get());
}
2.4 验证
3. 执行结果:
3.1 shuffle Job
public static void main(String[] args) throws Exception {
args = new String[]{
"hdfs://master:8020/user/fanzhe/linear_regression.txt",
"hdfs://master:8020/user/fanzhe/shuffle_out",
"1"
} ;
ToolRunner.run(Utils.getConf(),new ShuffleDataJob(),args);
}
6.1101,17.592
5.5277,9.1302
8.5186,13.662
。 。 。
Shuffle输出:
3.2 Linear Regression
public static void main(String[] args) throws Exception {
// <input> <output> <theta0;theta1;alpha> <splitter> // 注意第三个參数使用分号切割
args = new String[]{
"hdfs://master:8020/user/fanzhe/shuffle_out",
"hdfs://master:8020/user/fanzhe/linear_regression",
"1;0;0.01",
","
} ;
ToolRunner.run(Utils.getConf(),new LinearRegressionJob(),args);
}
查看输出结果:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
3.3 Combine Theta
public static void main(String[] args) throws Exception {
// <input> <output> <theta_path> <splitter> <average|weight>
args = new String[]{
"hdfs://master:8020/user/fanzhe/shuffle_out",
"hdfs://master:8020/user/fanzhe/single_linear_regression_error",
"hdfs://master:8020/user/fanzhe/linear_regression",
",",
"weight"
} ;
ToolRunner.run(Utils.getConf(),new SingleLinearRegressionError(),args);
}
这里设置的合并theta值的方式使用加权。读者能够设置为average,从而使用平均值;
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
3.4 验证
public static void main(String[] args) throws Exception {
// <input> <output> <theta_path> <splitter>
args = new String[]{
"hdfs://master:8020/user/fanzhe/shuffle_out",
"hdfs://master:8020/user/fanzhe/last_linear_regression_error",
"hdfs://master:8020/user/fanzhe/single_linear_regression_error",
",",
} ;
ToolRunner.run(Utils.getConf(),new LastLinearRegressionError(),args);
}
输出结果为:
4. 总结
分享,成长。快乐
转载请注明blog地址:http://blog.csdn.net/fansy1990
MapReduce实现线性回归的更多相关文章
- MapReduce原理及其主要实现平台分析
原文:http://www.infotech.ac.cn/article/2012/1003-3513-28-2-60.html MapReduce原理及其主要实现平台分析 亢丽芸, 王效岳, 白如江 ...
- Alink漫谈(十一) :线性回归 之 L-BFGS优化
Alink漫谈(十一) :线性回归 之 L-BFGS优化 目录 Alink漫谈(十一) :线性回归 之 L-BFGS优化 0x00 摘要 0x01 回顾 1.1 优化基本思路 1.2 各类优化方法 0 ...
- Mapreduce的文件和hbase共同输入
Mapreduce的文件和hbase共同输入 package duogemap; import java.io.IOException; import org.apache.hadoop.co ...
- mapreduce多文件输出的两方法
mapreduce多文件输出的两方法 package duogemap; import java.io.IOException; import org.apache.hadoop.conf ...
- mapreduce中一个map多个输入路径
package duogemap; import java.io.IOException; import java.util.ArrayList; import java.util.List; imp ...
- Hadoop 中利用 mapreduce 读写 mysql 数据
Hadoop 中利用 mapreduce 读写 mysql 数据 有时候我们在项目中会遇到输入结果集很大,但是输出结果很小,比如一些 pv.uv 数据,然后为了实时查询的需求,或者一些 OLAP ...
- [Hadoop in Action] 第5章 高阶MapReduce
链接多个MapReduce作业 执行多个数据集的联结 生成Bloom filter 1.链接MapReduce作业 [顺序链接MapReduce作业] mapreduce-1 | mapr ...
- MapReduce
2016-12-21 16:53:49 mapred-default.xml mapreduce.input.fileinputformat.split.minsize 0 The minimum ...
- 使用mapreduce计算环比的实例
最近做了一个小的mapreduce程序,主要目的是计算环比值最高的前5名,本来打算使用spark计算,可是本人目前spark还只是简单看了下,因此就先改用mapreduce计算了,今天和大家分享下这个 ...
随机推荐
- nodejs 封装mysql连接池
写在前面的 在nodejs后台代码中,我们总是会和数据库打交道 然而,每次都要写数据库的配置以及连接和断开,不胜其烦 我就封装了一个连接池模块,不足之处还请多多批评 上代码 一下是写在mysqls.j ...
- 在远程X server上显示图形的设置方法
1.在服务器的/etc/ssh/sshd_config中,设置X11Forwarding yes,然后重启ssh服务,cd /etc/init.d这个目录下执行 ./ssh restart 2.在客户 ...
- 【模板】多项式乘法 NTT
相对来说是封装好的,可以当模板来用. #include <bits/stdc++.h> #define maxn 5000000 #define G 3 #define ll long l ...
- 字符串格式时间转Date格式
/** * 字符串时间格式转 Date 格式 * @param strDate * @return */ public static Date getDateTimeByStringTime(Stri ...
- yii2.0 发送邮件带word小附件
把 common/config/main-local.php 下的 mailer 注释掉: 'mailer'=>[ 'class ...
- Android群英传-拼图游戏puzzle-代码设计和实现
上个周末,3个小时总体上读完了<Android群英传>,本周主要在研究代码层次的设计和实现. 编译安装在手机上,玩了几把,结合代码,一周时间才掌握了整体的思路. 大部分时间,其实花在了 ...
- HDU 2782 The Worm Turns (DFS)
Winston the Worm just woke up in a fresh rectangular patch of earth. The rectangular patch is divide ...
- 洛谷——P2863 [USACO06JAN]牛的舞会The Cow Prom
https://www.luogu.org/problem/show?pid=2863#sub 题目描述 The N (2 <= N <= 10,000) cows are so exci ...
- Unity渲染
我们先大概了解一下对渲染的优先级有影响的几个因素 1.Camera.Depth 不同相机的深度,在渲染顺序的优先度里面是最高的,Depth越大,渲染的图像越靠前 2.Render.SortingOrd ...
- HDU 1022 Train Problem I 模拟栈题解
火车进站,模拟一个栈的操作,额外的栈操作,查看能否依照规定顺序出栈. 数据量非常少,故此题目非常easyAC. 直接使用数组模拟就好. #include <stdio.h> const i ...