zoukankan      html  css  js  c++  java
  • 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" + "	" + "Label")
        for (i <- 0 to showPrediction.length - 1) {
          println(showPrediction(i)._1 + "	" + showPrediction(i)._2)
        }
    
        // 计算误差并输出
        val metrics = new MulticlassMetrics(prediction)
        val precision = metrics.precision
        println("Precision = " + precision)
      }
    
    }

    运行结果:

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

  • 相关阅读:
    298. Binary Tree Longest Consecutive Sequence
    117. Populating Next Right Pointers in Each Node II
    116. Populating Next Right Pointers in Each Node
    163. Missing Ranges
    336. Palindrome Pairs
    727. Minimum Window Subsequence
    211. Add and Search Word
    年底购物狂欢,移动支付安全不容忽视
    成为程序员前需要做的10件事
    全球首推iOS应用防破解技术!
  • 原文地址:https://www.cnblogs.com/mstk/p/7019227.html
Copyright © 2011-2022 走看看