//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** @author John Miller * @version 1.2 * @date Sat Aug 20 15:24:46 EDT 2016 * @see LICENSE (MIT style license file). */ package scalation.analytics.classifier import scala.reflect.ClassTag import scalation.linalgebra.{MatriI, VectoI, VectorD, VectorI} import scalation.linalgebra.gen.HMatrix3 import scalation.relalgebra.Relation import scalation.util.{banner, time} // Change import to change the base classifier: //import scalation.analytics.classifier.{NaiveBayes => BayesClf} //import scalation.analytics.classifier.{TANBayes => BayesClf} import BayesClassifier.me_default //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `BayesClfML` class implements an Integer-Based Naive Bayes Multi-Label Classifier, * which is a commonly used such classifier for discrete input data. The * classifier is trained using a data matrix 'x' and a classification matrix 'y'. * Each data vector in the matrix is classified into one of 'k' classes numbered * 0, ..., k-1. Prior probabilities are calculated based on the population of * each class in the training-set. Relative posterior probabilities are computed * by multiplying these by values computed using conditional probabilities. The * classifier is naive, because it assumes feature independence and therefore * simply multiplies the conditional probabilities. * @see www.aia-i.com/ijai/sample/vol3/no2/173-188.pdf * ----------------------------------------------------------------------------- * @param x the integer-valued data vectors stored as rows of a matrix * @param y the class matrix, where y(i, j) = class for row i and column j * @param fn the names for all features/variables * @param k the number of classes * @param cn the names for all classes */ class BayesClfML (BayesClf: BayesClassifier, x: MatriI, y: MatriI, fn: Array [String], k: Int, cn: Array [String], private var vc: VectoI = null, me: Int = me_default) extends ClassifierInt (x, y.col(0), fn, k, cn) { private val DEBUG = true // debug flag private val labels = y.dim2 // total number of labels private val bayes = Array.ofDim [BayesClassifier] (labels) // array of regular Bayes classifiers //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Build a model. * @param testStart starting index of test region (inclusive) used in cross-validation * @param testEnd ending index of test region (exclusive) used in cross-validation */ def buildModel (testStart: Int, testEnd: Int): (Array [Boolean], DAG) = { (Array.fill (n)(true), new DAG (Array.ofDim [Int] (n, 0))) } // buildModel //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Train the classifier by computing the probabilities for C, and the * conditional probabilities for X_j. * @param testStart starting index of test region (inclusive) used in cross-validation. * @param testEnd ending index of test region (exclusive) used in cross-validation. */ def train (testStart: Int, testEnd: Int) { for (l <- 0 until labels) { bayes(l) = BayesClf (x, y.col(l), fn, k, cn) bayes(l).buildModel () bayes(l).train (testStart, testEnd) } // for } // train //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Train the classifier by computing the probabilities for C, and the * conditional probabilities for X_j. * @param itrain indices of the instances considered train data */ override def train (itrain: Array [Int]) { for (l <- 0 until labels) { bayes(l) = BayesClf (x, y.col(l), fn, k, cn) bayes(l).train (itrain) } // for } // train //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Given a discrete data vector 'z', classify it returning the class number * (0, ..., k-1) with the highest relative posterior probability, returning * the class, its name and its relative probability. * @param z the data vector to classify */ def classify (z: VectoI): (Int, String, Double) = { var resMax = (0, "", 0.0) for (l <- 0 until labels) { val result = bayes(l).classify (z) if (result._3 > resMax._3) resMax = result } // for resMax // return the best class, its name and probability } // classify //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Reset or re-initialize all the population and probability vectors and * hypermatrices to 0. */ def reset () { for (l <- 0 until labels) bayes(l).reset () } // reset } // BayesClfML class //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** `BayesClfML` is the companion object for the `BayesClfML` class. */ object BayesClfML { //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Create a 'BayesClfML` object, passing 'x' and 'y' together in one matrix. * @param xy the data vectors along with their classifications stored as rows of a matrix * @param fn the names of the features * @param k the number of classes * @param vc the value count (number of distinct values) for each feature * @param me use m-estimates (me == 0 => regular MLE estimates) def apply (bayesClf: BayesClassifier, xy: MatriI, nx: Int, fn: Array [String], k: Int, cn: Array [String]): BayesClfML = { val x = xy.sliceCol (0, nx) // X-features val y = xy.sliceCol (nx, xy.dim2) // C-classes new BayesClfML (bayesClf, x, y, fn, k, cn) } // apply */ } // BayesClfML object import scalation.linalgebra.MatrixI //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `BayesClfMLTest` object is used to test the `BayesClfML` class. * Classify whether a car is more likely to be stolen (1) or not (1). * @see www.inf.u-szeged.hu/~ormandi/ai2/06-naiveBayes-example.pdf * > run-main scalation.analytics.classifier.BayesClfMLTest */ object BayesClfMLTest extends App { // x0: Color: Red (1), Yellow (0) // x1: Type: SUV (1), Sports (0) // x2: Origin: Domestic (1), Imported (0) // x3: Mpg: High (1), Low (0) // features: x0 x1 x2 x3 y0 y1 val xy = new MatrixI ((10, 6), 1, 0, 1, 1, 1, 0, // data matrix 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0) val fn = Array ("Color", "Type", "Origin", "Mpg") // feature/variable names val cn = Array ("No", "Yes") // class names - for both classes println ("xy = " + xy) println ("---------------------------------------------------------------") def bayesBuilder (): BayesClassifier = new NaiveBayes (xy, 4, fn, 2, cn) val bayes = BayesClfML (bayesBuilder, 2) // create the classifier // train the classifier --------------------------------------------------- bayes.train() // test sample ------------------------------------------------------------ val z1 = VectorI (1, 0, 1, 1) // existing data vector to classify val z2 = VectorI (1, 1, 1, 0) // new data vector to classify println ("classify (" + z1 + ") = " + bayes.classify (z1) + "\n") println ("classify (" + z2 + ") = " + bayes.classify (z2) + "\n") // bayes.crossValidateRand () // cross validate the classifier } // NaiveBayesMLTest object //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `NaiveBayesMLTest2` object is used to test the 'NaiveBayesML' class. * Given whether a person is Fast and/or Strong, classify them as making C = 1 * or not making C = 0 the football team. * > run-main scalation.analytics.classifier.NaiveBayesMLTest2 */ object NaiveBayesMLTest2 extends App { // training-set ----------------------------------------------------------- // x0: Fast // x1: Strong // y: Classification (No/0, Yes/1) // features: x0 x1 y val xy = new MatrixI ((10, 3), 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0) val fn = Array ("Fast", "Strong") // feature names val cn = Array ("No", "Yes") // class names println ("xy = " + xy) println ("---------------------------------------------------------------") val bayes = BayesClfML (xy, 2, fn, 2, cn) // create the classifier // train the classifier --------------------------------------------------- bayes.train () // test sample ------------------------------------------------------------ val z = VectorI (1, 0) // new data vector to classify println ("classify (" + z + ") = " + bayes.classify (z) + "\n") bayes.crossValidate () // cross validate the classifier } // NaiveBayesMLTest2 object //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `NaiveBayesMLTest3` object is used to test the 'NaiveBayesML' class. * > run-main scalation.analytics.classifier.NaiveBayesMLTest3 */ object NaiveBayesMLTest3 extends App { val filename = BASE_DIR + "breast-cancer.arff" var data = Relation (filename, -1, null) val xy = data.toMatriI2 (null) val fn = data.colName.toArray val cn = Array ("0", "1") // class names val bayes = BayesClfML (xy, xy.dim2-1, fn, 2, cn) // create the classifier bayes.train () bayes.crossValidate () } // NaiveBayesMLTest3 object