PHP code example of sphamster / classification-metrics

1. Go to this page and download the library: Download sphamster/classification-metrics library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sphamster / classification-metrics example snippets


use Sphamster\ClassificationMetrics\ConfusionMatrix;

// Your ground truth labels
$true_labels = ['cat', 'dog', 'cat', 'bird', 'dog', 'bird'];

// Your model's predictions
$predicted_labels = ['cat', 'dog', 'dog', 'bird', 'cat', 'bird'];

// Optional: specify the order of labels (if omitted, will use unique values from true_labels)
$labels = ['cat', 'dog', 'bird'];

// Create the confusion matrix
$confusion_matrix = ConfusionMatrix::fromPredictions($true_labels, $predicted_labels, $labels);

$labels = ['cat', 'dog', 'bird'];
$matrix = [
    [5, 1, 0],  // cat:  5 correct, 1 as dog, 0 as bird
    [2, 8, 1],  // dog:  2 as cat, 8 correct, 1 as bird
    [0, 0, 6]   // bird: 0 as cat, 0 as dog, 6 correct
];

$confusion_matrix = new ConfusionMatrix($labels, $matrix);

// Get true positives for all classes
$tp = $confusion_matrix->truePositives();
// Or for a specific class
$tp_cat = $confusion_matrix->truePositives('cat');

// Similarly for false positives, false negatives, and true negatives
$fp = $confusion_matrix->falsePositives();
$fn = $confusion_matrix->falseNegatives();
$tn = $confusion_matrix->trueNegatives();

use Sphamster\ClassificationMetrics\Metrics\Precision;
use Sphamster\ClassificationMetrics\Enums\AverageStrategy;

// Get precision for each class
$precision = new Precision();
$class_precision = $precision->measure($confusion_matrix);

// Get macro-averaged precision
$macro_precision = (new Precision(AverageStrategy::MACRO))->measure($confusion_matrix);

// Get micro-averaged precision
$micro_precision = (new Precision(AverageStrategy::MICRO))->measure($confusion_matrix);

// Get weighted-averaged precision
$weighted_precision = (new Precision(AverageStrategy::WEIGHTED))->measure($confusion_matrix);

use Sphamster\ClassificationMetrics\Metrics\Recall;

// Get recall for each class
$recall = new Recall();
$class_recall = $recall->measure($confusion_matrix);

// Similarly, you can use AverageStrategy for macro, micro, and weighted averaging

use Sphamster\ClassificationMetrics\Metrics\F1Score;

// Get F1 score for each class
$f1 = new F1Score();
$class_f1 = $f1->measure($confusion_matrix);

// Similarly, you can use AverageStrategy for macro, micro, and weighted averaging