lakala GradientBoostedTrees
/**
* Created by lkl on 2017/12/6.
*/
import org.apache.spark.mllib.evaluation.BinaryClassificationMetrics
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.tree.GradientBoostedTrees
import org.apache.spark.mllib.tree.configuration.BoostingStrategy
import org.apache.spark.sql.hive.HiveContext
import org.apache.spark.{SparkConf, SparkContext}
import scala.collection.mutable.ArrayBuffer
object GradientBoostingClassificationForLK {
//http://blog.csdn.net/xubo245/article/details/51499643
def main(args: Array[String]): Unit = {
val conf = new SparkConf().setAppName("GradientBoostingClassificationForLK")
val sc = new SparkContext(conf) // sc is an existing SparkContext.
val hc = new HiveContext(sc) if(args.length!=){
println("请输入参数:trainingData对应的库名、表名、模型运行时间")
System.exit()
} //分别传入库名、表名、对比效果路径
// val database = args(0)
// val table = args(1)
// val date = args(2)
//lkl_card_score.overdue_result_all_new_woe
val format = new java.text.SimpleDateFormat("yyyyMMdd")
val database ="lkl_card_score"
val table = "overdue_result_all_new_woe"
val date =format.format(new java.util.Date())
//提取数据集 RDD[LabeledPoint]
//val data = hc.sql(s"select * from $database.$table").map{ val data = hc.sql(s"select * from lkl_card_score.overdue_result_all_new_woe").map{
row =>
var arr = new ArrayBuffer[Double]()
//剔除label、contact字段
for(i <- until row.size){
if(row.isNullAt(i)){
arr += 0.0
}
else if(row.get(i).isInstanceOf[Int])
arr += row.getInt(i).toDouble
else if(row.get(i).isInstanceOf[Double])
arr += row.getDouble(i)
else if(row.get(i).isInstanceOf[Long])
arr += row.getLong(i).toDouble
else if(row.get(i).isInstanceOf[String])
arr += 0.0
}
LabeledPoint(row.getInt(), Vectors.dense(arr.toArray))
}
// Split the data into training and test sets (30% held out for testing)
val splits = data.randomSplit(Array(0.7, 0.3))
val (trainingData, testData) = (splits(), splits()) // Train a GradientBoostedTrees model.
// The defaultParams for Classification use LogLoss by default.
val boostingStrategy = BoostingStrategy.defaultParams("Classification")
boostingStrategy.setNumIterations() // Note: Use more iterations in practice.
boostingStrategy.treeStrategy.setNumClasses()
boostingStrategy.treeStrategy.setMaxDepth()
// Empty categoricalFeaturesInfo indicates all features are continuous.
//boostingStrategy.treeStrategy.setCategoricalFeaturesInfo(Map[Int, Int]()) val model = GradientBoostedTrees.train(trainingData, boostingStrategy) // Evaluate model on test instances and compute test error
val predictionAndLabels = testData.map { point =>
val prediction = model.predict(point.features)
(point.label, prediction)
} predictionAndLabels.map(x => {"predicts: "+x._1+"--> labels:"+x._2}).saveAsTextFile(s"hdfs://ns1/tmp/$date/predictionAndLabels")
//===================================================================
//使用BinaryClassificationMetrics评估模型
val metrics = new BinaryClassificationMetrics(predictionAndLabels) // Precision by threshold
val precision = metrics.precisionByThreshold
precision.map({case (t, p) =>
"Threshold: "+t+"Precision:"+p
}).saveAsTextFile(s"hdfs://ns1/tmp/$date/precision") // Recall by threshold
val recall = metrics.recallByThreshold
recall.map({case (t, r) =>
"Threshold: "+t+"Recall:"+r
}).saveAsTextFile(s"hdfs://ns1/tmp/$date/recall") //the beta factor in F-Measure computation.
val f1Score = metrics.fMeasureByThreshold
f1Score.map(x => {"Threshold: "+x._1+"--> F-score:"+x._2+"--> Beta = 1"})
.saveAsTextFile(s"hdfs://ns1/tmp/$date/f1Score") /**
* 如果要选择Threshold, 这三个指标中, 自然F1最为合适
* 求出最大的F1, 对应的threshold就是最佳的threshold
*/
/*val maxFMeasure = f1Score.select(max("F-Measure")).head().getDouble(0)
val bestThreshold = f1Score.where($"F-Measure" === maxFMeasure)
.select("threshold").head().getDouble(0)*/ // Precision-Recall Curve
val prc = metrics.pr
prc.map(x => {"Recall: " + x._1 + "--> Precision: "+x._2 }).saveAsTextFile(s"hdfs://ns1/tmp/$date/prc") // AUPRC,精度,召回曲线下的面积
val auPRC = metrics.areaUnderPR
sc.makeRDD(Seq("Area under precision-recall curve = " +auPRC)).saveAsTextFile(s"hdfs://ns1/tmp/$date/auPRC") //roc
val roc = metrics.roc
roc.map(x => {"FalsePositiveRate:" + x._1 + "--> Recall: " +x._2}).saveAsTextFile(s"hdfs://ns1/tmp/$date/roc") // AUC
val auROC = metrics.areaUnderROC
sc.makeRDD(Seq("Area under ROC = " + +auROC)).saveAsTextFile(s"hdfs://ns1/tmp/$date/auROC")
println("Area under ROC = " + auROC) val testErr = predictionAndLabels.filter(r => r._1 != r._2).count.toDouble / testData.count()
sc.makeRDD(Seq("Test Mean Squared Error = " + testErr)).saveAsTextFile(s"hdfs://ns1/tmp/$date/testErr")
sc.makeRDD(Seq("Learned regression tree model: " + model.toDebugString)).saveAsTextFile(s"hdfs://ns1/tmp/$date/GBDTclassification")
} }
lakala GradientBoostedTrees的更多相关文章
- lakala反欺诈建模实际应用代码GBDT监督学习
/** * Created by lkl on 2018/1/16. */ import org.apache.spark.mllib.evaluation.BinaryClassificationM ...
- lakala proportion轨迹分析代码
/** * Created by lkl on 2017/12/7. */ import breeze.numerics.abs import org.apache.spark.sql.SQLCont ...
- 决策树和基于决策树的集成方法(DT,RF,GBDT,XGBT)复习总结
摘要: 1.算法概述 2.算法推导 3.算法特性及优缺点 4.注意事项 5.实现和具体例子 内容: 1.算法概述 1.1 决策树(DT)是一种基本的分类和回归方法.在分类问题中它可以认为是if-the ...
- 《Spark 官方文档》机器学习库(MLlib)指南
spark-2.0.2 机器学习库(MLlib)指南 MLlib是Spark的机器学习(ML)库.旨在简化机器学习的工程实践工作,并方便扩展到更大规模.MLlib由一些通用的学习算法和工具组成,包括分 ...
- ORACLE11G常用函数
1 单值函数 1.1 日期函数 1.1.1 Round [舍入到最接近的日期](day:舍入到最接近的星期日) select sysdate S1, round(sysdate) S2 , round ...
- 决策树和基于决策树的集成方法(DT,RF,GBDT,XGB)复习总结
摘要: 1.算法概述 2.算法推导 3.算法特性及优缺点 4.注意事项 5.实现和具体例子 内容: 1.算法概述 1.1 决策树(DT)是一种基本的分类和回归方法.在分类问题中它可以认为是if-the ...
- MLlib--GBDT算法
转载请标明出处http://www.cnblogs.com/haozhengfei/p/8b9cb1875288d9f6cfc2f5a9b2f10eac.html GBDT算法 江湖传言:GBDT算法 ...
- spark MLlib Classification and regression 学习
二分类:SVMs,logistic regression,decision trees,random forests,gradient-boosted trees,naive Bayes 多分类: ...
- Oracle分析函数及常用函数: over(),rank()over()作用及用法--分区(分组)求和& 不连续/连续排名
(1) 函数: over()的作用及用法: -- 分区(分组)求和. sum() over( partition by column1 order by column2 )主要用来对某个字 ...
随机推荐
- 设计模式之模板方法模式&&迪米特法则(代码Objective-C展示)
模板方法模式 模板方法模式:定义一个操作中的算法骨架,而将一些步骤延迟到子类中.模板方法使得子类可以在不改变一个算法的结构即可重定义该算法的某些特定步骤. 比如说,小时候数学老师的随堂检测,都是在黑板 ...
- mysql 常用指令集合
show variables ——显示系统变量(扩展show variables like 'XXX') 在MYSQL的主从复制中 ,通过命令show master status,可以查看maste ...
- git拉取远程分支
查看本地所有分支列表: git branch -a 查看远程所有分支列表: git branch -r 拉取远程分支(使用该方式会在本地新建分支x,但是不会自动切换到该本地分支x,需要手动checko ...
- C# if为false仍然进入方法体,==和qeual结果不一致
场景: 代码: if( e.Key == Key.Tab) { // ... } 断点调试:结果为false,进入方法体 ??? 更改为: if(Key.Tab.Equals(e.key)) { ...
- GODOT 3.0 开发进度汇报 #6
经过了又一个月的开发工作,在此作进度报告.本月的工作可以划分为:完成Web导出工具开发.GDNative.以及新的粒子系统. Web Export Godot 现在有了一款实验性的导出工具,导出目标为 ...
- [lsof]lsof查看哪些设备/文件被占用或者打开
转自:http://blog.csdn.net/yuzhihui_no1/article/details/51767516 最近在查一个Bug,应用程序kill之后重启,总是会出现adc的设备open ...
- Android——程序员的情怀——优化BaseAdapter
总结: 1- 在MainActivity中只放数据,加载适配器 2- 单独定义实体类 3- 自定义适配器,并与实体类相关联,在适配器里写优化的代码将视图与数据相关联 MainActivity 2- N ...
- CPP_封装_继承_多态
类的三方法:封装,继承,多态.封装:使用一整套方法去创建一个新的类型,这叫类的封装.继承:从一个现有的类型基础上,稍作改动,得到一个新的类型的方法,叫类的继承.多态:当有几个不同的子类对象时,对象调用 ...
- Java编程的逻辑 (63) - 实用序列化: JSON/XML/MessagePack
本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http:/ ...
- 【进阶修炼】——改善C#程序质量(5)
71, 区分异步和多线程的应用场景. 计算机的很多硬件,如硬盘,光驱,声卡,网卡都有DMA(Direct Memory Access)功能,它可以不占用cpu的资源,而异步的提出恰恰就是基于这个的.而 ...