多层感知器(MLP)

 from __future__ import print_function
from pyspark.ml.classification import MultilayerPerceptronClassifier
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
from pyspark.sql import SparkSession spark = SparkSession\
.builder.appName("multilayer_perceptron_classification_example").getOrCreate() # 加载数据
data = spark.read.format("libsvm")\
.load("data/mllib/sample_multiclass_classification_data.txt") # 切分训练集和测试集
splits = data.randomSplit([0.6, 0.4], 1234)
train = splits[0]
test = splits[1] # 输入、隐层、隐层、输出个数
layers = [4, 5, 4, 3] # 创建多层感知器
trainer = MultilayerPerceptronClassifier(maxIter=100, layers=layers, blockSize=128, seed=1234) # 训练模型
model = trainer.fit(train) # 预测和计算准确度
result = model.transform(test)
result.show()
predictionAndLabels = result.select("prediction", "label")
evaluator = MulticlassClassificationEvaluator(metricName="accuracy")
print("Test set accuracy = " + str(evaluator.evaluate(predictionAndLabels))) spark.stop()
+-----+--------------------+----------+
|label| features|prediction|
+-----+--------------------+----------+
| 0.0|(4,[0,1,2,3],[-0....| 2.0|
| 0.0|(4,[0,1,2,3],[-0....| 0.0|
| 0.0|(4,[0,1,2,3],[-0....| 0.0|
| 0.0|(4,[0,1,2,3],[-0....| 2.0|
| 0.0|(4,[0,1,2,3],[-0....| 2.0|
| 0.0|(4,[0,1,2,3],[-1....| 2.0|
| 0.0|(4,[0,1,2,3],[0.1...| 0.0|
| 0.0|(4,[0,1,2,3],[0.2...| 0.0|
| 0.0|(4,[0,1,2,3],[0.3...| 0.0|
| 0.0|(4,[0,1,2,3],[0.3...| 0.0|
| 0.0|(4,[0,1,2,3],[0.3...| 0.0|
| 0.0|(4,[0,1,2,3],[0.4...| 0.0|
| 0.0|(4,[0,1,2,3],[0.5...| 0.0|
| 0.0|(4,[0,1,2,3],[0.7...| 0.0|
| 0.0|(4,[0,1,2,3],[0.8...| 0.0|
| 0.0|(4,[0,1,2,3],[1.0...| 0.0|
| 0.0|(4,[0,2,3],[0.166...| 0.0|
| 0.0|(4,[0,2,3],[0.388...| 0.0|
| 1.0|(4,[0,1,2,3],[-0....| 1.0|
| 1.0|(4,[0,1,2,3],[-0....| 1.0|
+-----+--------------------+----------+
only showing top 20 rows Test set accuracy = 0.901960784314
04-11 03:28