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计算了,今天和大家分享下这个 ...
随机推荐
- 用MyBatis进行数据库的增删改查
前提是MyBatis环境部署好了,参考地址: https://www.cnblogs.com/package-java/p/10316536.html 为了方便演示,我提前在数据库插入了数据方便查询 ...
- git clone 和 git pull 代码无响应
记录一下今天 git 拉代码遇到的一些异常情况: 无论是项目目录下 git pull 还是直接 git clone 都不能正常拉代码: 异常情况1 ssh: connect to host gitee ...
- mybatis中 #跟$的区别
#相当于对数据 加上 双引号,$相当于直接显示数据 1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号.如:order by #user_id#,如果传入的值是111,那么解析成sq ...
- pandas 2 选择数据
from __future__ import print_function import pandas as pd import numpy as np np.random.seed(1) dates ...
- [luogu] P4514 上帝造题的七分钟 (树状数组,二维差分)
P4514 上帝造题的七分钟 题目背景 裸体就意味着身体. 题目描述 "第一分钟,X说,要有矩阵,于是便有了一个里面写满了0的n×m矩阵. 第二分钟,L说,要能修改,于是便有了将左上角为(a ...
- 没用私服,自己安装下本地jar包,制作坐标
没用私服的话,自己安装下本地jar包吧.执行下面命令即可. -Dfile 代表jar存在路径.mvn install:install-file -DgroupId=alipay -DartifactI ...
- [Angular] Configure an Angular App at Compile Time with the Angular CLI
Compile time configuration options allow you to provide different kind of settings based on the envi ...
- Swift学习——使用if和switch来进行条件操作,使用for,while,和do-while来进行循环(三)
Swift学习--使用if和switch来进行条件操作,使用for,while,和do-while来进行循环 //switch支持随意类型的数据以及各种比較操作--不不过整数以及測试相等 //注意假设 ...
- nodejs02
Node.js没有根目录的概念,因为它根本没有任何的web容器! 让node.js提供一个静态服务,都非常难! 也就是说,node.js中,如果看见一个网址是 1127.0.0.1:3000/fang ...
- Sqlite3的安装Windows