Multilayer perceptron classifier
Multilayer perceptron classifier (MLPC) is a classifier based on the feedforward artificial neural network. MLPC consists of multiple layers of nodes. Each layer is fully connected to the next layer in the network. Nodes in the input layer represent the input data. All other nodes map inputs to outputs by a linear combination of the inputs with the node's weights w and bias b and applying an activation function. This can be written in matrix form for MLPC with K+1 layers as follows:
Nodes in intermediate layers use sigmoid (logistic) function:
Nodes in the output layer use softmax function:
The number of nodes N in the output layer corresponds to the number of classes.
MLPC employs backpropagation for learning the model. We use the logistic loss function for optimization and L-BFGS as an optimization routine.
1
import org.apache.spark.ml.classification.MultilayerPerceptronClassifier
2
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator
3
​
4
// Load the data stored in LIBSVM format as a DataFrame.
5
val data = spark.read.format("libsvm")
6
.load("file:///opt/spark/data/mllib/sample_multiclass_classification_data.txt")
7
​
8
// Split the data into train and test
9
val splits = data.randomSplit(Array(0.6, 0.4), seed = 1234L)
10
val train = splits(0)
11
val test = splits(1)
12
​
13
// specify layers for the neural network:
14
// input layer of size 4 (features), two intermediate of size 5 and 4
15
// and output of size 3 (classes)
16
val layers = Array[Int](4, 5, 4, 3)
17
​
18
// create the trainer and set its parameters
19
val trainer = new MultilayerPerceptronClassifier()
20
.setLayers(layers)
21
.setBlockSize(128)
22
.setSeed(1234L)
23
.setMaxIter(100)
24
​
25
// train the model
26
val model = trainer.fit(train)
27
​
28
// compute accuracy on the test set
29
val result = model.transform(test)
30
val predictionAndLabels = result.select("prediction", "label")
31
val evaluator = new MulticlassClassificationEvaluator()
32
.setMetricName("accuracy")
33
​
34
println(s"Test set accuracy = ${evaluator.evaluate(predictionAndLabels)}")
35
​
36
/*
37
​
38
Output:
39
Test set accuracy = 0.9019607843137255
40
​
41
*/
Copied!
Trick:
The number of neurons in the first layer needs to be equal to number of features
Last modified 1yr ago
Copy link