[Spark] 03 - Programming
入门知识
PySpark MLlib
一、基本介绍
这里是MLlib,但目前推荐使用ml库直接针对DataFrame,这里使用老库,主要是为了“了解”。
Apache Spark提供了一个名为 MLlib 的机器学习API。PySpark也在Python中使用这个机器学习API。它支持不同类型的算法,如下所述
mllib.classification - spark.mllib 包支持二进制分类,多类分类和回归分析的各种方法。分类中一些最流行的算法是 随机森林,朴素贝叶斯,决策树 等。
mllib.clustering - 聚类是一种无监督的学习问题,您可以根据某些相似概念将实体的子集彼此分组。
mllib.fpm - 频繁模式匹配是挖掘频繁项,项集,子序列或其他子结构,这些通常是分析大规模数据集的第一步。 多年来,这一直是数据挖掘领域的一个活跃的研究课题。
mllib.linalg - 线性代数的MLlib实用程序。
mllib.recommendation - 协同过滤通常用于推荐系统。 这些技术旨在填写用户项关联矩阵的缺失条目。
spark.mllib - 它目前支持基于模型的协同过滤,其中用户和产品由一小组可用于预测缺失条目的潜在因素描述。 spark.mllib使用交替最小二乘(ALS)算法来学习这些潜在因素。
mllib.regression - 线性回归属于回归算法族。 回归的目标是找到变量之间的关系和依赖关系。使用线性回归模型和模型摘要的界面类似于逻辑回归案例。
二、代码示范
提供了一个简单的数据集。
使用数据集 - test.data 1,1,5.0
1,2,1.0
1,3,5.0
1,4,1.0
2,1,5.0
2,2,1.0
2,3,5.0
2,4,1.0
3,1,1.0
3,2,5.0
3,3,1.0
3,4,5.0
4,1,1.0
4,2,5.0
4,3,1.0
4,4,5.0
数据集
from __future__ import print_function
from pyspark import SparkContext
# 这里使用了mllib,比较老的api,最新的是ml。
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating
if __name__ == "__main__":
sc = SparkContext(appName="Pspark mllib Example")
data = sc.textFile("test.data") # 训练模型
ratings = data.map(lambda s: s.split(',')).map(lambda x: Rating(int(x[0]), int(x[1]), float(x[2])))
rank = 10
numIterations = 10
model = ALS.train(ratings, rank, numIterations) # 测试模型
testdata = ratings.map(lambda p: (p[0], p[1]))
predictions = model.predictAll(testdata).map(lambda r: ((r[0], r[1]), r[2]))
ratesAndPreds = ratings.map(lambda r: ((r[0], r[1]), r[2])).join(predictions)
MSE = ratesAndPreds.map(lambda r: (r[1][0] - r[1][1])**2).mean()
print("Mean Squared Error = " + str(MSE)) # Save and load model
model.save(sc, "target/tmp/myCollaborativeFilter")
sameModel = MatrixFactorizationModel.load(sc, "target/tmp/myCollaborativeFilter")
三、spark.ml 库
Ref: http://spark.apache.org/docs/latest/ml-guide.html
As of Spark 2.0, the RDD-based APIs in the spark.mllib package have entered maintenance mode. The primary Machine Learning API for Spark is now the DataFrame-based API in the spark.ml package.
- spark.mllib: 数据抽象是rdd。
- spark.ml: 数据抽象是dataframe。

NLP基础
一、TF-IDF 单词的重要性
第一步,分拆单词,构成单词集合
from pyspark.ml.feature import HashingTF, IDF, Tokenizer
sentenceData = spark.createDataFrame([
(0, "..."),
(1, "..."),
...
]).toDF("label", "sentence") tokenizer = Tokenizer(inputCol="sentence", outputCol="words")
wordsData = tokenizer.transform(sentenceData)
wordsData.show()
可见,多出了最后一列:

第二步,Hash成为特征向量
hashingTF = HashingTF(inputCol="words", outputCol="rawFeatures", numFeatures=2000)
featurizedData = hashingTF.transform(wordsData)
featurizedData.select("words", "rawFeatures").show(truncate=False)
第三步,IDF构造
idf = IDF(InputCol="rawFeatures", outputCol="features")
idfModel = idf.fit(featurizedData)
第四步,调权重
rescaledData = idfModel.transform(featurizedData)
rescaledData.select("feature", "label").show(truncate=False)
二、Word2Vec 单词的向量化
org.apache.spark.ml.feature包:
- StringIndexer
- IndexToString
- OneHotEncoder
- VectorIndexer
方法一,StringIndexer
频率最高的为0。IndexToString(),是反操作。
from pyspark.ml.feature import StringIndexer # 构建一个DataFrame, 设置StringIndexer的输入列和输出列的名字
df = spark.createDataFrame([(0, "a"), (1, "b"), (2, "c"), (3, "a"), (4, "a"), (5, "c")], ["id", "category"])
indexer = StringIndexer(inputCol="category", outputCol="categoryIndex") # 训练并转换
model = indexer.fit(df)
indexed = model.transform(df) indexed.show()

方法二,VectorIndexer
from pyspark.ml.feature import VectorIndexer
from pyspark.ml.linalg import Vector, Vectors df = spark.createDataFrame([ \
(Vectors.dense(-1.0, 1.0, 1.0), ),
(Vectors.dense(-1.0, 3.0, 1.0), ),
(Vectors.dense( 0.0, 5.0, 1.0), )], ["features"]) indexer = VectorIndexer(inputCol="features", outputCol="indexed", maxCategories=2)
indexerModel = indexer.fit(df)
categoricalFeatures = indexerModel.categoryMaps.keys()
转换后查看。
indexed = indexerModel.transform(df)
indexed.show()
第一列,只有两种,认为是类别特征,故转换;
第二列,有三种,不认为是类别特征,故保持;
第三列,只有一种,认为是列别特征,故转换。

工作流 Pipeline
Logistic 回归分类器
(1) 获得 SparkSesson
from pyspark.sql import SparkSession
spark = SparkSession.builder.master("local").appName("WordCount").getOrCreate()
(2) 准备 train 数据

(3) 构建流水线
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])
model = pipeline.fit(training)
(4) 测试并预测

开始预测以上这些数据,得到预测结果。
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))玩儿
决策树分类器
(1) 引用包

(2) 构造数据
def f(x):
rel = {}
rel['feature'] = Vectors.dense(float(x[0]), float(x[1]), float(x[2]), float(x[3]))
ref['label'] = str(x[4])
return rel data = spark.sparkContext.textFile("file:///usr/local/spark/iris.txt").
map(lambda line: line.split(',')).
map(lambda p: Row(**f(p))).
toDF() # 成为二维表
(3) 转换器

(4) 分类模型
dtClassfier = DecisionTreeClassifier(). \
setLabelCol("indexedLabel"). \
setFeaturesCol("indexedFeatures")
(5) 构建流水线
dtPipeline = Pipeline().setStages([labelIndexer, featureIndexer, dtClassifier, labelConverter]) dtPipelineModel = dtPipeline.fit(trainingData)
dtPredictions = dtPipelineModel.transform(testData)
dtPredictions.select("predictedLabel", "label", "features").show(20)

(6) 评估模型
evaluator = MulticlassClassificationEvaluator(). \
setLabelCol("indexedLabel"). \
setPredictionCol("prediction") dtAccuracy = evaluator.evaluate(dtPredictions)
AWS ETL Pipeline
一、学习资源
Ref: 使用 AWS Glue 和 Amazon Athena 实现无服务器的自主型机器学习
Ref: AWS Glue 常见问题
Extract is the process of reading data from a database. In this stage, the data is collected, often from multiple and different types of sources.
Transform is the process of converting the extracted data from its previous form into the form it needs to be in so that it can be placed into another database. Transformation occurs by using rules or lookup tables or by combining the data with other data.
Load is the process of writing the data into the target database.
二、代码示范
ETL具备pipeline的思想,这里没用,但可以加上。
import sys
from awsglue.utils import getResolvedOptions
from awsglue.context import GlueContext
from awsglue.job import Job
from awsglue.transforms import SelectFields
from awsglue.transforms import RenameField
from awsglue.dynamicframe import DynamicFrame, DynamicFrameReader, DynamicFrameWriter, DynamicFrameCollection
from pyspark.context import SparkContext
from pyspark.ml.regression import LinearRegression
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.regression import LinearRegression
from pyspark.ml.clustering import KMeans args = getResolvedOptions(sys.argv, ['JOB_NAME']) #JOB INPUT DATA
destination = "s3://luiscarosnaprds/gluescripts/results/ClusterResults3.parquet"
namespace = "nyc-transportation-version2"
tablename = "green"
# 固定套路
sc = SparkContext()
glueContext = GlueContext(sc)
job = Job(glueContext)
job.init(args['JOB_NAME'], args) #Load table and select fields
datasource0 = glueContext.create_dynamic_frame.from_catalog(name_space = namespace, table_name = tablename) SelectFields0 = SelectFields.apply(frame = datasource0, paths=["trip_distance","fare_amount","pickup_longitude","pickup_latitude" ])
DataFrame0 = DynamicFrame.toDF(SelectFields0) # 变成了二维表
#------------------------------------------------------------
#Filter some unwanted values
DataFrameFiltered = DataFrame0.filter("pickup_latitude > 40.472278 AND pickup_latitude < 41.160886 AND pickup_longitude > -74.300074 AND pickup_longitude < -71.844077")
#Select features and convert to SparkML required format
features = ["pickup_longitude","pickup_latitude"]
assembler = VectorAssembler(inputCols=features,outputCol='features')
assembled_df = assembler.transform(DataFrameFiltered) #Fit and Run Kmeans
kmeans = KMeans(k=100, seed=1)
model = kmeans.fit(assembled_df)
transformed = model.transform(assembled_df) #Save data to destination
transformed.write.mode('overwrite').parquet(destination)
job.commit()
End.
[Spark] 03 - Programming的更多相关文章
- Spark Streaming Programming Guide
参考,http://spark.incubator.apache.org/docs/latest/streaming-programming-guide.html Overview SparkStre ...
- <Spark><Advanced Programming>
Introduction 介绍两种共享变量的方式: accumulators:聚集信息 broadcast variables:高效地分布large values 介绍对高setup costs任务的 ...
- spark第六篇:Spark Streaming Programming Guide
预览 Spark Streaming是Spark核心API的扩展,支持高扩展,高吞吐量,实时数据流的容错流处理.数据可以从Kafka,Flume或TCP socket等许多来源获取,并且可以使用复杂的 ...
- [Spark] 07 - Spark Streaming Programming
Streaming programming 一.编程套路 编写Streaming程序的套路 创建DStream,也就定义了输入源. 对DStream进行一些 “转换操作” 和 "输出操作&q ...
- [Spark] Scala programming - basic level
环境配置 IDE: https://www.jetbrains.com/idea/ 子雨大数据之Spark入门教程(Scala版) /* implement */ 语言特性 Online compil ...
- [AI] 深度数据 - Data
Data Engineering Data Pipeline Outline [DE] How to learn Big Data[了解大数据] [DE] Pipeline for Data Eng ...
- Spark踩坑记——数据库(Hbase+Mysql)
[TOC] 前言 在使用Spark Streaming的过程中对于计算产生结果的进行持久化时,我们往往需要操作数据库,去统计或者改变一些值.最近一个实时消费者处理任务,在使用spark streami ...
- Spark Streaming容错的改进和零数据丢失
本文来自Spark Streaming项目带头人 Tathagata Das的博客文章,他现在就职于Databricks公司.过去曾在UC Berkeley的AMPLab实验室进行大数据和Spark ...
- sparklyr包--实现R与Spark接口
1.sparklyr包简介 Rstudio公司发布的sparklyr包具有以下几个功能: 实现R与Spark的连接: sparklyr包提供了一个完整的dplyr后端,可筛选并聚合Spark数据集,接 ...
随机推荐
- Gradle 是什么
写在前面的话,最近在系统的学习Gradle,本来想写一篇关于 Gradle 的介绍. 但在官网发现了这篇关于 Gradle 的介绍,已经介绍的很好了,我就很直接翻译过来了. 原文地址 https:// ...
- Springboot源码分析之代理三板斧
摘要: 在Spring的版本变迁过程中,注解发生了很多的变化,然而代理的设计也发生了微妙的变化,从Spring1.x的ProxyFactoryBean的硬编码岛Spring2.x的Aspectj注解, ...
- 微服务SpringCloud之Spring Cloud Config配置中心服务化
在前面两篇Spring Cloud Config配置中心的博客中都是需要指定配置服务的地址url:spring.cloud.config.uri,客户端都是直接调用配置中心的server端来获取配置文 ...
- c++采集windows操作系统名称
WINAPI windows通过c++获取操作系统主要分两种: 1. windows是8.1版本以下版本:获取操作系统可以通过windows提供的api中GetVersionEx函数来获取 2. wi ...
- 初识JAVA语言
推荐阅读: 我的CSDN 我的博客园 QQ群:704621321 前言 很多游戏开发者可能会有疑问,你会C#,JS,TS,为什么还要初识JAVA呢?有人可能会说,多学点对自己有好处 ...
- C#开发BIMFACE系列13 服务端API之获取转换状态
系列目录 [已更新最新开发文章,点击查看详细] 在<C#开发BIMFACE系列12 服务端API之文件转换>中详细介绍了7种文件转换的方法.发起源文件/模型转换后,转换过程可能成功 ...
- div拖拽
分析逻辑关于该过程有一下3个动作 1.点击 2.移动 3.释放鼠标 1.点击时获得点击下去的一点的坐标(盒子的top,left),去除默认事件. 2.移动时不断改变盒子的坐标.(移动的dom目标应该为 ...
- iOS中的几个重要方法
iOS开发中几个重要的方法: 加载类到内存,程序刚启动的时候调用,调用在main函数之前 1.+(void)load{ } 初始化类,类第一次使用的时候调用一次 2.+(void)initialize ...
- POJ-1511 Invitation Cards( 最短路,spfa )
题目链接:http://poj.org/problem?id=1511 Description In the age of television, not many people attend the ...
- D-query
SPOJ - DQUERY 题意 求区间内出现一共有几种数字. 上次写了一个主席树,这次用一下莫队,莫队是离线询问的一种操作,将询问分块,如果在同一个块内就按照右端点排序,如果不在同一个块内就按照块的 ...