ML Ecosystem in PHP
Learning examples
These examples will help you understand how you can use ML in PHP. They are not full-fledged applications, but they will help you understand the basics of working with ML in PHP.
Example with PHP-ML
A typical scenario: you have features from a database, you want to quickly train a model for classification or regression, save it, and use it in runtime without external services.
Let's consider a simple and illustrative example. In it, we train a k-nearest neighbors (k-NN) classifier on a small set of points, each of which belongs to one of two classes — $a$ or $b$. After training, the model must determine which class a new point belongs to. We specify the training set as coordinates on a plane and the corresponding class labels. For the point $[3, 2]$, the algorithm returns class b because its nearest neighbors in the training set belong to this class.
Example of use
<?php
use Phpml\Classification\KNearestNeighbors;
$samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
$labels = ['a', 'a', 'a', 'b', 'b', 'b'];
$classifier = new KNearestNeighbors();
$classifier->train($samples, $labels);
$prediction = $classifier->predict([3, 2]);
echo $prediction;
b