我正在为电信行业进行流失
分析,并拥有一个样本数据集。我编写了下面的代码,使用Spark
中的决策树
算法通过python
进行分析。在数据集中我有多个列,我选择了我需要的列作为我的特征
集。
from pyspark.mllib.regression import LabeledPointfrom pyspark.mllib.tree import DecisionTree, DecisionTreeModelfrom pyspark.mllib.util import MLUtilsimport os.pathimport numpy as npinputPath = 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)
现在这段代码运行良好并进行了预测,但我在prediction
集合或testdata
中缺少每个客户的标识符。在我的数据集中有一个customerid
列(列号为4),目前我没有选择它,因为它不是模型中要考虑的特征。我在将这个customerid
列与testdata
关联起来时遇到了困难,这些testdata
包含了客户的详细信息。如果我在LabeledPoint
中形成feature
向量时选择了数据集中的这一列,这将导致错误,因为它不是特征值。
我如何在我的分析中添加这一列,以便我可以得到流失值较高的前50名客户?
回答:
你可以像在预测后添加标签一样,采用相同的方式来添加这一列。
小助手:
customerIndex = ... # 放入列的索引def extract(line): """给定一行,创建一个元组 (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)) # 映射到元组
训练:
# 与之前一样(trainingdata, testdata) = final_data.randomSplit([0.7, 0.3])# 只使用点,将其余参数放在...的位置model = DecisionTree.trainRegressor(trainingdata.map(lambda x: x[1]), ...)
预测:
# 使用点进行预测predictions = model.predict(testdata.map(lambda x: x[1].features))# 添加客户ID和标签labelsIdsAndPredictions = (testData .map(lambda x: (x[0], x[1].label)) .zip(predictions))
提取前50名:
top50 = labelsIdsAndPredictions.top(50, key=lambda x: x[1])