Scala-Spark实现RF(随机森林)

本文介绍了一个使用随机森林回归算法预测酒店产量的Spark MLlib模型。该模型利用历史数据进行训练,并对未来日期的数据进行预测,最终将预测结果写入指定的Hive表中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package Cii_Forecast

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.hive.HiveContext

object Cii_Forecast_main {
  def main(args: Array[String]): Unit ={
    //获得昨天的日期
    // 调用形式: /opt/app/spark-1.6.1/bin/spark-shell --master yarn-client
    import java.util.Calendar
    import java.text.SimpleDateFormat
    import java.util.Date

    def getYesterday():String={
      var  dateFormat:SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd")
      var cal:Calendar=Calendar.getInstance()
      cal.add(Calendar.DATE,-1)
      var yesterday=dateFormat.format(cal.getTime())
      yesterday
    }
    val Yesterday=getYesterday()

    //获取今天的日期
    def getNowDate():String={
      var now:Date = new Date()
      var  dateFormat:SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd")
      var today = dateFormat.format( now )
      today
    }
    val Today=getNowDate()


    // 训练集、测试集
    // 训练集:CiiFcst_hotel_Cii_Traintable
    //测试集: CiiFcst_hotel_Cii_Testtable

    // LabelPoint相关包的导入
    import org.apache.spark.mllib.linalg.Vectors
    import org.apache.spark.mllib.regression.LabeledPoint


    // 机器学习包
    import org.apache.spark.mllib.tree.RandomForest
    import org.apache.spark.mllib.tree.model.RandomForestModel
    import org.apache.spark.mllib.util.MLUtils


    //训练集构建(模型数据保持不变)

    //sqlContext初始化
    val conf=new SparkConf().setAppName("cii_prediction")
    val sc=new SparkContext(conf)
    val sqlContext=new HiveContext(sc)


    //新增,对toDF()
    import sqlContext.implicits._

    val df=sqlContext.sql("select * from databasename.CiiFcst_hotel_Cii_Traintable where d='2016-08-29'")
    val data=df.select(df("notcancelcii"),df("week_constant"),df("working_day_constant"),df("cii_ahead_sameoneweek_constant")
      ,df("cii_ahead_sametwoweeks_avg_constant"),df("cii_ahead_samethreeweeks_avg_constant") ,df("cii_ahead_samefourweeks_avg_constant")
      ,df("simple_estimate_constant") ,df("cii_ahead_1day_1") ,df("cii_ahead_3days_avg_1"),df("cii_ahead_7days_avg_1"),df("order_ahead_lt_1days_1")
      ,df("order_ahead_lt_2days_1"),df("order_ahead_lt_3days_1"),df("order_ahead_lt_7days_1"),df("order_ahead_lt_14days_1"),df("order_alldays_1"))

    //LablePoint构建
    val  trainData=data.map{line =>
      val label=line(0).toString.toDouble
      val value0=(1 to 16).map(i=>  line(i).toString.toDouble  )
      val featureVector=Vectors.dense( value0.toArray)
      LabeledPoint(label, featureVector)
    }

    //模型预测
    //              提取预测表数据


    //*******************************  模型修改部分1  ******************************//
    //  val df1=sqlContext.sql("select * from databasename.CiiFcst_hotel_Cii_Testtable where d='2016-08-29' and starttime='2016-08-30'")


    val sql_1="select * from databasename.CiiFcst_hotel_Cii_Testtable where d="+"'"+Yesterday+"'"+" and starttime="+"'"+ Today +"'"

    val df1=sqlContext.sql(sql_1)


    val data1=df1.select(df1("hotelid"),df1("week_constant"),df1("working_day_constant"),df1("cii_ahead_sameoneweek_constant")
       ,df1("cii_ahead_sametwoweeks_avg_constant"),df1("cii_ahead_samethreeweeks_avg_constant") ,df1("cii_ahead_samefourweeks_avg_constant")
       ,df1("simple_estimate_constant") ,df1("cii_ahead_1day_1") ,df1("cii_ahead_3days_avg_1"),df1("cii_ahead_7days_avg_1"),df1("order_ahead_lt_1days_1")
       ,df1("order_ahead_lt_2days_1"),df1("order_ahead_lt_3days_1"),df1("order_ahead_lt_7days_1"),df1("order_ahead_lt_14days_1"),df1("order_alldays_1"))


    //构建预测集
    //LablePoint构建
    val  testData=data1.map{line =>
      val label=line(0).toString.toDouble
      val value0=(1 to 16).map(i=>  line(i).toString.toDouble  )
      val featureVector=Vectors.dense( value0.toArray)
      LabeledPoint(label, featureVector)
    }


    // 开始位置
    //模型参数
    val categoricalFeaturesInfo = Map[Int, Int]()
    val numTrees = 100 // Use more in practice.
    val featureSubsetStrategy = "auto" // Let the algorithm choose.
    val impurity = "variance"    //mse没有
    val maxDepth = 5
    val maxBins = 200

    //模型调用
    val model = RandomForest.trainRegressor(trainData, categoricalFeaturesInfo,
      numTrees, featureSubsetStrategy, impurity, maxDepth, maxBins)


    //结果集预测,母酒店ID和预测的产量,还可以加上日期
    val result_test = testData.map { point =>
      val prediction = model.predict(point.features)
      (point.label.toInt, prediction)
    }

    val tmp_frame=result_test.toDF()
    val tmp_frame1=tmp_frame.withColumnRenamed(tmp_frame.columns(0),"masterhotel")
    val tmp_frame2=tmp_frame1.withColumnRenamed(tmp_frame.columns(1),"cii_num");


    val result_frame= tmp_frame2.toDF()
    result_frame.registerTempTable("tmp_tableresult")


    //*******************************  模型修改部分2  ******************************//
    //sqlContext.sql("insert overwrite table  databasename.Tmp_CiiFcst_hotel_forecast_result partition(d='2016-09-05') select * from tmp_tableresult")


    val sql_2="insert overwrite table  databasename.Tmp_CiiFcst_hotel_forecast_result partition(d='"+Yesterday+"') select * from tmp_tableresult"
    sqlContext.sql(sql_2)


  }

}
好的,我将为您介绍一个Spark随机森林算法的实例。 随机森林是一种集成学习方法,它在机器学习中应用广泛。Spark MLlib提供了随机森林分类器和回归器,下面我们以分类器为例进行说明。 实例: ```scala import org.apache.spark.sql.SparkSession import org.apache.spark.ml.Pipeline import org.apache.spark.ml.classification.RandomForestClassifier import org.apache.spark.ml.feature.{IndexToString, StringIndexer, VectorIndexer} import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator // 创建SparkSession val spark = SparkSession.builder.appName("RandomForestExample").getOrCreate() import spark.implicits._ // 加载数据 val data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt") // 索引标签,添加元数据到标签列 val labelIndexer = new StringIndexer().setInputCol("label").setOutputCol("indexedLabel").fit(data) // 自动识别分类特征并进行索引 val featureIndexer = new VectorIndexer() .setInputCol("features") .setOutputCol("indexedFeatures") .setMaxCategories(4) // 超过4个不同值的特征被认为是连续的 .fit(data) // 拆分训练数据和测试数据 val Array(trainingData, testData) = data.randomSplit(Array(0.7, 0.3)) // 创建RandomForest模型 val rf = new RandomForestClassifier() .setLabelCol("indexedLabel") .setFeaturesCol("indexedFeatures") .setNumTrees(10) // 将索引标签转换回原始标签 val labelConverter = new IndexToString() .setInputCol("prediction") .setOutputCol("predictedLabel") .setLabels(labelIndexer.labels) // 创建Pipeline val pipeline = new Pipeline().setStages(Array(labelIndexer, featureIndexer, rf, labelConverter)) // 训练模型 val model = pipeline.fit(trainingData) // 进行预测 val predictions = model.transform(testData) // 选择要显示的列 predictions.select("predictedLabel", "label", "features").show(5) // 选择(预测,真实)标签并计算测试错误 val evaluator = new MulticlassClassificationEvaluator() .setLabelCol("indexedLabel") .setPredictionCol("prediction") .setMetricName("accuracy") val accuracy = evaluator.evaluate(predictions) println(s"Test Accuracy = ${(accuracy * 100)}%") // 停止SparkSession spark.stop() ``` 这个实例展示了如何在Spark中使用随机森林算法进行分类任务。主要步骤包括: 1. 数据加载和预处理 2. 特征索引和标签索引 3. 训练集和测试集的划分 4. 构建随机森林模型 5. 创建Pipeline并训练模型 6. 进行预测并评估模型性能 通过这个实例,我们可以看到Spark MLlib提供的随机森林算法使用起来非常方便,只需几行代码就可以构建一个完整的机器学习流程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值