MCPcopy Create free account
hub / github.com/arrayfire/arrayfire / kmeans

Function kmeans

examples/machine_learning/kmeans.cpp:61–108  ·  view source on GitHub ↗

kmeans(means, clusters, data, k) data: input, 1D or 2D (range > [0-1]) k: input, # desired means (k > 1) means: output, vector of means

Source from the content-addressed store, hash-verified

59// k: input, # desired means (k > 1)
60// means: output, vector of means
61void kmeans(array &means, array &clusters, const array in, int k,
62 int iter = 100) {
63 unsigned n = in.dims(0); // Num of data points
64 unsigned d = in.dims(2); // Num of features (will only be 1 in spider image example)
65
66 // reshape input
67 array data = in * 0;
68
69 // re-center and scale down data to [0, 1]
70 array minimum = min(in);
71 array maximum = max(in);
72
73 gfor(seq ii, d) {
74 data(span, span, ii) =
75 (in(span, span, ii) - minimum(ii).scalar<float>()) /
76 maximum(ii).scalar<float>();
77 }
78
79 // Initial guess of means
80 means = randu(1, k, d);
81 array curr_clusters = constant(0, data.dims(0)) - 1;
82 array prev_clusters;
83
84 // Stop updating after specified number of iterations
85 for (int i = 0; i < iter; i++) {
86 // Store previous cluster ids
87 prev_clusters = curr_clusters;
88
89 // Get cluster ids for current means
90 curr_clusters = clusterize(data, means);
91
92 // Break early if clusters not changing
93 unsigned num_changed = count<unsigned>(prev_clusters != curr_clusters);
94
95 if (num_changed < (n / 1000) + 1) break;
96
97 // Update current means for new clusters
98 means = new_means(data, curr_clusters, k);
99 }
100
101 // Scale up means
102 gfor(seq ii, d) {
103 means(span, span, ii) =
104 maximum(ii) * means(span, span, ii) + minimum(ii);
105 }
106
107 clusters = prev_clusters;
108}
109
110// K-Means image recoloring.
111// Shifts the hues of an image to the k mean hues.

Callers 1

kmeans_demoFunction · 0.85

Calls 7

randuFunction · 0.85
constantFunction · 0.85
clusterizeFunction · 0.85
new_meansFunction · 0.85
minFunction · 0.50
maxFunction · 0.50
dimsMethod · 0.45

Tested by

no test coverage detected