阅读前提:有一定的机器学习基础, 本文重点面向的是应用,至于机器学习的相关复杂理论和优化理论,还是多多看论文,初学者推荐Ng的公开课

/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.spark.examples.mllib

import org.apache.log4j.{Level, Logger}
import scopt.OptionParser

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.mllib.classification.{LogisticRegressionWithLBFGS, SVMWithSGD}
import org.apache.spark.mllib.evaluation.BinaryClassificationMetrics
import org.apache.spark.mllib.util.MLUtils
import org.apache.spark.mllib.optimization.{SquaredL2Updater, L1Updater}

/**
* An example app for binary classification. Run with
* {{{
* bin/run-example org.apache.spark.examples.mllib.BinaryClassification
* }}}
* A synthetic dataset is located at `data/mllib/sample_binary_classification_data.txt`.
* If you use it as a template to create your own app, please use `spark-submit` to submit your app.
*/
object BinaryClassification {

object Algorithm extends Enumeration {
type Algorithm = Value
val SVM, LR = Value
}

object RegType extends Enumeration {
type RegType = Value
val L1, L2 = Value
}

import Algorithm._
import RegType._

case class Params(
input: String = null,
numIterations: Int = 100,  迭代次数 submit时可以传递进来
stepSize: Double = 1.0,     步长
algorithm: Algorithm = LR,   默认的二分算法是逻辑回归
regType: RegType = L2,  默认的正则化规则是L2 ,
regParam: Double = 0.01) extends AbstractParams[Params]  L1 L2 正则化参数

def main(args: Array[String]) {    
val defaultParams = Params()

val parser = new OptionParser[Params]("BinaryClassification") {
head("BinaryClassification: an example app for binary classification.")
opt[Int]("numIterations") 
.text("number of iterations")
.action((x, c) => c.copy(numIterations = x))
opt[Double]("stepSize")
.text("initial step size (ignored by logistic regression), " +
s"default: ${defaultParams.stepSize}")
.action((x, c) => c.copy(stepSize = x))
opt[String]("algorithm")
.text(s"algorithm (${Algorithm.values.mkString(",")}), " +
s"default: ${defaultParams.algorithm}")
.action((x, c) => c.copy(algorithm = Algorithm.withName(x)))
opt[String]("regType")
.text(s"regularization type (${RegType.values.mkString(",")}), " +
s"default: ${defaultParams.regType}")
.action((x, c) => c.copy(regType = RegType.withName(x)))
opt[Double]("regParam")
.text(s"regularization parameter, default: ${defaultParams.regParam}")
arg[String]("<input>")
.required()
.text("input paths to labeled examples in LIBSVM format")
.action((x, c) => c.copy(input = x))
note(
"""
|For example, the following command runs this app on a synthetic dataset:
|
| bin/spark-submit --class org.apache.spark.examples.mllib.BinaryClassification \
| examples/target/scala-*/spark-examples-*.jar \
| --algorithm LR --regType L2 --regParam 1.0 \
| data/mllib/sample_binary_classification_data.txt
""".stripMargin)
}

parser.parse(args, defaultParams).map { params =>                                      ////params 是参数列表 保存了线性回归或者svm的各种参数
run(params)
} getOrElse {
sys.exit(1)
}
}

def run(params: Params) {
val conf = new SparkConf().setAppName(s"BinaryClassification with $params") 创建sparkConf 
val sc = new SparkContext(conf)  创建sc sparkcontext

Logger.getRootLogger.setLevel(Level.WARN)

val examples = MLUtils.loadLibSVMFile(sc, params.input).cache()   //input 是我们的样本文件的路径

val splits = examples.randomSplit(Array(0.8, 0.2))  将输入文本进行随机切割 80%的文件为训练文本 20%的文件为 测试文本
val training = splits(0).cache()  训练数据
val test = splits(1).cache()  测试数据

val numTraining = training.count()
val numTest = test.count()
println(s"Training: $numTraining, test: $numTest.")

examples.unpersist(blocking = false)

val updater = params.regType match {   根据输入选择 是L1正则化还是L2正则化
case L1 => new L1Updater()
case L2 => new SquaredL2Updater()
}

val model = params.algorithm match {  根据输入参数选择是 逻辑回归还是 SVM
case LR =>
val algorithm = new LogisticRegressionWithLBFGS()
algorithm.optimizer
.setNumIterations(params.numIterations) 参数设置
.setUpdater(updater)         参数设置
.setRegParam(params.regParam)  参数设置
algorithm.run(training).clearThreshold()        开始train
case SVM =>
val algorithm = new SVMWithSGD()
algorithm.optimizer
.setNumIterations(params.numIterations)
.setStepSize(params.stepSize)
.setUpdater(updater)
.setRegParam(params.regParam)
algorithm.run(training).clearThreshold()     开始train
}

val prediction = model.predict(test.map(_.features))  开始测试
val predictionAndLabel = prediction.zip(test.map(_.label))

val metrics = new BinaryClassificationMetrics(predictionAndLabel)

println(s"Test areaUnderPR = ${metrics.areaUnderPR()}.")
println(s"Test areaUnderROC = ${metrics.areaUnderROC()}.")

sc.stop()
}
}

Spark MLlib 示例代码阅读的更多相关文章

  1. Spark MLlib线性回归代码实现及结果展示

    线性回归(Linear Regression)是利用称为线性回归方程的最小平方函数对一个或多个自变量和因变量之间关系进行建模的一种回归分析. 这种函数是一个或多个称为回归系数的模型参数的线性组合.只有 ...

  2. 十二、spark MLlib的scala示例

    简介 spark MLlib官网:http://spark.apache.org/docs/latest/ml-guide.html mllib是spark core之上的算法库,包含了丰富的机器学习 ...

  3. spark mllib lda 简单示例

    舆情系统每日热词用到了lda主题聚类 原先的版本是python项目,分词应用Jieba,LDA应用Gensim 项目工作良好 有以下几点问题 1 舆情产品基于elasticsearch大数据,es内应 ...

  4. Spark 跑 java 示例代码

    一.下载示例代码: git clone https://github.com/melphi/spark-examples.git 从示例代码中可以看到 pox中引入了 Spark开发所需要的依赖. 二 ...

  5. Spark mllib 随机森林算法的简单应用(附代码)

    此前用自己实现的随机森林算法,应用在titanic生还者预测的数据集上.事实上,有很多开源的算法包供我们使用.无论是本地的机器学习算法包sklearn 还是分布式的spark mllib,都是非常不错 ...

  6. 使用 Spark MLlib 做 K-means 聚类分析[转]

    原文地址:https://www.ibm.com/developerworks/cn/opensource/os-cn-spark-practice4/ 引言 提起机器学习 (Machine Lear ...

  7. 《Spark MLlib机器学习实践》内容简介、目录

      http://product.dangdang.com/23829918.html Spark作为新兴的.应用范围最为广泛的大数据处理开源框架引起了广泛的关注,它吸引了大量程序设计和开发人员进行相 ...

  8. Spark入门实战系列--8.Spark MLlib(上)--机器学习及SparkMLlib简介

    [注]该系列文章以及使用到安装包/测试数据 可以在<倾情大奉送--Spark入门实战系列>获取 .机器学习概念 1.1 机器学习的定义 在维基百科上对机器学习提出以下几种定义: l“机器学 ...

  9. Spark入门实战系列--8.Spark MLlib(下)--机器学习库SparkMLlib实战

    [注]该系列文章以及使用到安装包/测试数据 可以在<倾情大奉送--Spark入门实战系列>获取 .MLlib实例 1.1 聚类实例 1.1.1 算法说明 聚类(Cluster analys ...

随机推荐

  1. [转]overflow:hidden真的失效了吗

    项目中常常有同学遇到这样的问题,现象是给元素设置了overflow:hidden,但超出容器的部分并没有被隐藏,难道是设置的hidden失效了吗?其实看似不合理的现象背后都会有其合理的解释. 我们知道 ...

  2. iOS app发布流程

    http://www.xuebuyuan.com/1980497.html http://blog.csdn.net/alincexiaohao/article/details/38725367 ap ...

  3. PHPCMS快速建站系列之网站迁移(本地到服务器,服务器迁移,更换域名等)

    可能出现的问题: 1.后台登录验证码显示不正常(修改/caches/configs/system.php文件) //网站路径'web_path' => '/', 2.phpsso修改 如果不修改 ...

  4. Centos7.3-mysql5.7复制安装过程

    一.环境 192.168.56.102 为主服务器 192.168.56.101 为从服务器 Mysql5.7.20 二进制安装包环境 1. 下载免编译安装包并进行安装 从官网下载 mysql-5.7 ...

  5. oralce GROUPING SETS

    select id,area,stu_type,sum(score) score from students group by grouping sets((id,area,stu_type),(id ...

  6. @codeforces - 1214G@ Feeling Good

    目录 @description@ @solution@ @accepted code@ @details@ @description@ 给定一个 n*m 的 01 矩阵 A,一开始所有格子都为 0. ...

  7. MySQL性能分析, mysql explain执行计划详解

    MySQL性能分析 MySQL性能分析及explain用法的知识是本文我们主要要介绍的内容,接下来就让我们通过一些实际的例子来介绍这一过程,希望能够对您有所帮助. 1.使用explain语句去查看分析 ...

  8. Struts2整合Spring方法及原理

    一.   Struts 2框架整合Spring步骤 1. 复制文件.复制struts2-spring-plugin-x-x-x.jar和spring.jar到WEB-INF/lib目录下.其中的x对应 ...

  9. python2和python3一些不同

    文件写法: #python2fp=file(filepath,'wb')#python3# fp = open(filepath, 'wb') 关于乱码问题: #python2 #coding=utf ...

  10. 2012-4-2 通过MdiParent设置窗体最前

    SentenceForm form = new SentenceForm(); form.MdiParent = this; form.Show(); //form.MdiParent = this; ...