Spark机器学习(2):逻辑回归算法

逻辑回归本质上也是一种线性回归,和普通线性回归不同的是,普通线性回归特征到结果输出的是连续值,而逻辑回归增加了一个函数g(z),能够把连续值映射到0或者1。

MLLib的逻辑回归类有两个:LogisticRegressionWithSGD和LogisticRegressionWithLBFGS,前者基于随机梯度下降,只支持2分类,后者基于LBFGS优化损失函数,支持多分类。

直接上代码:

import org.apache.log4j.{Level, Logger}
import org.apache.spark.mllib.classification.LogisticRegressionWithLBFGS
import org.apache.spark.mllib.evaluation.MulticlassMetrics
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.mllib.util.MLUtils
import org.apache.spark.mllib.regression.LabeledPoint

object LogisticRegression {
  def main(args: Array[String]) {
    // 设置运行环境
    val conf = new SparkConf().setAppName("Logistic Regression Test")
      .setMaster("spark://master:7077").setJars(Seq("E:\\Intellij\\Projects\\MachineLearning\\MachineLearning.jar"))
    val sc = new SparkContext(conf)
    Logger.getRootLogger.setLevel(Level.WARN)

    // 读取样本数据,格式化为LIBSVM的RDD
    val dataRDD = MLUtils.loadLibSVMFile(sc, "hdfs://master:9000/ml/data/sample_libsvm_data.txt")

    // 样本数据划分,训练样本占0.7,测试样本占0.3
    val dataParts = dataRDD.randomSplit(Array(0.7, 0.3), seed = 25L)
    val trainRDD = dataParts(0).cache()
    val testRDD = dataParts(1)

    // 建立逻辑回归模型并训练
    val LRModel = new LogisticRegressionWithLBFGS().setNumClasses(10).run(trainRDD)

    // 对测试样本进行测试
    val prediction = testRDD.map {
      case LabeledPoint(label, features) =>
        val prediction = LRModel.predict(features)
        (prediction, label)
    }
    val showPrediction = prediction.take(10)
    // 输出测试结果
    println("Prediction" + "\t" + "Label")
    for (i <- 0 to showPrediction.length - 1) {
      println(showPrediction(i)._1 + "\t" + showPrediction(i)._2)
    }

    // 计算误差并输出
    val metrics = new MulticlassMetrics(prediction)
    val precision = metrics.precision
    println("Precision = " + precision)
  }

}

运行结果:

可见模型预测得非常准确。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值