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 ...
随机推荐
- 洛谷 P2486 [SDOI2011]染色 树链剖分
目录 题面 题目链接 题目描述 输入输出格式 输入格式 输出格式 输入输出样例 输入样例: 输出样例: 说明 思路 PushDown与Update Q AC代码 总结与拓展 题面 题目链接 P2486 ...
- bzoj3522 Hotel
Description 有一个树形结构的宾馆,n个房间,n-1条无向边,每条边的长度相同,任意两个房间可以相互到达.吉丽要给他的三个妹子各开(一个)房(间).三个妹子住的房间要互不相同(否则要打起来了 ...
- 【JZOJ4359】【GDKOI2016】魔卡少女
题目描述 君君是中山大学的四年级学生.有一天在家不小心开启了放置在爸爸书房中的一本古书.于是,君君把放在书中最上面的一张牌拿出来观摩了一下,突然掀起一阵大风把书中的其她所有牌吹散到各地.这时一只看上去 ...
- Hbuilder的使用技巧
/*注:本教程针对HBuilder5.0.0,制作日期2014-12-31*/创建HTML结构: h 8 (敲h激活代码块列表,按8选择第8个项目,即HTML代码块,或者敲h t Enter)中途换行 ...
- 2019-3-27-win10-uwp-动画移动滑动条的滑块
title author date CreateTime categories win10 uwp 动画移动滑动条的滑块 lindexi 2019-03-27 10:51:32 +0800 2019- ...
- python 语法错误
- 01-常见Dos命令、Java历史、Java跨平台、配置Path环境变量、第一个HelloWorld例子
常见Dos命令 dir: 列出当前目录下的文件以及文件夹 md: 创建目录 rd: 删除目录 cd: 进入指定目录 del: 删除文件 copy: 复制文件 xcopy: 复制目录 tree: 列出目 ...
- spring的父子关系
1.父容器不能拿子容器的资源 2.子容器可以拿到父容器的资源
- 云原生生态周报 Vol. 5 | etcd性能知多少
业界要闻 1 Azure Red Hat OpenShift已经GA.在刚刚结束的Red Hat Summit 2019上,Azure Red Hat OpenShift正式宣布GA,这是一个微软和红 ...
- OracleSpatial函数
Oracle_spatial的函数 一sdo_Geom包的函数: 用于表示两个几何对象的关系(结果为True/False)的函数:RELATE,WITHIN_DISTANCE 验证的函数:VALIDA ...