PHP code example of medansoftware / kmeans-algorithm-php
1. Go to this page and download the library: Download medansoftware/kmeans-algorithm-php 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/ */
medansoftware / kmeans-algorithm-php example snippets
ns = new \Algorithm\KMeans;
$kmeans->setAttributes(array(
'A',
'B'
));
$kmeans->setDataFromArgs(1, 1);
$kmeans->setDataFromArgs(2, 1);
$kmeans->setDataFromArgs(4, 3);
$kmeans->setDataFromArgs(5, 4);
$kmeans->setClusterCount(2);
/*
* Use data points at indexes 0 and 1
* as the initial centroids.
*/
$kmeans->setCentroid(0, 1);
/*
* Run K-Means with a maximum of 100 iterations.
*/
$kmeans->setIteration(100);
$kmeans->run();
echo '<h2>Initial Centroids</h2>';
echo '<pre>';
print_r($kmeans->getInitialCentroid());
echo '</pre>';
echo '<h2>Final Centroids</h2>';
echo '<pre>';
print_r($kmeans->getCentroid());
echo '</pre>';
echo '<h2>Iterations</h2>';
echo 'Iterations executed: ' . $kmeans->countIterations();
echo '<h2>Results</h2>';
echo '<pre>';
print_r($kmeans->getAllResults());
echo '</pre>';
ns = new \Algorithm\KMeans;
$kmeans->setAttributes(array(
'x'
));
$kmeans->setDataFromArgs(1);
$kmeans->setDataFromArgs(2);
$kmeans->setDataFromArgs(6);
$kmeans->setDataFromArgs(7);
$kmeans->setDataFromArgs(8);
$kmeans->setDataFromArgs(10);
$kmeans->setDataFromArgs(15);
$kmeans->setDataFromArgs(17);
$kmeans->setDataFromArgs(20);
$kmeans->setClusterCount(3);
/*
* Use data points at indexes 1, 5, and 7
* as the initial centroids.
*
* The selected values are 2, 10, and 17.
*/
$kmeans->setCentroid(1, 5, 7);
/*
* Run K-Means with a maximum of 100 iterations.
*/
$kmeans->setIteration(100);
$kmeans->run();
echo '<h2>Initial Centroids</h2>';
echo '<pre>';
print_r($kmeans->getInitialCentroid());
echo '</pre>';
echo '<h2>Final Centroids</h2>';
echo '<pre>';
print_r($kmeans->getCentroid());
echo '</pre>';
echo '<h2>Iterations</h2>';
echo 'Iterations executed: ' . $kmeans->countIterations();
echo '<h2>Logs</h2>';
echo '<pre>';
print_r($kmeans->catchLogs());
echo '</pre>';