Spark MLlib 示例代码阅读
阅读前提:有一定的机器学习基础, 本文重点面向的是应用,至于机器学习的相关复杂理论和优化理论,还是多多看论文,初学者推荐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 示例代码阅读的更多相关文章
- Spark MLlib线性回归代码实现及结果展示
线性回归(Linear Regression)是利用称为线性回归方程的最小平方函数对一个或多个自变量和因变量之间关系进行建模的一种回归分析. 这种函数是一个或多个称为回归系数的模型参数的线性组合.只有 ...
- 十二、spark MLlib的scala示例
简介 spark MLlib官网:http://spark.apache.org/docs/latest/ml-guide.html mllib是spark core之上的算法库,包含了丰富的机器学习 ...
- spark mllib lda 简单示例
舆情系统每日热词用到了lda主题聚类 原先的版本是python项目,分词应用Jieba,LDA应用Gensim 项目工作良好 有以下几点问题 1 舆情产品基于elasticsearch大数据,es内应 ...
- Spark 跑 java 示例代码
一.下载示例代码: git clone https://github.com/melphi/spark-examples.git 从示例代码中可以看到 pox中引入了 Spark开发所需要的依赖. 二 ...
- Spark mllib 随机森林算法的简单应用(附代码)
此前用自己实现的随机森林算法,应用在titanic生还者预测的数据集上.事实上,有很多开源的算法包供我们使用.无论是本地的机器学习算法包sklearn 还是分布式的spark mllib,都是非常不错 ...
- 使用 Spark MLlib 做 K-means 聚类分析[转]
原文地址:https://www.ibm.com/developerworks/cn/opensource/os-cn-spark-practice4/ 引言 提起机器学习 (Machine Lear ...
- 《Spark MLlib机器学习实践》内容简介、目录
http://product.dangdang.com/23829918.html Spark作为新兴的.应用范围最为广泛的大数据处理开源框架引起了广泛的关注,它吸引了大量程序设计和开发人员进行相 ...
- Spark入门实战系列--8.Spark MLlib(上)--机器学习及SparkMLlib简介
[注]该系列文章以及使用到安装包/测试数据 可以在<倾情大奉送--Spark入门实战系列>获取 .机器学习概念 1.1 机器学习的定义 在维基百科上对机器学习提出以下几种定义: l“机器学 ...
- Spark入门实战系列--8.Spark MLlib(下)--机器学习库SparkMLlib实战
[注]该系列文章以及使用到安装包/测试数据 可以在<倾情大奉送--Spark入门实战系列>获取 .MLlib实例 1.1 聚类实例 1.1.1 算法说明 聚类(Cluster analys ...
随机推荐
- SDUT-2498_AOE网上的关键路径
数据结构实验之图论十一:AOE网上的关键路径 Time Limit: 2000 ms Memory Limit: 65536 KiB Problem Description 一个无环的有向图称为无环图 ...
- php中括号定义数组
php5.3及之前的版本是不支持中括号定义数组的.5.4之后支持. 错误信息是,不识别“[”
- js遮罩
1.1 背景半透明遮罩层样式 需要一个黑色(当然也可以其他)背景,且须设置为绝对定位,以下是项目中用到的css样式: /* 半透明的遮罩层 */ #overlay { background: #000 ...
- springboot项目启动,但是访问报404错误
启动类Application上加了@ComponentScan(basePackages = {})这个注解导致controller扫描不到导致的,如果加了这个注解,springboot就不会扫描Ap ...
- TIJ——Chapter Six:Access Control
package:the library unit The levels of access control from "most access" to "least ac ...
- @codeforces - 718E@ Matvey's Birthday
目录 @description@ @solution@ @accepted code@ @detail@ @description@ 给定一个长度为 n 的字符串 s,保证只包含前 8 个小写字母 ' ...
- css技巧:清除浮动
1.常用方法——overflow 给浮动元素的容器添加overflow:hidden;或overflow:auto;可以清除浮动,另外在 IE6 中还需要触发 hasLayout ,例如为父元素设置容 ...
- 【算法】BSGS算法
BSGS算法 BSGS算法用于求解关于x的模方程\(A^x\equiv B\mod P\)(P为质数),相当于求模意义下的对数. 思想: 由费马小定理,\(A^{p-1}\equiv 1\mod P\ ...
- 2018-8-10-WPF-轻量级-MVVM-框架入门-2.1.2
title author date CreateTime categories WPF 轻量级 MVVM 框架入门 2.1.2 lindexi 2018-08-10 19:16:51 +0800 20 ...
- 阿里云IPv6 DDoS防御被工信部认定为“网络安全技术应用试点示范项目”
近日,阿里云数据中心骨干网IPv6 DDoS网络安全防御被工业和信息化部认定为“网络安全技术应用试点示范项目”,本次评选由工业和信息部网络安全管理局发起,从实用性.创新性.先进性.可推广性等维度展 ...