使用Spark和Python中的决策树算法进行分析时遇到的问题

我正在为电信行业进行流失分析,并拥有一个样本数据集。我编写了下面的代码,使用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])

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注