MNIST: digit recognition with kNN (no training)

Implementation in pure PHP

Running the kNN example in pure PHP.

 
<?php

use app\classes\KNearestNeighbors;
use 
app\classes\MnistLoader;

try {
    [
$trainSamples, $trainLabels] = MnistLoader::load('train.csv', normalize: true);
    [
$testSamples, $testLabels] = MnistLoader::load('test.csv', normalize: true);
} catch (
Exception $e) {
    echo 
'<div class="alert alert-danger" role="alert">' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . '</div>';
    exit;
}

$model = new KNearestNeighbors($trainSamples, $trainLabels);

// Calculate model accuracy
$score = $model->score($testSamples, $testLabels, k: 3, trainLimit: 300);

echo 
'Train samples handled: ' . number_format(count($trainSamples)) . PHP_EOL;
echo 
'Test samples handled: ' . number_format(count($testSamples)) . PHP_EOL . PHP_EOL;
echo 
'Accuracy: ' . round($score * 100, 2) . '%';
Samples of digit: 0
Predicted digit: 0
Predicted digit: 0
Predicted digit: 0
Samples of digit: 1
Predicted digit: 1
Predicted digit: 1
Predicted digit: 1
Result: Memory: 0 Mb Time running: < 0.001 sec.
Train samples handled: 12,666
Test samples handled: 2,116

Accuracy: 99.81%