Clustering examples

This commit is contained in:
Arkadiusz Kondas committed 2019-03-20 20:52:11 +01:00
1 parent 7d5c98e53f
commit 50af45491b
6 files changed
+8632 -4

No files matched your search

+1
View File
@@ -9,3 +9,4 @@ humbuglog.*
/data/t10k-labels-idx1-ubyte
/data/stackoverflow_*.csv
/data/crimes*.csv
/data/bbc
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace PhpmlExamples;
use Phpml\Clustering\KMeans;
use Phpml\Math\Distance\Euclidean;
require 'vendor/autoload.php';
$lines = file(__DIR__.'/../data/crimes-robbery.csv');
foreach ($lines as &$line) {
$row = explode(';', $line);
$line = [(float) $row[0], (float) $row[1]];
}
function squaredDistances(array $center, array $points): float
{
$sum = 0;
$metric = new Euclidean();
foreach ($points as $point) {
$sum += $metric->sqDistance($center, $point);
}
return $sum;
}
for ($i=1; $i<21; $i++) {
$clusterer = new KMeans($i);
$clusters = $clusterer->cluster($lines);
$centronoids = $clusterer->centronoids();
$sum = 0;
foreach ($centronoids as $key => $centronoid) {
$sum += squaredDistances($centronoid, $clusters[$key]);
}
echo sprintf('SSE (k=%s): %s' . PHP_EOL, $i, $sum);
}
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace PhpmlExamples;
use Phpml\Clustering\KMeans;
use Phpml\Math\Distance\Euclidean;
require 'vendor/autoload.php';
$lines = file(__DIR__.'/../data/syntetic-g.csv');
foreach ($lines as &$line) {
$row = explode(',', $line);
$line = [(float) $row[0], (float) $row[1]];
}
function squaredDistances($center, $points): float
{
$sum = 0;
$metric = new Euclidean();
foreach ($points as $point) {
$sum += $metric->sqDistance($center, $point);
}
return $sum;
}
for ($i=1; $i<21; $i++) {
$clusterer = new KMeans($i);
$clusters = $clusterer->cluster($lines);
$centronoids = $clusterer->centronoids();
$sum = 0;
foreach ($centronoids as $key => $centronoid) {
$sum += squaredDistances($centronoid, $clusters[$key]);
}
echo sprintf('SSE (k=%s): %f' . PHP_EOL, $i, $sum);
}
File diff suppressed because it is too large. Load diff
+6500
View File
File diff suppressed because it is too large. Load diff
+1 -4
View File
@@ -26,10 +26,7 @@ def cluster_to_color(cluster):
with open('data/crimes-robbery-clusters.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=';')
for row in reader:
if row[0] == 'C':
marker = CircleMarker((float(row[2]), float(row[1])), (0,0,0), 15)
else:
marker = CircleMarker((float(row[2]), float(row[1])), cluster_to_color(row[0]), 6)
marker = CircleMarker((float(row[2]), float(row[1])), cluster_to_color(row[0]), 6)
m.add_marker(marker)
image = m.render(center=[-87.684871189, 41.8348221989])