使用pyspark进行机器学习(聚类问题)
使用pyspark进行机器学习(回归问题)
LogisticRegression
class pyspark.ml.classification.LogisticRegression(self, featuresCol="features", labelCol="label", predictionCol="prediction", maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, threshold=0.5, thresholds=None, probabilityCol="probability", rawPredictionCol="rawPrediction", standardization=True, weightCol=None, aggregationDepth=2, family="auto")
参数解释
regParam: 正则化参数(>=0)
elasticNetParam: ElasticNet混合参数,0-1之间,当alpha为0时,惩罚为L2正则化,当为1时为L1正则化
fitIntercept: 是否拟合一个截距项
Standardization: 是否在拟合数据之前对数据进行标准化
aggregationDepth: 树聚合所建议的深度(>=2)
Family:标签分布簇的名称,可选:“auto", "binomial", "multinomial"
参数的getter和setter方法
拟合后的模型拥有的方法和属性
coefficientMatrix: 模型的系数矩阵(对于multinomial而言)
coefficients: 双变量logistic回归的模型系数,如果是多元Logistic回归的话会有异常
evaluate(dataset):在测试集上评估模型
hasSummary: 是否有summary
intercept: 二变量logistic模型的截距
interceptVector: 多变量logistic模型截距
summary:获得summary
transform(dataset,param=None)
Summary拥有的属性
predictions: 模型transform方法输出的预测数据框
probabilityCol: 给出每个类的概率
对于双变量的summary而言拥有的属性:
areaUnderROC: 计算AUC
fMeasureByTreshold: 返回带有两个字段(阈值,F-统计量)的数据框,beta=1.0
pr: 返回精度-召回率两字段的数据框
precisionByTreshold:返回带有阈值,精度两字段的数据框,应用了从转换后数据里的所有可能概率作为阈值来计算精度
recallByTreshold: 返回带有阈值,召回率两字段的数据框,应用了从转换后数据里的所有可能概率作为阈值来计算召回率
roc:返回带有两字段FPR, TPR的数据框,
代码
from pyspark.ml.linalg import Vectors
from pyspark.sql import Row
from pyspark.ml.classification import LogisticRegression
#双变量Logistic回归
bdf = sc.parallelize([Row(label=1.0,weight=2.0,features=Vectors.dense(1.0)),Row(label=0.0, weight=2.0, features=Vectors.sparse(1,[],[]))]).toDF()
bdf.show()
blor = LogisticRegression(maxIter=5, regParam=0.01,weightCol='weight')
blorModel = blor.fit(bdf)
blorModel.coefficients
blorModel.intercept
#多元Logistic回归
mdf = sc.parallelize([Row(label=1.0,weight=2.0, features=Vectors.dense(1.0)),Row(label=0.0,weight=2.0, features=Vectors.sparse(1,[],[])),Row(label=2.,weight=2.0, features=Vectors.dense(3.0))]).toDF()
mlor=LogisticRegression(maxIter=5,regParam=0.01,weightCol='weight',family='multinomial')
mlorModel = mlor.fit(mdf)
print mlorModel.coefficientMatrix
mlorModel.interceptVector
#模型预测
test0=sc.parallelize([Row(features=Vectors.dense(-1.0))]).toDF()
result = blorModel.transform(test0).head()
result.prediction
result.probability
result.rawPrediction
test