MLlib--保序回归

时间:2023-03-09 16:21:51
MLlib--保序回归

转载请标明出处http://www.cnblogs.com/haozhengfei/p/24cb3f38b55e5d7516d8059f9f105eb6.html


保序回归

1.线性回归VS保序回归

   • 线性回归->线性拟合
   • 保序回归->保序的分段线性拟合,保序回归是拟合原始数据最佳的单调函数

1.1保序回归

MLlib--保序回归
    保序回归是特殊的线性回归,如果业务上具有单调性,这时候就可以用保序回归,而不是用线性回归。

1.2保序回归应用场景

    药剂和中毒的预测,剂量和毒性呈非递减函数

1.3保序回归模型使用

• 预测规则:
   – 如果预测输入能准确匹配训练特征,那么返回相关预测,如果有多个预测匹配训练特征,那么就返回其中之一。
   – 如果预测输入比所有的训练特征低或者高,那么最低和最高的训练特征各自返回。如果有多个预测比所有的训练特征低或者高,那么都会返回。
   – 如果预测输入介于两个训练特征,那么预测会被视为分段线性函数和从最接近的训练特征中计算得到的插值。

1.4保序回归code

IsotonicRegression_new
MLlib--保序回归
 import org.apache.log4j.{Level, Logger}
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.mllib.regression.{IsotonicRegressionModel, IsotonicRegression} /**
* Created by hzf
*/
object IsotonicRegression_new {
// F:\额外项目\pensionRisk\data\IsR\train\sample_isotonic_regression_data.txt F:\额外项目\pensionRisk\data\IsR\model true local
def main(args: Array[String]) {
Logger.getLogger("org.apache.spark").setLevel(Level.ERROR)
if (args.length < 4) {
System.err.println("Usage: LRwithLGD <inputPath> <modelPath> Isotonic <master> [<AppName>]")
System.err.println("eg: hdfs://192.168.57.104:8020/user/000000_0 hdfs://192.168.57.104:8020/user/model true spark://192.168.57.104:7077 IsotonicRegression")
System.exit(1)
}
val appName = if (args.length > 4) args(4) else "IsotonicRegression"
val conf = new SparkConf().setAppName(appName).setMaster(args(3))
val sc = new SparkContext(conf)
var isotonic = true
isotonic = args(2) match {
case "true" => true
case "false" => false
}
val data = sc.textFile(args(0))
val parsedData: RDD[(Double, Double, Double)] = data.map { line =>
val parts = line.split(',').map(_.toDouble)
(parts(0), parts(1), 1.0)
} val splitRdd: Array[RDD[(Double, Double, Double)]] = parsedData.randomSplit(Array(1.0, 9.0))
val testData = splitRdd(0)
val realTrainData: RDD[(Double, Double, Double)] = splitRdd(1) val model: IsotonicRegressionModel = new IsotonicRegression().setIsotonic(isotonic).run(realTrainData)
val predictionAndLabel = testData.map { point =>
val predictedLabel = model.predict(point._2)
(predictedLabel, point._1)
} val meanSquaredError = predictionAndLabel.map { case p => math.pow((p._1 - p._2), 2) }.mean()
println("meanSquaredError = " + meanSquaredError)
model.boundaries.zip(model.predictions).foreach(println(_))
model.save(sc, args(1)) }
}
设置运行参数
  1. E:\IDEA_Projects\mlib\data\IsR\train\sample_isotonic_regression_data.txt E:\IDEA_Projects\mlib\data\IsR\model true local
MLlib--保序回归