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计算了,今天和大家分享下这个 ...
随机推荐
- javascript中的正则示例
// 方式一var obj_re = new RegExp("\d+","gi"); //g 全局,i 不区分大小写obj_re.test("fasf ...
- [转载]vim常用命令总结
内容出处https://www.jianshu.com/p/a8ab13cff1ea 如有侵权请告知 移动.跳转 h.j.k.l:分别对应左.下.上.右.按键盘分布,从左到右,逆时针. w:移动到下一 ...
- (WC2016模拟十一)【BZOJ4695】最假女选手
ps:好久没更博啦……这几天连着有模拟赛,等初赛前后休息的时候来疯狂补坑吧……顺便补一下前面的数论啥的? 题解: mdzz我场上写了个15分暴力长度跟标算差不多... 线段树大法好啊!这题听说很多人做 ...
- Tomcat跨域资源共享
1.下载Jar包 cors-filter-1.7.jar java-property-utils-1.9.jar 下载完成后将Jar拷贝到tomcat下lib目录中 2.修改web.xml配置 在29 ...
- javaweb实现教师和教室管理系统 java jsp sqlserver
1,程序设计思想 (1)设计三个类,分别是工具类(用来写连接数据库的方法和异常类的方法).信息类(用来写存储信息的方法).实现类(用来写各种操作数据库的方法) (2)定义两个jsp文件,一个用来写入数 ...
- 紫书 习题8-19 UVa 1312 (枚举技巧)
这道题参考了https://www.cnblogs.com/20143605--pcx/p/4889518.html 这道题就是枚举矩形的宽, 然后从宽再来枚举高. 具体是这样的, 先把所有点的高度已 ...
- Docker之Mysql安装及配置
原文:Docker之Mysql安装及配置 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/zhaobw831/article/details/8014 ...
- macOS seria 10.12升级到macOS Mojave的报错:xcrun: error: invalid active developer path, missing xcrun
今天升级mac系统到macOS mojave后,在终端操作gitlab时遇到一行莫名其妙的错误: xcrun: error: invalid active developer path (/Libra ...
- 响应http报文中的Date属性与cookie过期时间的关系
今天在測试.net时,发现一个莫名其妙的问题:cookie老是保存不到浏览器端; 经过细致的比对成功与不成功的报文,居然无意中发现好像Date与它有关系,这太让我意想不到了,从来不知道cookie保存 ...
- ITOO右击菜单实现
ITOO做了持续了这么长时间,client使用MVC+EF+EasyUI框架,服务端在三层基础上增加WCF服务,后来增加容器,AOP(还没怎么接触),封装了在我们刚開始看来神奇的底层方法,克服了非常多 ...