python - Spark 和 Python 中使用决策树算法分析问题

标签 python machine-learning apache-spark decision-tree pyspark

我正在对电信行业进行流失分析,并且我有一个示例数据集。我在下面编写了这段代码,通过 pythonSpark 中使用决策树算法。在数据集中,我有多个列,我正在选择我的功能集所需的列。

from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.tree import DecisionTree, DecisionTreeModel
from pyspark.mllib.util import MLUtils
import os.path
import numpy as np


inputPath = os.path.join('file1.csv')
file_name = os.path.join(inputPath)
data = sc.textFile(file_name).zipWithIndex().filter(lambda (line,rownum): rownum>0).map(lambda (line, rownum): line)


final_data = data.map(lambda line: line.split(",")).filter(lambda line: len(line)>1).map(lambda line:LabeledPoint(1 if line[5] == 'True' else 0,[line[6],line[7]]))

(trainingdata, testdata) = final_data.randomSplit([0.7, 0.3])

model = DecisionTree.trainRegressor(trainingdata, categoricalFeaturesInfo={},
                                    impurity='variance', maxDepth=5, maxBins=32)

predictions = model.predict(testdata.map(lambda x: x.features))
prediction= predictions.collect()

labelsAndPredictions = testData.map(lambda lp: lp.label).zip(predictions)

现在,这段代码可以正常工作并进行预测,但我缺少的是预测集中或测试数据中每个客户的标识符。在我的数据集中,有一个 customerid 列(第 4 列),到目前为止我没有选择它,因为它不是模型中要考虑的特征。对于详细信息位于 testdata 中的客户,我很难将此 customerid 列与 testdata 关联起来。如果我添加此选项,请从我在 LabeledPoint 中形成的 feature 向量中的数据集中选择此列,那么这将导致错误,因为它不是特征值。

如何在我的分析中添加此列,以便获得流失值(value)较高的前 50 位客户?

最佳答案

您可以按照与预测后添加标签完全相同的方式进行操作。

小 helper :

customerIndex = ... # Put index of the column

def extract(line):
    """Given a line create a tuple (customerId, labeledPoint)"""
    label = 1 if line[5] == 'True' else 0
    point =  LabeledPoint(label, [line[6], line[7]])
    customerId = line[customerIndex]
    return (customerId, point)

使用extract函数准备日期:

final_data = (data
    .map(lambda line: line.split(","))
    .filter(lambda line: len(line) >1 )
    .map(extract)) # Map to tuples

火车:

# As before
(trainingdata, testdata) = final_data.randomSplit([0.7, 0.3])

# Use only points, put the rest of the arguments in place of ...
model = DecisionTree.trainRegressor(trainingdata.map(lambda x: x[1]), ...)

预测:

# Make predictions using points
predictions = model.predict(testdata.map(lambda x: x[1].features))

# Add customer id and label
labelsIdsAndPredictions = (testData
    .map(lambda x: (x[0], x[1].label))
    .zip(predictions))

提取前 50 名:

top50 = labelsIdsAndPredictions.top(50, key=lambda x: x[1])

关于python - Spark 和 Python 中使用决策树算法分析问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31973282/

相关文章:

python - 求不同年份同一日期的平均值

python - 我需要导入什么才能访问我的模型?

python - 使用django模板,如何删除循环中最后一项换行符

machine-learning - 在实践中如何使用 TfidfVectorizer 加元数据进行分类?

r - 是否有可能在 R 中精简 GBM 模型?

java - 如何从Java调用DataFrameFunctions.createCassandraTable?

scala - 未找到 SparkContext 类错误

python - 我对 Spark 中并行操作的理解是否正确?

python - 用于循环具有多变结构的 json 散列的优雅解决方案

python - 任何人都可以解释这种准确性和我的网络丢失的行为吗?