OneVsRest
OneVsRest is an example of a machine learning reduction for performing multiclass classification given a base classifier that can perform binary classification efficiently. It is also known as β€œOne-vs-All.”
OneVsRest is implemented as an Estimator. For the base classifier, it takes instances of Classifier and creates a binary classification problem for each of the k classes. The classifier for class i is trained to predict whether the label is i or not, distinguishing class i from all other classes.
Predictions are done by evaluating each binary classifier and the index of the most confident classifier is output as label.
Examples
The example below demonstrates how to load the Iris dataset, parse it as a DataFrame and perform multiclass classification using OneVsRest. The test error is calculated to measure the algorithm accuracy.
1
import org.apache.spark.ml.classification.{LogisticRegression, OneVsRest}
2
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator
3
// load data file.
4
val inputData = spark.read.format("libsvm")
5
.load("file:///opt/spark/data/mllib/sample_libsvm_data.txt")
6
// generate the train/test split.
7
val Array(train, test) = inputData.randomSplit(Array(0.8, 0.2))
8
// instantiate the base classifier
9
val classifier = new LogisticRegression()
10
.setMaxIter(10)
11
.setTol(1E-6)
12
.setFitIntercept(true)
13
// instantiate the One Vs Rest Classifier.
14
val ovr = new OneVsRest().setClassifier(classifier)
15
// train the multiclass model.
16
val ovrModel = ovr.fit(train)
17
// score the model on test data.
18
val predictions = ovrModel.transform(test)
19
// obtain evaluator.
20
val evaluator = new MulticlassClassificationEvaluator()
21
.setMetricName("accuracy")
22
// compute the classification error on test data.
23
val accuracy = evaluator.evaluate(predictions)
24
println(s"Test Error = ${1 - accuracy}")
25
​
26
/*
27
Output:
28
Test Error = 0.0
29
​
30
*/
Copied!
​
Last modified 1yr ago
Copy link