如何在PySpark中从www.example.com中提取模型超参数spark.ml?

qoefvg9y  于 2022-12-11  发布在  Spark
关注(0)|答案(8)|浏览(124)

我正在修改PySpark文档中的一些交叉验证代码,并试图让PySpark告诉我选择了什么模型:

from pyspark.ml.classification import LogisticRegression
from pyspark.ml.evaluation import BinaryClassificationEvaluator
from pyspark.mllib.linalg import Vectors
from pyspark.ml.tuning import ParamGridBuilder, CrossValidator

dataset = sqlContext.createDataFrame(
    [(Vectors.dense([0.0]), 0.0),
     (Vectors.dense([0.4]), 1.0),
     (Vectors.dense([0.5]), 0.0),
     (Vectors.dense([0.6]), 1.0),
     (Vectors.dense([1.0]), 1.0)] * 10,
    ["features", "label"])
lr = LogisticRegression()
grid = ParamGridBuilder().addGrid(lr.regParam, [0.1, 0.01, 0.001, 0.0001]).build()
evaluator = BinaryClassificationEvaluator()
cv = CrossValidator(estimator=lr, estimatorParamMaps=grid, evaluator=evaluator)
cvModel = cv.fit(dataset)

在PySpark shell中运行这个函数,我可以得到线性回归模型的系数,但是我似乎找不到交叉验证过程选择的lr.regParam的值。

In [3]: cvModel.bestModel.coefficients
Out[3]: DenseVector([3.1573])

In [4]: cvModel.bestModel.explainParams()
Out[4]: ''

In [5]: cvModel.bestModel.extractParamMap()
Out[5]: {}

In [15]: cvModel.params
Out[15]: []

In [36]: cvModel.bestModel.params
Out[36]: []
jchrr9hc

jchrr9hc1#

我也遇到了这个问题。我发现你需要调用java属性,因为一些原因,我不知道为什么。所以只要这样做:

from pyspark.ml.tuning import TrainValidationSplit, ParamGridBuilder, CrossValidator
from pyspark.ml.regression import LinearRegression
from pyspark.ml.evaluation import RegressionEvaluator

evaluator = RegressionEvaluator(metricName="mae")
lr = LinearRegression()
grid = ParamGridBuilder().addGrid(lr.maxIter, [500]) \
                                .addGrid(lr.regParam, [0]) \
                                .addGrid(lr.elasticNetParam, [1]) \
                                .build()
lr_cv = CrossValidator(estimator=lr, estimatorParamMaps=grid, \
                        evaluator=evaluator, numFolds=3)
lrModel = lr_cv.fit(your_training_set_here)
bestModel = lrModel.bestModel

打印所需参数:

>>> print 'Best Param (regParam): ', bestModel._java_obj.getRegParam()
0
>>> print 'Best Param (MaxIter): ', bestModel._java_obj.getMaxIter()
500
>>> print 'Best Param (elasticNetParam): ', bestModel._java_obj.getElasticNetParam()
1

这也适用于其他方法,如extractParamMap()。他们应该很快就会修复这个问题。

dsekswqp

dsekswqp2#

这可能不如wernerchao的回答好(因为在变量中存储超参数并不方便),但你可以通过以下方式快速查看交叉验证模型的最佳超参数:

cvModel.getEstimatorParamMaps()[ np.argmax(cvModel.avgMetrics) ]
bfrts1fy

bfrts1fy3#

假设cvModel3Day是您的模型名称,可以在SparkScala中提取参数,如下所示

val params = cvModel3Day.bestModel.asInstanceOf[PipelineModel].stages(2).asInstanceOf[GBTClassificationModel].extractParamMap()

val depth = cvModel3Day.bestModel.asInstanceOf[PipelineModel].stages(2).asInstanceOf[GBTClassificationModel].getMaxDepth

val iter = cvModel3Day.bestModel.asInstanceOf[PipelineModel].stages(2).asInstanceOf[GBTClassificationModel].getMaxIter

val bins = cvModel3Day.bestModel.asInstanceOf[PipelineModel].stages(2).asInstanceOf[GBTClassificationModel].getMaxBins

val features  = cvModel3Day.bestModel.asInstanceOf[PipelineModel].stages(2).asInstanceOf[GBTClassificationModel].getFeaturesCol

val step = cvModel3Day.bestModel.asInstanceOf[PipelineModel].stages(2).asInstanceOf[GBTClassificationModel].getStepSize

val samplingRate  = cvModel3Day.bestModel.asInstanceOf[PipelineModel].stages(2).asInstanceOf[GBTClassificationModel].getSubsamplingRate
cyvaqqii

cyvaqqii4#

我的头也撞到了墙上,不幸的是,你只能得到特定模型的特定参数。幸运的是,对于逻辑回归,你可以访问截距和权重,不幸的是,你不能检索regParam。这可以通过以下方式完成:

best_lr = cv.bestModel

#get weigths
best_lr.weights
>>>DenseVector([3.1573])

#or better
best_lr.coefficients
>>>DenseVector([3.1573])

#get intercept
best_lr.intercept
>>>-1.0829958115287153

正如我之前所写的,每个模型都有很少的参数可以提取。总体而言,从管道中获取相关模型(例如,当交叉验证器在管道上运行时,cv.bestModel)可以通过以下方式完成:

best_pipeline = cv.bestModel
best_pipeline.stages
>>>[Tokenizer_4bc8884ad68b4297fd3c,CountVectorizer_411fbdeb4100c2bfe8ef, PCA_4c538d67e7b8f29ff8d0,LogisticRegression_4db49954edc7033edc76]

每个模型通过简单的列表索引获得

best_lr = best_pipeline.stages[3]

现在可以应用上述方法。

fdx2calv

fdx2calv5#

其实有两个问题:

  • 拟合模型有哪些方面(如系数和截距)
  • 拟合bestModel所使用的 meta参数是什么。

不幸的是,拟合估计器(模型)的python API不允许(容易地)直接访问估计器的参数,这使得很难回答后一个问题。
但是,有一个使用API的变通方法。

%pyspark
from pyspark.ml import Pipeline
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.evaluation import BinaryClassificationEvaluator
from pyspark.ml.tuning import CrossValidator, ParamGridBuilder
logit = LogisticRegression(maxIter=10)
pipeline = Pipeline(stages=[logit])
paramGrid = ParamGridBuilder() \
    .addGrid(logit.regParam, [0, 0.01, 0.05, 0.1, 0.5, 1]) \
    .addGrid(logit.elasticNetParam, [0.0, 0.1, 0.5, 0.8, 1]) \
    .build()
evaluator = BinaryClassificationEvaluator(metricName = 'areaUnderPR')
crossval = CrossValidator(estimator=pipeline,
                          estimatorParamMaps=paramGrid,
                          evaluator=evaluator,
                          numFolds=5)
tuned_model = crossval.fit(train)
model = tuned_model.bestModel

然后,可以使用java对象上的泛型方法来获取参数值,而无需显式引用getRegParam()之类的方法:

java_model = model.stages[-1]._java_obj
{param.name: java_model.getOrDefault(java_model.getParam(param.name)) 
    for param in paramGrid[0]}

这将执行以下步骤:
1.从最佳模型的最后阶段获得由估计器创建的拟合logit模型:crossval.fit(..).bestModel.stages[-1]
1.从_java_obj获取内部java对象
1.从paramGrid(一个字典列表)中获取所有配置的名称。只使用第一行,假设它是一个实际的网格,如,每行包含相同的键。否则,您需要收集任何行中使用过的所有名称。
1.从java对象中获取相应的Param<T>参数标识符。
1.将Param<T>示例传递给getOrDefault()函数以获取实际值

0ejtzxu1

0ejtzxu16#

花了几分钟才破译出来,但我猜出来了。

from pyspark.ml.tuning import CrossValidator, ParamGridBuilder

    # prenotation: I've built out my model already and I am calling the validator ParamGridBuilder
paramGrid = ParamGridBuilder() \
                          .addGrid(hashingTF.numFeatures, [1000]) \
                          .addGrid(linearSVC.regParam, [0.1, 0.01]) \
                          .addGrid(linearSVC.maxIter, [10, 20, 30]) \
                          .build()
crossval = CrossValidator(estimator=pipeline,\
                          estimatorParamMaps=paramGrid,\
                          evaluator=MulticlassClassificationEvaluator(),\
                          numFolds=2)

cvModel = crossval.fit(train)

prediction = cvModel.transform(test)

bestModel = cvModel.bestModel

    #applicable to your model to pull list of all stages
for x in range(len(bestModel.stages)):
print bestModel.stages[x]

    #get stage feature by calling correct Transformer then .get<parameter>()
print bestModel.stages[3].getNumFeatures()
l2osamch

l2osamch7#

(2020年5月21日)
我知道这是一个老问题,但我找到了一个方法来做到这一点。
@Pierre Gourseaud给了我们一个很好的方法来获取最佳模型的超参数

hyperparams = model_cv.getEstimatorParamMaps()[np.argmax(model_cv.avgMetrics)]
print(hyperparams)
[(Param(parent='ALS_cd65d45ab31c', name='implicitPrefs', doc='whether to use implicit preference'),
  True),
 (Param(parent='ALS_cd65d45ab31c', name='nonnegative', doc='whether to use nonnegative constraint for least squares'),
  True),
 (Param(parent='ALS_cd65d45ab31c', name='coldStartStrategy', doc="strategy for dealing with unknown or new users/items at prediction time. This may be useful in cross-validation or production scenarios, for handling user/item ids the model has not seen in the training data. Supported values: 'nan', 'drop'."),
  'drop'),
 (Param(parent='ALS_cd65d45ab31c', name='rank', doc='rank of the factorization'),
  28),
 (Param(parent='ALS_cd65d45ab31c', name='maxIter', doc='max number of iterations (>= 0).'),
  20),
 (Param(parent='ALS_cd65d45ab31c', name='regParam', doc='regularization parameter (>= 0).'),
  0.01),
 (Param(parent='ALS_cd65d45ab31c', name='alpha', doc='alpha for implicit preference'),
  20.0)]

但这不是以一种时尚的方式看,所以可以这样做:

import re

hyper_list = []

for i in range(len(hyperparams.items())):
    hyper_name = re.search("name='(.+?)'", str([x for x in hyperparams.items()][i])).group(1)
    hyper_value = [x for x in hyperparams.items()][i][1]

    hyper_list.append({hyper_name: hyper_value})

print(hyper_list)
[{'implicitPrefs': True}, {'nonnegative': True}, {'coldStartStrategy': 'drop'}, {'rank': 28}, {'maxIter': 20}, {'regParam': 0.01}, {'alpha': 20.0}]

在我的案例中,我训练了一个ALS模型,但它应该适用于您的案例,因为我也训练了交叉验证!

ruyhziif

ruyhziif8#

如果只需要参数名及其值

{param.name: value for param, value in zip(cvModel.bestModel.extractParamMap().keys(), cvModel.bestModel.extractParamMap().values())}

如果你不介意描述等使用

cvModel.bestModel.extractParamMap()

输出将

Out[58]: {'aggregationDepth': 2,
 'elasticNetParam': 0.0,
 'family': 'auto',
 'featuresCol': 'features',
 'fitIntercept': True,
 'labelCol': 'label',
 'maxBlockSizeInMB': 0.0,
 'maxIter': 10,
 'predictionCol': 'prediction',
 'probabilityCol': 'probability',
 'rawPredictionCol': 'rawPrediction',
 'regParam': 0.01,
 'standardization': True,
 'threshold': 0.5,
 'tol': 1e-06}

Out[54]: {Param(parent='LogisticRegression_a6db1af69019', name='aggregationDepth', doc='suggested depth for treeAggregate (>= 2).'): 2,
 Param(parent='LogisticRegression_a6db1af69019', name='elasticNetParam', doc='the ElasticNet mixing parameter, in range [0, 1]. For alpha = 0, the penalty is an L2 penalty. For alpha = 1, it is an L1 penalty.'): 0.0,
 Param(parent='LogisticRegression_a6db1af69019', name='family', doc='The name of family which is a description of the label distribution to be used in the model. Supported options: auto, binomial, multinomial'): 'auto',
 Param(parent='LogisticRegression_a6db1af69019', name='featuresCol', doc='features column name.'): 'features',
 Param(parent='LogisticRegression_a6db1af69019', name='fitIntercept', doc='whether to fit an intercept term.'): True,
 Param(parent='LogisticRegression_a6db1af69019', name='labelCol', doc='label column name.'): 'label',
 Param(parent='LogisticRegression_a6db1af69019', name='maxBlockSizeInMB', doc='maximum memory in MB for stacking input data into blocks. Data is stacked within partitions. If more than remaining data size in a partition then it is adjusted to the data size. Default 0.0 represents choosing optimal value, depends on specific algorithm. Must be >= 0.'): 0.0,
 Param(parent='LogisticRegression_a6db1af69019', name='maxIter', doc='max number of iterations (>= 0).'): 10,
 Param(parent='LogisticRegression_a6db1af69019', name='predictionCol', doc='prediction column name.'): 'prediction',
 Param(parent='LogisticRegression_a6db1af69019', name='probabilityCol', doc='Column name for predicted class conditional probabilities. Note: Not all models output well-calibrated probability estimates! These probabilities should be treated as confidences, not precise probabilities.'): 'probability',
 Param(parent='LogisticRegression_a6db1af69019', name='rawPredictionCol', doc='raw prediction (a.k.a. confidence) column name.'): 'rawPrediction',
 Param(parent='LogisticRegression_a6db1af69019', name='regParam', doc='regularization parameter (>= 0).'): 0.01,
 Param(parent='LogisticRegression_a6db1af69019', name='standardization', doc='whether to standardize the training features before fitting the model.'): True,
 Param(parent='LogisticRegression_a6db1af69019', name='threshold', doc='Threshold in binary classification prediction, in range [0, 1]. If threshold and thresholds are both set, they must match.e.g. if threshold is p, then thresholds must be equal to [1-p, p].'): 0.5,
 Param(parent='LogisticRegression_a6db1af69019', name='tol', doc='the convergence tolerance for iterative algorithms (>= 0).'): 1e-06}

相关问题