<!DOCTYPE html><html><head><meta charset="utf-8"><title>Linear_Classifiers.md</title><style></style></head><body>
<p>Linear classifiers perform classification based on the linear combinition of the component features. Some examples of Linear Classifiers include: Naive Bayesian Classifier, Linear Discriminant Analysis, Logistic Regression and Perceptrons.</p>
<p>ArrayFire&#39;s easy to use API enables users to write such classifiers from scratch fairly easily. In this post we show how you can map mathematical equations to ArrayFire code and implement them from scratch.</p>
<ul>
<li>Naive Bayesian Classifier</li>
<li>Perceptron</li>
</ul>
<h3 id="naive-bayesian-classifier">Naive Bayesian Classifier</h3>
<p><a href="http://en.wikipedia.org/wiki/Naive_Bayes_classifier">Naive bayesian classifier</a> is a probabilistic classifier that assumes all the features in a feature vector are independent of each other. This assumption simplifies the bayesian rule to a linear number of operations represented below.</p>
<pre><code>P(Ck | x) = (P(Ck) / P(x)) * P(Ck | x0) * P(Ck | x1) * P(Ck | x2) ... P(Ck | xn)
</code></pre><p>Classification based on Naive Bayesian method uses the following phases:</p>
<ul>
<li>Training Phase: The probability ditribution of each feature variable is modeled</li>
<li>Prediction Phase: The probability of a sample belonging to each class is calculated based on the distributions from Phase 1.</li>
</ul>
<p>In our example, we are assuming all the input features to a normal distribution. This requres us to calculate the mean and the variance in the training phase.</p>
<p>The necessary ArrayFire code for the training phase can be seen below:</p>
<pre><code>    // Iterate through each class
    for (int ii = 0; ii &lt; num_classes; ii++) {

        // train_feats is of size [num_feats, num_train]
        // train_classes is of size [1, num_train]

        // Get indices where train_classes matches current class
        array idx = where(train_classes == ii);

        // Get train_feats from the current class only
        array train_feats_ii = train_feats(span, idx);

        // Get the distribution parameters
        mu(span, ii)  = mean(train_feats_ii, 1);
        sig2(span,ii)  = var(train_feats_ii, 0, 1);

        // Calculate priors
        priors[ii] = (float)idx.elements() / (float)num_samples;
    }
</code></pre><p>With the mean and variance of each class known, we can check the probabiltiy of a sample belonging to a particular class using the CDF of the distribution. The class with the highest probability wins.</p>
<p>However when working with a large number of feature variables, multiplication can lead to underflow errors. We can get around this by using <code>log</code> and <code>sum</code> instead of <code>exp</code> and <code>mul</code>.</p>
<p>The prediciton phase can be seen below.</p>
<pre><code>    for (int ii = 0; ii &lt; num_classes; ii++) {

        // test_feats is of size [num_feats, num_test]
        // mu, sig2 are of size  [num_feats, num_classes]
        // mu(span, ii), sig2(span, ii) will get mean and variance of current class

        // Tile the mean and variance of current class to match test_feats
        array Mu  = tile(mu (span, ii), 1, num_test);
        array Sig2 = tile(sig2(span, ii), 1, num_test) + 0.01; // to avoid dividing by zero

        array Df = test_feats - Mu;

        // CDF of normal distribution is as follows
        // array P = exp(-(Df * Df) / 2 * Sig2) / sqrt(2 * af::Pi * Sig2);
        // Multiply the conditional probabilities and the prior of the class
        // probs(span, ii) = priors[ii] * product(P).T();

        // Calculate log_P instead for numerical stability
        array log_P =  (-(Df * Df) / (2 * Sig2))  - log(sqrt(2 * af::Pi * Sig2));
        // Accumulate the log of conditional probabilities and the prior of the class
        log_probs(span, ii) = log(priors[ii]) + sum(log_P).T();
    }

    array val; // ignored
    array idx; // Gets the class id

    // Get the class ID with maximum log_probability
    max(val, idx, log_probs, 1);
</code></pre><h3 id="perceptron">Perceptron</h3>
<p><a href="http://en.wikipedia.org/wiki/Perceptron">Perceptron</a> is one of the first classification algorithms to use supervised learning. The perceptron transforms the weighted input features into an output in the range [0, 1].</p>
<p>// Enter the formulas for the transformation here</p>
<p>The equivalent ArrayFire code can be seen here:</p>
<pre><code>    // Activation function
    array sigmoid(const array &amp;Xw)
    {
        // Transforms Xw to a value between [0, 1]
        return 1 / (1 + exp(-Xw));
    }

    // Predict based on given parameters
    array predict(const array &amp;X, const array &amp;Weights)
    {
        // Weighted inputs
        array Xw = matmul(X, Weights);
        // Transform Weighted inputs to output
        return sigmoid(Xw);
    }
</code></pre><p>The weights of the perceptron are trained in an iterative process. The trained weights are then used for prediction on test data. Training a perceptron includes the following steps:</p>
<ol>
<li>Initialize the weights</li>
<li>Predict the output based on training data</li>
<li>Update the weights based on the following formula
//Enter formula here</li>
<li>if error greater than treshold, go to step 2.</li>
</ol>
<p>The training process of the perceptron can be implemented in ArrayFire using the following code.</p>
<pre><code>    for (int i = 0; i &lt; maxiter; i++) {

        // Make a prediction based on current weights
        array predicted = predict(input, Weights);

        // G
        array err = target - predicted;

        // Get the average error
        float mean_abs_err = mean&lt;float&gt;(abs(err));
        // Stop training if the error is less than specified bounds
        if (mean_abs_err  &lt; maxerr) break;

        // Update the weights based on the input and error
        Weights = Weights + alpha * matmul(transpose(input), err);
    }
</code></pre><h3 id="results">Results</h3>
<p>The complete source code for testing and benchmarking these algorithms can be found here:</p>
<ul>
<li><a href="https://github.com/arrayfire/arrayfire/blob/devel/examples/machine_learning/naive_bayes.cpp">Naive Bayesian Classifier</a></li>
<li><a href="https://github.com/arrayfire/arrayfire/blob/devel/examples/machine_learning/perceptron.cpp">Peceptron</a></li>
</ul>
<p>We tested these algorithms on a small subset of the MNIST database with 6100 training images, 3900 testing images.</p>
<p>The performance and accuracy results can be seen below:</p>
<table>
<thead>
<tr>
<th>Algorithm</th>
<th>Hardware</th>
<th>Accuracy</th>
<th>Train Time</th>
<th>Predict Time</th>
</tr>
</thead>
<tbody>
<tr>
<td>Naive Bayes</td>
<td>NVIDIA GTX 680</td>
<td>80.69%</td>
<td>0.003s</td>
<td>0.011s</td>
</tr>
<tr>
<td>Naive Bayes</td>
<td>AMD Radeon 7970</td>
<td>81.19%</td>
<td>0.007s</td>
<td>0.007s</td>
</tr>
<tr>
<td>Perceptron (1000 iters)</td>
<td>NVIDIA GTX 680</td>
<td>83.64%</td>
<td>2.005s</td>
<td>0.0003s</td>
</tr>
<tr>
<td>Perceptron (1000 iters)</td>
<td>AMD Radeon 7970</td>
<td>85.29%</td>
<td>4.935s</td>
<td>0.0005s</td>
</tr>
</tbody>
</table>
<h3 id="conclusion">Conclusion</h3>
<p>We have shown how simple mathematical expressions can easily translate into ArrayFire code. If you are interested in learning more about how ArrayFire can be used to develop Machine Learning applications, follow this blog!</p>
<p>If are going to GTC 2015, you may also be interested in the following tutorials.</p>
<ul>
<li><a href="https://registration.gputechconf.com/form/session-listing&amp;doSearch=true&amp;queryInput=S5803">S5803</a>: Simplified Machine Learning for CUDA</li>
<li><a href="https://registration.gputechconf.com/form/session-listing&amp;doSearch=true&amp;queryInput=S5722">S5722</a>: Deep Belief Networks using ArrayFire</li>
</ul>

</body></html>