簡介
多層感知器,分類器
簡單的多層神經網絡
注意:神經網絡的層數不能超過3層,否則會出現梯度消失問題
代碼
// Load the data stored in LIBSVM format as a DataFrame.
val data = spark.read.format("libsvm")
.load("D://data/mllib/sample_multiclass_classification_data.txt")
// Split the data into train and test
val splits = data.randomSplit(Array(0.6, 0.4), seed = 1234L)
val train = splits(0)
val test = splits(1)
// specify layers for the neural network:
// input layer of size 4 (features), two intermediate of size 5 and 4
// and output of size 3 (classes)
val layers = Array[Int](4, 5, 4, 3)
// create the trainer and set its parameters
// 建立多層感知器分類器MLPC模型
// 傳統神經網絡通常,層數<=5,隱藏層數<=3
// layers 指定神經網絡的圖層
// MaxIter 最大迭代次數
// stepSize 每次優化的迭代步長,僅適用於solver="gd"
// blockSize 用於在矩陣中堆疊輸入數據的塊大小以加速計算。 數據在分區內堆疊。 如果塊大小大於分區中的剩餘數據,則將其調整爲該數據的大小。 建議大小介於10到1000之間。默認值:128
// initialWeights 模型的初始權重
// solver 算法優化。 支持的選項:“gd”(minibatch梯度下降)或“l-bfgs”。 默認值:“l-bfgs”
val trainer = new MultilayerPerceptronClassifier()
.setLayers(layers)
.setBlockSize(128)
.setSeed(1234L)
.setMaxIter(100)
// train the model
val model = trainer.fit(train)
// compute accuracy on the test set
val result = model.transform(test)
val predictionAndLabels = result.select("prediction", "label")
val evaluator = new MulticlassClassificationEvaluator()
.setMetricName("accuracy")
val accuracy = evaluator.evaluate(result)
println(s"test Error ${1.0 - accuracy}")