PySpark机器学习(1)——随机森林

本文主要在PySpark环境中实现随机森林算法:

%pyspark

from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import StringIndexer
from pyspark.ml.classification import RandomForestClassifier
from pyspark.sql import Row

#任务目标:通过随机森林解决二分类问题并评估分类效果

#1.读取数据
data = spark.sql("""select * from datatable""")

#2.构造训练数据集
dataSet = data.na.fill('0').rdd.map(list)

(trainData, testData) = dataSet.randomSplit([0.7, 0.3])
#print(trainData.take(1))
trainingSet = trainData.map(lambda x:Row(label=x[-1], features=Vectors.dense(x[:-1]))).toDF()

train_num = trainingSet.count()
print("训练样本数:{}".format(train_num))
print(trainingSet.show())

#3.使用随机森林进行训练
stringIndexer = StringIndexer(inputCol="label", outputCol="indexed")
si_model = stringIndexer.fit(trainingSet)
tf = si_model.transform(trainingSet)
tf.show()

rf = RandomForestClassifier(numTrees=10, maxDepth=8, labelCol="indexed", seed=42)
rfcModel = rf.fit(tf)

#输出模型特征重要性、子树权重
print("模型特征重要性:{}".format(rfcModel.featureImportances))
print("模型特征数:{}".format(rfcModel.numFeatures))

#4.测试
testSet = testData.map(lambda x:Row(label=x[-1], features=Vectors.dense(x[:-1]))).toDF()

print("测试样本数:{}".format(testSet.count()))
print(testSet.show())

si_model = stringIndexer.fit(testSet)
test_tf = si_model.transform(testSet)

result = rfcModel.transform(test_tf)
result.show()

#5.分类效果评估
total_amount=result.count()
correct_amount = result.filter(result.indexed==result.prediction).count()
precision_rate = correct_amount/total_amount
print("预测准确率为:{}".format(precision_rate))

positive_precision_amount = result.filter(result.indexed == 0).filter(result.prediction == 0).count()
negative_precision_amount = result.filter(result.indexed == 1).filter(result.prediction == 1).count()
positive_false_amount = result.filter(result.indexed == 0).filter(result.prediction == 1).count()
negative_false_amount = result.filter(result.indexed == 1).filter(result.prediction == 0).count()

print("正样本预测准确数量:{},负样本预测准确数量:{}".format(positive_precision_amount,negative_precision_amount))

positive_amount = result.filter(result.indexed == 0).count()
negative_amount = result.filter(result.indexed == 1).count()

print("正样本数:{},负样本数:{}".format(positive_amount,negative_amount))
print("正样本预测错误数量:{},负样本错误准确数量:{}".format(positive_false_amount,negative_false_amount))

recall_rate1 = positive_precision_amount/positive_amount
recall_rate2 = negative_precision_amount/negative_amount

print("正样本召回率为:{},负样本召回率为:{}".format(recall_rate1,recall_rate2))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值