This example is part of the k-means tutorial. See Step 2: Pick Random Centers and Classify
#include <ostream>
#include <random>
#include <vector>
double DistanceSquare(
const Point& b)
const {
return (x - b.x) * (x - b.x) + (y - b.y) * (y - b.y);
}
};
return os << '(' << p.x << ',' << p.y << ')';
}
struct ClosestCenter {
size_t cluster_id;
};
std::ostream&
operator << (std::ostream& os,
const ClosestCenter& cc) {
return os << '(' << cc.cluster_id << ':' << cc.point << ')';
}
std::default_random_engine rng(std::random_device { } ());
std::uniform_real_distribution<double> dist(0.0, 1000.0);
auto points =
ctx, 100,
[&](const size_t&) {
return Point { dist(rng), dist(rng) };
})
.Cache();
points.Print("points");
auto centers = points.Sample( 10);
std::vector<Point> local_centers = centers.AllGather();
auto closest = points.Map(
[local_centers](
const Point& p) {
double min_dist = p.DistanceSquare(local_centers[0]);
size_t cluster_id = 0;
for (size_t i = 1; i < local_centers.size(); ++i) {
double dist = p.DistanceSquare(local_centers[i]);
if (dist < min_dist)
min_dist = dist, cluster_id = i;
}
return ClosestCenter { cluster_id, p };
});
closest.Print("closest");
}
}