kmeans.hh
Go to the documentation of this file.
1 /* -*- mia-c++ -*-
2  *
3  * This file is part of MIA - a toolbox for medical image analysis
4  * Copyright (c) Leipzig, Madrid 1999-2017 Gert Wollny
5  *
6  * MIA is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with MIA; if not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20 
21 #ifndef __mia_core_kmeans_hh
22 #define __mia_core_kmeans_hh
23 #include <vector>
24 #include <numeric>
25 #include <cmath>
26 #include <stdexcept>
27 #include <iomanip>
28 #include <limits>
29 #include <mia/core/defines.hh>
30 #include <mia/core/errormacro.hh>
31 #include <mia/core/msgstream.hh>
32 #include <boost/concept/requires.hpp>
33 #include <boost/concept_check.hpp>
34 
36 
37 int EXPORT_CORE kmeans_get_closest_clustercenter(const std::vector<double>& classes, size_t l, double value);
38 
39 
40 template <typename InputIterator, typename OutputIterator>
41 bool kmeans_step(InputIterator ibegin, InputIterator iend, OutputIterator obegin,
42  std::vector<double>& classes, size_t l, int& biggest_class )
43 {
44  cvdebug()<< "kmeans enter: ";
45  for (size_t i = 0; i <= l; ++i )
46  cverb << std::setw(8) << classes[i]<< " ";
47  cverb << "\n";
48 
49  biggest_class = -1;
50  const double convLimit = 0.005; // currently fixed
51  std::vector<double> sums(classes.size());
52  std::vector<size_t> count(classes.size());
53 
54  bool conv = false;
55  int iter = 50;
56 
57  while( iter-- && !conv) {
58 
59  sort(classes.begin(), classes.end());
60 
61  // assign closest cluster center
62  OutputIterator ob = obegin;
63  for (InputIterator b = ibegin; b != iend; ++b, ++ob) {
64  *ob = kmeans_get_closest_clustercenter(classes,l, *b);
65  ++count[*ob];
66  sums[*ob] += *b;
67  };
68 
69  // recompute cluster centers
70  conv = true;
71  size_t max_count = 0;
72  for (size_t i = 0; i <= l; i++) {
73  if (count[i]) {
74  double a = sums[i] / count[i];
75  if (a && fabs ((a - classes[i]) / a) > convLimit)
76  conv = false;
77  classes[i] = a;
78 
79  if (max_count < count[i]) {
80  max_count = count[i];
81  biggest_class = i;
82  }
83  } else { // if a class is empty move it closer to neighbour
84  if (i == 0)
85  classes[i] = (classes[i] + classes[i + 1]) / 2.0;
86  else
87  classes[i] = (classes[i] + classes[i - 1]) / 2.0;
88  conv = false;
89  }
90  sums[i] = 0;
91  count[i] = 0;
92  };
93  };
94 
95  cvinfo()<< "kmeans: " << l + 1 << " classes, " << 50 - iter << " iterations";
96  for (size_t i = 0; i <= l; ++i )
97  cverb << std::setw(8) << classes[i]<< " ";
98  cverb << "\n";
99 
100  return conv;
101 }
102 
103 
104 template <typename InputIterator, typename OutputIterator>
105 bool kmeans_step_with_fixed_centers(InputIterator ibegin, InputIterator iend, OutputIterator obegin,
106  std::vector<double>& classes, const std::vector<bool>& fixed_center,
107  size_t l, int& biggest_class )
108 {
109  cvdebug()<< "kmeans enter: ";
110  for (size_t i = 0; i <= l; ++i )
111  cverb << std::setw(8) << classes[i]<< " ";
112  cverb << "\n";
113 
114  biggest_class = -1;
115  const double convLimit = 0.005; // currently fixed
116  std::vector<double> sums(classes.size());
117  std::vector<size_t> count(classes.size());
118 
119  bool conv = false;
120  int iter = 50;
121 
122  while( iter-- && !conv) {
123 
124  sort(classes.begin(), classes.end());
125 
126  // assign closest cluster center
127  OutputIterator ob = obegin;
128  for (InputIterator b = ibegin; b != iend; ++b, ++ob) {
129  *ob = kmeans_get_closest_clustercenter(classes,l, *b);
130  ++count[*ob];
131  sums[*ob] += *b;
132  };
133 
134  // recompute cluster centers
135  conv = true;
136  size_t max_count = 0;
137  for (size_t i = 0; i <= l; i++) {
138  if (fixed_center[i])
139  continue;
140  if (count[i]) {
141  double a = sums[i] / count[i];
142  if (a && fabs ((a - classes[i]) / a) > convLimit)
143  conv = false;
144  classes[i] = a;
145 
146  if (max_count < count[i]) {
147  max_count = count[i];
148  biggest_class = i;
149  }
150  } else { // if a class is empty move it closer to neighbour
151  if (i == 0)
152  classes[i] = (classes[i] + classes[i + 1]) / 2.0;
153  else
154  classes[i] = (classes[i] + classes[i - 1]) / 2.0;
155  conv = false;
156  }
157  sums[i] = 0;
158  count[i] = 0;
159  };
160  };
161 
162  cvinfo()<< "kmeans: " << l + 1 << " classes, " << 50 - iter << " iterations";
163  for (size_t i = 0; i <= l; ++i )
164  cverb << std::setw(8) << classes[i]<< " ";
165  cverb << "\n";
166 
167  return conv;
168 }
169 
170 
187 template <typename InputIterator, typename OutputIterator>
188 BOOST_CONCEPT_REQUIRES( ((::boost::ForwardIterator<InputIterator>))
189  ((::boost::Mutable_ForwardIterator<OutputIterator>)),
190  (void)
191  )
192  kmeans(InputIterator ibegin, InputIterator iend, OutputIterator obegin,
193  std::vector<double>& classes)
194 {
195  if (classes.size() < 2)
196  throw create_exception<std::invalid_argument>("kmeans: requested ", classes.size(),
197  "class(es), required are at least two");
198 
199  const size_t nclusters = classes.size();
200  const double size = std::distance(ibegin, iend);
201  if ( size < nclusters )
202  throw create_exception<std::invalid_argument>("kmeans: insufficient input: want ", nclusters ,
203  " classes, but git only ", size, " input elements");
204 
205  double sum = std::accumulate(ibegin, iend, 0.0);
206 
207  // simple initialization splitting at the mean
208  classes[0] = sum / (size - 1);
209  classes[1] = sum / (size + 1);
210 
211  // first run calles directly
212  int biggest_class = 0;
213 
214  // coverity is completely off here, the 1UL is actually a class index
215  // and has nothing to do with the size of the type pointed to by ibegin
216  //
217  // coverity[sizeof_mismatch]
218  kmeans_step(ibegin, iend, obegin, classes, 1, biggest_class);
219 
220  // further clustering always splits biggest class
221  for (size_t l = 2; l < nclusters; l++) {
222  const size_t pos = biggest_class > 0 ? biggest_class - 1 : biggest_class + 1;
223  classes[l] = 0.5 * (classes[biggest_class] + classes[pos]);
224  kmeans_step(ibegin, iend, obegin, classes, l, biggest_class);
225  };
226 
227  // some post iteration until centers no longer change
228  for (size_t l = 1; l < 3; l++) {
229  if (kmeans_step(ibegin, iend, obegin, classes, nclusters - 1, biggest_class))
230  break;
231  }
232 }
233 
235 
236 #endif
vstream & cvinfo()
informal output that may be of interest to understand problems with a program and are of higher prior...
Definition: msgstream.hh:252
void kmeans(InputIterator ibegin, InputIterator iend, OutputIterator obegin, std::vector< double > &classes)
Definition: kmeans.hh:192
CDebugSink & cvdebug()
Definition: msgstream.hh:216
#define cverb
define a shortcut to the raw output stream
Definition: msgstream.hh:331
#define NS_MIA_BEGIN
conveniance define to start the mia namespace
Definition: defines.hh:33
bool kmeans_step(InputIterator ibegin, InputIterator iend, OutputIterator obegin, std::vector< double > &classes, size_t l, int &biggest_class)
Definition: kmeans.hh:41
int EXPORT_CORE kmeans_get_closest_clustercenter(const std::vector< double > &classes, size_t l, double value)
double fabs(const T3DVector< T > &t)
A way to get the norm of a T3DVector using faba syntax.
Definition: 3d/vector.hh:333
static F::result_type accumulate(F &f, const B &data)
Definition: core/filter.hh:317
#define EXPORT_CORE
Macro to manage Visual C++ style dllimport/dllexport.
Definition: defines.hh:101
bool kmeans_step_with_fixed_centers(InputIterator ibegin, InputIterator iend, OutputIterator obegin, std::vector< double > &classes, const std::vector< bool > &fixed_center, size_t l, int &biggest_class)
Definition: kmeans.hh:105
#define NS_MIA_END
conveniance define to end the mia namespace
Definition: defines.hh:36