-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgallery_clustering_animation.cpp
More file actions
282 lines (241 loc) 路 8.41 KB
/
Copy pathgallery_clustering_animation.cpp
File metadata and controls
282 lines (241 loc) 路 8.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/**
* @file gallery_clustering_animation.cpp
* @brief K-means Clustering Animation - Machine Learning Visualization
* @author plotly.cpp contributors
* @date 2025
*
* @example gallery_clustering_animation.cpp
*
* # K-means Clustering Animation
*
* This example demonstrates the K-means clustering algorithm through real-time
* animation, visualizing how the algorithm iteratively converges to optimal
* cluster assignments by alternating between assignment and centroid update
* steps.
*
* ## What You'll Learn
* - Implementing the complete K-means clustering algorithm with iterative
* convergence
* - Creating real-time animations that update plot elements dynamically during
* computation
* - Visualizing machine learning algorithm convergence through interactive
* plots
* - Managing multiple data traces (points and centroids) with different visual
* properties
* - Using color coding to represent cluster assignments and algorithm state
* - Applying mathematical distance calculations (Euclidean) for cluster
* assignment
* - Implementing convergence detection and algorithm termination conditions
*
* ## Sample Output
* The example creates an animated visualization of K-means clustering with:
* - 200 synthetic data points distributed across 4 natural clusters
* - 4 cluster centroids (marked with X symbols) that move during optimization
* - Real-time color updates showing point-to-cluster assignments
* - Convergence detection that stops animation when algorithm reaches optimum
* - Final visualization highlighting the discovered cluster structure
*
* The algorithm demonstrates the two-step process:
* 1. Assignment step: Points change color based on nearest centroid
* 2. Update step: Centroids move to cluster centers
*
* @image html clustering_animation.gif "K-means Clustering Animation Output"
*
* @see plotly::Figure For the main plotting interface
* @see plotly::Figure::restyle() For updating plot properties during animation
*/
#include "plotly/plotly.hpp"
#include <chrono>
#include <cmath>
#include <iostream>
#include <limits>
#include <random>
#include <string>
#include <thread>
#include <utility>
#include <vector>
struct Point {
double x, y;
int cluster;
std::string color;
};
struct Centroid {
double x, y;
std::string color;
};
// Calculate Euclidean distance
auto distance(const Point &p, const Centroid &c) -> double {
return std::sqrt((p.x - c.x) * (p.x - c.x) + (p.y - c.y) * (p.y - c.y));
}
auto main() -> int {
std::cout << "Starting K-means clustering animation..." << '\n';
plotly::Figure fig;
fig.openBrowser();
// Clustering parameters
const int numPoints = 200;
const int k = 4; // Number of clusters
const int maxIterations = 20;
std::vector<std::string> clusterColors = {"red", "blue", "green", "orange"};
// Generate synthetic data with natural clusters
std::random_device rd;
std::mt19937 gen(rd());
std::vector<Point> points;
points.reserve(numPoints);
// Create 4 natural clusters
std::vector<std::pair<double, double>> clusterCenters = {
{2.0, 2.0}, {-2.0, 2.0}, {-2.0, -2.0}, {2.0, -2.0}};
for (int cluster = 0; cluster < 4; cluster++) {
std::normal_distribution<double> xDist(clusterCenters[cluster].first, 0.8);
std::normal_distribution<double> yDist(clusterCenters[cluster].second, 0.8);
for (int i = 0; i < numPoints / 4; i++) {
points.push_back({xDist(gen), yDist(gen),
-1, // Initially unassigned
"gray"});
}
}
// Initialize centroids randomly
std::uniform_real_distribution<double> coordDist(-4.0, 4.0);
std::vector<Centroid> centroids(k);
for (int i = 0; i < k; i++) {
centroids[i] = {
.x = coordDist(gen), .y = coordDist(gen), .color = clusterColors[i]};
}
// Create initial plot data
std::vector<double> xCoords, yCoords;
std::vector<std::string> pointColors;
for (const auto &p : points) {
xCoords.push_back(p.x);
yCoords.push_back(p.y);
pointColors.emplace_back("gray");
}
std::vector<double> centroidX, centroidY;
std::vector<std::string> centroidColors;
for (const auto &c : centroids) {
centroidX.push_back(c.x);
centroidY.push_back(c.y);
centroidColors.push_back(c.color);
}
// Create traces
plotly::Object pointTrace = {
{"type", "scatter"},
{"mode", "markers"},
{"x", xCoords},
{"y", yCoords},
{"marker", {{"color", pointColors}, {"size", 8}, {"opacity", 0.7}}},
{"name", "Data Points"},
{"hovertemplate", "Point (%{x:.2f}, %{y:.2f})<extra></extra>"}};
plotly::Object centroidTrace = {
{"type", "scatter"},
{"mode", "markers"},
{"x", centroidX},
{"y", centroidY},
{"marker",
{{"color", centroidColors},
{"size", 20},
{"symbol", "x"},
{"line", {{"width", 3}, {"color", "black"}}}},
{"name", "Centroids"},
{"hovertemplate", "Centroid (%{x:.2f}, %{y:.2f})<extra></extra>"}}};
// Create layout
plotly::Object layout = {
{"title",
{{"text",
"K-means Clustering Animation<br>" +
std::string(
"<sub>Watch algorithm converge to optimal clusters</sub>")},
{"font", {{"size", 16}}}}},
{"xaxis",
{{"title", "X Coordinate"}, {"range", {-5, 5}}, {"showgrid", true}}},
{"yaxis",
{{"title", "Y Coordinate"},
{"range", {-5, 5}},
{"showgrid", true},
{"scaleanchor", "x"}}},
{"width", 800},
{"height", 700},
{"showlegend", true}};
// Create initial plot
std::vector<plotly::Object> data = {pointTrace, centroidTrace};
fig.newPlot(data, layout);
std::cout << "Starting K-means algorithm with " << k << " clusters..."
<< '\n';
// K-means algorithm with animation
for (int iteration = 0; iteration < maxIterations; iteration++) {
std::cout << "Iteration " << (iteration + 1) << "/" << maxIterations
<< '\n';
bool converged = true;
// Assignment step: assign each point to nearest centroid
for (auto &point : points) {
double minDist = std::numeric_limits<double>::max();
int bestCluster = 0;
for (int j = 0; j < k; j++) {
double dist = distance(point, centroids[j]);
if (dist < minDist) {
minDist = dist;
bestCluster = j;
}
}
if (point.cluster != bestCluster) {
converged = false;
point.cluster = bestCluster;
point.color = clusterColors[bestCluster];
}
}
// Update point colors
pointColors.clear();
for (const auto &p : points) {
pointColors.push_back(p.color);
}
// Update plot with new point assignments
fig.restyle({{"marker.color", {pointColors}}}, {0});
std::this_thread::sleep_for(std::chrono::milliseconds(800));
// Update step: move centroids to cluster centers
std::vector<double> newCentroidX(k, 0.0), newCentroidY(k, 0.0);
std::vector<int> clusterCounts(k, 0);
for (const auto &point : points) {
if (point.cluster >= 0) {
newCentroidX[point.cluster] += point.x;
newCentroidY[point.cluster] += point.y;
clusterCounts[point.cluster]++;
}
}
// Calculate new centroid positions
for (int j = 0; j < k; j++) {
if (clusterCounts[j] > 0) {
double newX = newCentroidX[j] / clusterCounts[j];
double newY = newCentroidY[j] / clusterCounts[j];
if (std::abs(centroids[j].x - newX) > 0.01 ||
std::abs(centroids[j].y - newY) > 0.01) {
converged = false;
}
centroids[j].x = newX;
centroids[j].y = newY;
}
}
// Update centroid positions
centroidX.clear();
centroidY.clear();
for (const auto &c : centroids) {
centroidX.push_back(c.x);
centroidY.push_back(c.y);
}
fig.restyle({{"x", {centroidX}}, {"y", {centroidY}}}, {1});
std::this_thread::sleep_for(std::chrono::milliseconds(800));
if (converged) {
std::cout << "Algorithm converged after " << (iteration + 1)
<< " iterations!" << '\n';
break;
}
}
// Update title to show completion
fig.relayout(
{{"title",
{{"text",
"K-means Clustering - CONVERGED!<br>" +
std::string(
"<sub>Algorithm found optimal cluster assignments</sub>")},
{"font", {{"size", 16}, {"color", "green"}}}}}});
std::cout << "Clustering animation completed. Close browser to exit." << '\n';
fig.waitClose();
return 0;
}