"""
Pipeline Example.
""" # $example on$
from pyspark.ml import Pipeline
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.feature import HashingTF, Tokenizer
# $example off$
from pyspark.sql import SparkSession if __name__ == "__main__":
spark = SparkSession\
.builder\
.appName("PipelineExample")\
.getOrCreate() # $example on$
# Prepare training documents from a list of (id, text, label) tuples.
training = spark.createDataFrame([
(0, "a b c d e spark", 1.0),
(1, "b d", 0.0),
(2, "spark f g h", 1.0),
(3, "hadoop mapreduce", 0.0)
], ["id", "text", "label"]) # Configure an ML pipeline, which consists of three stages: tokenizer, hashingTF, and lr.
tokenizer = Tokenizer(inputCol="text", outputCol="words")
hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol="features")
lr = LogisticRegression(maxIter=10, regParam=0.001)
pipeline = Pipeline(stages=[tokenizer, hashingTF, lr]) # Fit the pipeline to training documents.
model = pipeline.fit(training) # Prepare test documents, which are unlabeled (id, text) tuples.
test = spark.createDataFrame([
(4, "spark i j k"),
(5, "l m n"),
(6, "spark hadoop spark"),
(7, "apache hadoop")
], ["id", "text"]) # Make predictions on test documents and print columns of interest.
prediction = model.transform(test)
selected = prediction.select("id", "text", "probability", "prediction")
for row in selected.collect():
rid, text, prob, prediction = row
print("(%d, %s) --> prob=%s, prediction=%f" % (rid, text, str(prob), prediction))
# $example off$ spark.stop()
"""
Decision Tree Classification Example.
"""
from __future__ import print_function # $example on$
from pyspark.ml import Pipeline
from pyspark.ml.classification import DecisionTreeClassifier
from pyspark.ml.feature import StringIndexer, VectorIndexer
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
# $example off$
from pyspark.sql import SparkSession if __name__ == "__main__":
spark = SparkSession\
.builder\
.appName("DecisionTreeClassificationExample")\
.getOrCreate() # $example on$
# Load the data stored in LIBSVM format as a DataFrame.
data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt") # Index labels, adding metadata to the label column.
# Fit on whole dataset to include all labels in index.
labelIndexer = StringIndexer(inputCol="label", outputCol="indexedLabel").fit(data)
# Automatically identify categorical features, and index them.
# We specify maxCategories so features with > 4 distinct values are treated as continuous.
featureIndexer =\
VectorIndexer(inputCol="features", outputCol="indexedFeatures", maxCategories=4).fit(data) # Split the data into training and test sets (30% held out for testing)
(trainingData, testData) = data.randomSplit([0.7, 0.3]) # Train a DecisionTree model.
dt = DecisionTreeClassifier(labelCol="indexedLabel", featuresCol="indexedFeatures") # Chain indexers and tree in a Pipeline
pipeline = Pipeline(stages=[labelIndexer, featureIndexer, dt]) # Train model. This also runs the indexers.
model = pipeline.fit(trainingData) # Make predictions.
predictions = model.transform(testData) # Select example rows to display.
predictions.select("prediction", "indexedLabel", "features").show(5) # Select (prediction, true label) and compute test error
evaluator = MulticlassClassificationEvaluator(
labelCol="indexedLabel", predictionCol="prediction", metricName="accuracy")
accuracy = evaluator.evaluate(predictions)
print("Test Error = %g " % (1.0 - accuracy)) treeModel = model.stages[2]
# summary only
print(treeModel)
# $example off$ spark.stop()

管道里的主要概念

MLlib提供标准的接口来使联合多个算法到单个的管道或者工作流,管道的概念源于scikit-learn项目。

1.数据框:机器学习接口使用来自Spark SQL的数据框形式数据作为数据集,它可以处理多种数据类型。比如,一个数据框可以有不同的列存储文本、特征向量、标签值和预测值。

2.转换器:转换器是将一个数据框变为另一个数据框的算法。比如,一个机器学习模型就是一个转换器,它将带有特征数据框转为预测值数据框。

3.估计器:估计器是拟合一个数据框来产生转换器的算法。比如,一个机器学习算法就是一个估计器,它训练一个数据框产生一个模型。

4.管道:一个管道串起多个转换器和估计器,明确一个机器学习工作流。

5.参数:管道中的所有转换器和估计器使用共同的接口来指定参数。

工作原理

管道由一系列有顺序的阶段指定,每个状态时转换器或估计器。每个状态的运行是有顺序的,输入的数据框通过每个阶段进行改变。在转换器阶段,transform()方法被调用于数据框上。对于估计器阶段,fit()方法被调用来产生一个转换器,然后该转换器的transform()方法被调用在数据框上。

下面的图说明简单的文档处理工作流的运行。

spark pipeline 例子的更多相关文章

  1. spark JavaDirectKafkaWordCount 例子分析

    spark  JavaDirectKafkaWordCount 例子分析: 1. KafkaUtils.createDirectStream( jssc, String.class, String.c ...

  2. Spark Pipeline官方文档

    ML Pipelines(译文) 官方文档链接:https://spark.apache.org/docs/latest/ml-pipeline.html 概述 在这一部分,我们将要介绍ML Pipe ...

  3. Spark SQL例子

    综合案例分析 现有数据集 department.json与employee.json,以部门名称和员工性别为粒度,试计算每个部门分性别平均年龄与平均薪资. department.json如下: {&q ...

  4. Spark Pipeline

    一个简单的Pipeline,用作estimator.Pipeline由有序列的stages组成,每个stage是一个Estimator或者一个Transformer. 当Pipeline调用fit,s ...

  5. Spark Streaming 例子

    NetworkWordCount.scala /* * Licensed to the Apache Software Foundation (ASF) under one or more * con ...

  6. 看到了一个pipeline例子,

    pipeline { agent any options { timestamps() } parameters { string(name: 'GIT_BRANCH', defaultValue: ...

  7. spark执行例子eclipse maven打包jar

    首先在eclipse Java EE中新建一个Maven project具体选项如下 点击Finish创建成功,接下来把默认的jdk1.5改成jdk1.8 然后编辑pom.xml加入spark-cor ...

  8. spark scala 例子

    object ScalaApp { def main(args: Array[String]): Unit = { var conf = new SparkConf() conf.setMaster( ...

  9. Spark.ML之PipeLine学习笔记

    地址: http://spark.apache.org/docs/2.0.0/ml-pipeline.html   Spark PipeLine 是基于DataFrames的高层的API,可以方便用户 ...

随机推荐

  1. gdb学习-checkpoint,watch

    checkpoint的内容参考: http://blog.chinaunix.net/uid-23629988-id-2943273.html 这一篇主要是checkpoint,在next之前加che ...

  2. 使用Modernizr检测支持CSS3

    使用Modernizr检测支持CSS3 如果支持某个属性,会增加一个class,名字就是该属性: 不支持,名字是no-某属性 还提供了一个全局Modernizr对象,使用如下: <script ...

  3. 剑指offer_面试题_从上往下打印二叉树

    题目:从上往下打印出二叉树的每一个结点.同一层的结点依照从左到右的顺序打印.比如输入图4.5中的二叉树.则依次打印出8.6.10.5.7.9.11. 8 /     \ 6     10 /   \ ...

  4. JS数组去重 包含去除多个 NaN

    Array.prototype.uniq = function () { var arr = []; var flag = true; this.forEach(function(item) {   ...

  5. CAS算法

    /** * CAS(Compare-And-Swap)算法保证了数据的原子性 * CAS算法是硬件对于并发操作共享数据的支持 * CAS包含了3个操作数: * 内存值 V 看成两步 读取内存值为1步 ...

  6. windows模式编译

    //预编译,linker链接,Windows模式#pragma comment(linker,"/subsystem:\"windows\" /entry:\" ...

  7. 移动端fixed后 横竖屏切换时上部或下部出现空隙问题

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. BZOJ 2793: [Poi2012]Vouchers(调和级数)

    Time Limit: 20 Sec  Memory Limit: 64 MBSubmit: 582  Solved: 250[Submit][Status][Discuss] Description ...

  9. jQuery学习(三)——选择器总结

    1.基本选择器 id选择器:$(“#id名称”); 元素选择器:$(“元素名称”); 类选择器:$(“.类名”); 通配符:* 多个选择器共用(并集) 案例代码: <!DOCTYPE html& ...

  10. layui layer 弹框

    layer 这个是一个web弹层组件,挺好用的...然后项目框架是SSM... layer.open主要是用来弹出来一个iframe弹窗,然后用来展示数据也行,用来修改也行,这次记录的主要是展示,展示 ...