回归算法之逻辑回归

线性回归与逻辑回归的区别:
比如要分析年龄,性别,身高,饮食习惯对于体重的影响,如果体重是实际的重量,那么就要使用线性回归。如果将体重分类,分成了高,中,低三类,就要使用逻辑回归进行分类。
在这里插入图片描述

import org.apache.spark.mllib.classification.{LogisticRegressionWithLBFGS}
import org.apache.spark.mllib.util.MLUtils
import org.apache.spark.{SparkConf, SparkContext}
object LogisticRegressionExample01 {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setAppName("spark").setMaster("local[3]")
    val sc = new SparkContext(conf)
    //加载 LIBSVM 格式的数据  这种格式特征前缀要从1开始
    val inputData = MLUtils.loadLibSVMFile(sc, "healstatus.txt")
    val splits = inputData.randomSplit(Array(0.7, 0.3), seed = 1L)
    val (trainingData, testData) = (splits(0), splits(1))
    val lr = new LogisticRegressionWithLBFGS()
    lr.setIntercept(true)  //设置截距
    val model = lr.run(trainingData) 
    //预测值与测试y值的差
    val result = testData
      .map{point=>Math.abs(point.label-model.predict(point.features))}
      //打印预测的y值
    testData.foreach(t=>{
      println(model.predict(t.features)+".....")
    })
    println("正确率="+(1.0-result.mean()))

    /**
      *逻辑回归算法训练出来的模型,模型中的参数个数(w0....w6)=训练集中特征数(6)+1
      */
    println(model.weights.toArray.mkString(" "))
    println(model.intercept)
    sc.stop()
  }
}

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_38653290/article/details/86497616