天天看點

spark之MLlib機器學習-線性回歸

此篇博文根據《Spark MLlib機器學習》執行個體程式編寫,可作為熟悉scala和mllib編寫機器學習算法的一種實踐。

1、準備測試資料

可從作者部落格自行下載下傳。代碼及資料下載下傳位址

2、編寫scala源碼

為了進一步熟悉scala程式設計語言,建議自己把代碼敲一次。

//import org.apache.log4j{ Level, Logger }
import org.apache.spark.{SparkConf,SparkContext}
import org.apache.spark.mllib.regression.LinearRegressionWithSGD
import org.apache.spark.mllib.util.MLUtils
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LinearRegressionModel

object LinearRegression{

  def main(args:Array[String]){

    val conf = new SparkConf().setAppName("LinearRegressionWithSGD")
    val sc =new SparkContext(conf)
  //  Logger.getRootLogger.setLevel(Level.WARN)

    val data_path1="file:///usr/spark2.0/data/mllib/mydata/lpsa.data"
    val data=sc.textFile(data_path1)
    val examples=data.map{line=>
     val parts=line.split(',')
     LabeledPoint(parts().toDouble,Vectors.dense(parts().split(' ').map(_.toDouble)))
    }.cache()

    val numExamples=examples.count()
    val numIterations=
    val stepSize=
    val miniBatchFraction=
    val model=LinearRegressionWithSGD.train(examples,numIterations,stepSize,miniBatchFraction)
    val prediction=model.predict(examples.map(_.features))
    val predictionAndLabel=prediction.zip(examples.map(_.label))
    val print_predict=predictionAndLabel.take()
    println("prediction"+"\t"+"label")
    for (i <-  to print_predict.length- ){
       println(print_predict(i)._1 + "\t" + print_predict(i)._2)
    }
    val loss =predictionAndLabel.map{
        case(p,_)=>
            val err = p - 
            err*err
    }.reduce(_+_)
    val rmse=math.sqrt(loss/numExamples)
    println(s"Test RMSE = $rmse.")

  }
           

3、使用sbt工具編譯和打包

4、結果輸出:

spark之MLlib機器學習-線性回歸

可以看出,線性拟合的結果并不理想,說明模型選擇的不合理。本示例僅僅為了說明線性回歸api的用法。

繼續閱讀