Case 3. Classification with RubixML

Implementation in RubixML

In this case we implement a simple k-NN classification example using the RubixML library. We prepare a labeled dataset, train a KNearestNeighbors classifier, and predict the class of a new sample.

 
<?php

use Rubix\ML\Classifiers\KNearestNeighbors;
use 
Rubix\ML\Datasets\Labeled;
use 
Rubix\ML\Datasets\Unlabeled;
use 
Rubix\ML\Kernels\Distance\Euclidean;

$samples = [
    [
5, 2.1],
    [
3, 1.8],
    [
10, 6.5],
    [
12, 7.0],
    [
9, 5.8],
];

$labels = ['casual', 'casual', 'engaged', 'engaged', 'engaged'];

$dataset = new Labeled($samples, $labels);

$model = new KNearestNeighbors(3, false, new Euclidean());
$model->train($dataset);

$query = new Unlabeled([[8, 5.5]]);
$prediction = $model->predict($query);

echo 
'Prediction: ' . $prediction[0];
Result: Memory: 0.358 Mb Time running: 0.008 sec.
Prediction: engaged