阅读前提:有一定的机器学习基础, 本文重点面向的是应用,至于机器学习的相关复杂理论和优化理论,还是多多看论文,初学者推荐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. vue_qqmapdemo1

    腾讯地图vue组件,实现异步加载腾讯地图,坐标拾取器,支持按城市名称搜索. 搜索框样式依赖elementUI,不需要可删除顶部,地图部分无依赖项 //qqmap.vue <template> ...

  2. python三种导入模块的方法和区别

    方法一: import modname 模块是指一个可以交互使用,或者从另一Python 程序访问的代码段.只要导入了一个模块,就可以引用它的任何公共的函数.类或属性.模块可以通过这种方法来 使用其它 ...

  3. Sublime text 3 如何格式化HTML/css/js代码

    Sublime Text 3 安装Package Control   原来Subl3安装Package Control很麻烦,现在简单的方法来了 一.简单的安装方法 使用Ctrl+`快捷键或者通过Vi ...

  4. Servlet工作流程

    1.加载Servlet类 类加载器负责加载servlet类. 当Web容器接收到servlet的第一个请求时,将加载servlet类. 2.创建Servlet实例 Web容器在加载servlet类之后 ...

  5. nodeJs学习-14 mysql数据库学习、Navicat管理工具

    数据库: MySQL   免费.性能非常不错 缺点:集群.容灾稍微弱一点 Oracle 收费.大型应用.金融级.性能非常不错.集群.容灾非常强 缺点:贵 mySQL安装教程--nodeJsz智能社视频 ...

  6. 2019-9-23-dotnet-判断特定进程存在方法

    title author date CreateTime categories dotnet 判断特定进程存在方法 lindexi 2019-09-23 16:20:42 +0800 2019-09- ...

  7. python HTTP请求过程的两种常见异常

  8. C# —— 访问修饰符

    1.public 公有的,任何代码均可以访问,应用于所有类或成员. 2.internal 内部的,只能在当前程序集中使用,应用于所有类或成员. 3.protected internal 受保护的内部成 ...

  9. find 使用搜集

    find:-atime +n/-n:表示访问或执行时间大于或小于n天的文件-ctime +n/-n:表示写入.更改inode属性的时间大于或小于n天的文件-mtime +n/-n:表示写入时间大于或小 ...

  10. [牛腩]如何关闭.net framework4.0的请求验证 标签: 发布 2015-07-31 09:27 887人阅读 评论(38)

    敲牛腩的时候,点击运行提示:从客户端中检测到有潜在危险的 Request.Form 值,感觉自己代码敲的并没有问题,于是开始各种查,下面分享一下我对此进行的研究. 为什么会报这个错误? 在 Web 应 ...