Deep Learning Algorithm Implementations 1.0.0
C++ implementations of fundamental deep learning algorithms
Loading...
Searching...
No Matches
kmeans.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <limits>
4#include <random>
5#include <vector>
6#include "../utils/matrix.hpp"
7
15namespace ml {
16 using namespace utils;
17
40 template<typename T>
41 class KMeans {
42 public:
51 KMeans(size_t k, size_t max_iters = 300, T tol = 1e-4, int random_state = -1);
52
58 void fit(const Matrix<T> &data);
59
66 std::vector<int> predict(const Matrix<T> &data) const;
67
74 std::vector<int> fit_predict(const Matrix<T> &data);
75
82
88 T inertia() const;
89
95 size_t n_iter() const;
96
97 private:
98 size_t k_;
99 size_t max_iters_;
100 T tol_;
101 int random_state_;
102 Matrix<T> centroids_;
103 T inertia_;
104 size_t n_iter_;
105 bool is_fitted_;
106
112 void init_centroids(const Matrix<T> &data);
113
120 std::vector<int> assign_clusters(const Matrix<T> &data) const;
121
128 void update_centroids(const Matrix<T> &data, const std::vector<int> &labels);
129
137 T squared_distance(const std::vector<T> &point1, const std::vector<T> &point2) const;
138 };
139
143
144} // namespace ml
T inertia() const
Get the within-cluster sum of squares (inertia)
Definition kmeans.cpp:96
std::vector< int > fit_predict(const Matrix< T > &data)
Fit the model and predict cluster labels.
Definition kmeans.cpp:82
std::vector< int > predict(const Matrix< T > &data) const
Predict cluster labels for the given data.
Definition kmeans.cpp:74
Matrix< T > cluster_centers() const
Get the cluster centroids.
Definition kmeans.cpp:88
size_t n_iter() const
Get the number of iterations performed.
Definition kmeans.cpp:104
void fit(const Matrix< T > &data)
Fit the K-Means model to the data.
Definition kmeans.cpp:20
Namespace containing traditional machine learning algorithms.
Definition kmeans.hpp:15