43 #include <eigen3/Eigen/Core>
50 template <
typename _T>
86 void kcenters(
const std::vector<_T>& data,
unsigned int k, std::vector<unsigned int>& centers,
Matrix& dists)
90 std::vector<double> min_dist(data.size(), std::numeric_limits<double>::infinity());
94 if (((
long unsigned int)dists.rows()) < data.size() || ((
long unsigned int)dists.cols()) < k)
95 dists.resize(std::max(2 * ((
long unsigned int)dists.rows()) + 1, data.size()), k);
97 centers.push_back(std::uniform_int_distribution<size_t>{ 0, data.size() - 1 }(
generator_));
98 for (
unsigned i = 1; i < k; ++i)
101 const _T& center = data[centers[i - 1]];
102 double max_dist = -std::numeric_limits<double>::infinity();
103 for (
unsigned j = 0; j < data.size(); ++j)
105 if ((dists(j, i - 1) =
distFun_(data[j], center)) < min_dist[j])
106 min_dist[j] = dists(j, i - 1);
108 if (min_dist[j] > max_dist)
111 max_dist = min_dist[j];
115 if (max_dist < std::numeric_limits<double>::epsilon())
117 centers.push_back(ind);
120 const _T& center = data[centers.back()];
121 unsigned i = centers.size() - 1;
122 for (
unsigned j = 0; j < data.size(); ++j)
123 dists(j, i) =
distFun_(data[j], center);
An instance of this class can be used to greedily select a given number of representatives from a set...
const DistanceFunction & getDistanceFunction() const
Get the distance function used.
GreedyKCenters(const GreedyKCenters &)=default
void kcenters(const std::vector< _T > &data, unsigned int k, std::vector< unsigned int > ¢ers, Matrix &dists)
Greedy algorithm for selecting k centers.
void setDistanceFunction(const DistanceFunction &distFun)
Set the distance function to use.
Eigen::MatrixXd Matrix
A matrix type for storing distances between points and centers.
std::function< double(const _T &, const _T &)> DistanceFunction
The definition of a distance function.
DistanceFunction distFun_
The used distance function.
GreedyKCenters(GreedyKCenters &&) noexcept=default