2016-05-04 3 views
0

Я реализую DecisionTreeClassifier в pyspark, используя модуль Pipeline, так как у меня есть несколько шагов по разработке технических средств для выполнения на моем наборе данных. код похож на пример из искровой документации:pyspark Модель интерпретации из модели трубопровода

from pyspark import SparkContext, SQLContext 
from pyspark.ml import Pipeline 
from pyspark.ml.classification import DecisionTreeClassifier 
from pyspark.ml.feature import StringIndexer, VectorIndexer 
from pyspark.ml.evaluation import MulticlassClassificationEvaluator 

# Load the data stored in LIBSVM format as a DataFrame. 
data = sqlContext.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="precision") 
accuracy = evaluator.evaluate(predictions) 
print("Test Error = %g " % (1.0 - accuracy)) 

treeModel = model.stages[2] 
# summary only 
print(treeModel) 

Вопрос в том, как я выполняю интерпретацию модели на этом? Объектная модель трубопровода не имеет метод toDebugString() аналогичен методу в классе DecisionTree.trainClassifier И я не могу использовать DecisionTree.trainClassifier в моем трубопроводе, потому что trainclassifier() принимает обучающие данные, параметр.

В то время как трубопровод принимает обучающие данные в качестве аргумента в запрессовки() метод и преобразование() на тестовых данных

Есть ли способ использовать трубопровод и по-прежнему выполнять интерпретацию модели & найти значение атрибута?

ответ

0

Да, я использовал метод ниже почти во всех моих интерпретаторах модели в pyspark. В приведенной ниже строке используются соглашения об именах из фрагмента кода.

dtm = model.stages[-1] # you estimator is the last stage in the pipeline 
# hence the DecisionTreeClassifierModel will be the last transformer in the PipelineModel object 
dtm.explainParams() 

Теперь у вас есть доступ ко всем методам модели DecisionTreeClassifierModel. Все доступные методы и атрибуты можно найти here. Код не был протестирован на вашем примере.

+0

Обратите внимание, что аналогичным, но более запутанным способом можно извлечь модель оценки из лучшей модели CrossValidatorModel. – ffmmmm

Смежные вопросы