概述
ML包有三个主要的抽象类:转换器、评估器、管道
转换器:通过将一个新列附加到dataframe来转换数据。包含数据标准化、数据转换等内容,常用的有IndexToString,StringIndexer,VectorAssembler,Normalizer,OneHotEncoder,PCA等。
评估器:评估器可以被视为需要评估的统计模型,对观测对象做分类或预测。主要包括分类、回归、聚类三种。
管道:用来表示从转换到评估的端到端的过程。
聚类案例
数据
用于聚类的数据表是用户用电量表,包括的主要信息有:用户类型、用户用电量、本周用电量均值、上月用电量均值、用电量变动比率。数据如下图
转换器
本次分析中数据处理过程主要是将数据合并为一个向量。
合并向量处理
#要处理的列
num_col1 = ['cons_sort_code','g_rate','his_energy','week_energy','energy']
#向量合并
featuresCreator = ft.VectorAssembler(inputCols=[col for col in num_col1], outputCol="features")
评估器
from pyspark.ml.clustering import KMeans
import pyspark.ml.clustering as clus
#评估器
keamns = clus.KMeans(k=4,featuresCol = 'features')
管道与模型拟合
#管道
pipeline = Pipeline(stages = [featuresCreator,keamns])
#模型拟合
model = pipeline.fit(data)
test = model.transform(data)
最后结果test数据是包含有加工的向量“features"列和最终预测结果列"prediction"。
完整的代码
def keamns_deal():
num_col1 = ['cons_sort_code','g_rate','his_energy','week_energy']
for c in num_col1:
data = data.withColumn(c,data[c].cast(FloatType()))
#转换器
featuresCreator = ft.VectorAssembler(inputCols=[col for col in num_col1], outputCol="features")
#评估器
keamns = clus.KMeans(k=4,featuresCol = 'features')
#管道
pipeline = Pipeline(stages = [featuresCreator,keamns])
#拟合模型
model = pipeline.fit(data)
test = model.transform(data)
return test
test = keamns_deal(data)