Debian Codegraph @

plugins/core/Standard/qCanupo/include/trainer.h

raw
1 //##########################################################################
2 //# #
3 //# CLOUDCOMPARE PLUGIN: qCANUPO #
4 //# #
5 //# This program is free software; you can redistribute it and/or modify #
6 //# it under the terms of the GNU General Public License as published by #
7 //# the Free Software Foundation; version 2 or later of the License. #
8 //# #
9 //# This program is distributed in the hope that it will be useful, #
10 //# but WITHOUT ANY WARRANTY; without even the implied warranty of #
11 //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
12 //# GNU General Public License for more details. #
13 //# #
14 //# COPYRIGHT: UEB (UNIVERSITE EUROPEENNE DE BRETAGNE) / CNRS #
15 //# #
16 //##########################################################################
17
18 /** This file is directly inspired of the suggest_classifier_lda.cpp file in the
19 original CANUPO project, by N. Brodu and D. Lague.
20 **/
21
22 #ifndef QCANUPO_TRAINER_HEADER
23 #define QCANUPO_TRAINER_HEADER
24
25 //system
26 #include <vector>
27
28 //dlib
29 #include <dlib/matrix.h>
30 #include <dlib/svm.h>
31
32 class LDATrainer
33 {
34 public:
35
36 typedef dlib::matrix<float, 0, 1> sample_type;
37 typedef dlib::linear_kernel<sample_type> kernel_type;
38 typedef dlib::decision_function<kernel_type> trained_function_type;
39 //typedef trained_function_type::mem_manager_type mem_manager_type;
40
41 trained_function_type train(const std::vector<sample_type>& samplesvec, const std::vector<float>& labels) const
42 {
43 size_t fdim = samplesvec[0].size();
44 size_t nsamples = samplesvec.size();
45
46 long ndata_class1 = 0, ndata_class2 = 0;
47 for (size_t i = 0; i < nsamples; ++i)
48 {
49 if (labels[i] > 0)
50 ++ndata_class1;
51 else
52 ++ndata_class2;
53 }
54
55 dlib::matrix<sample_type, 0, 1> samples1, samples2;
56 samples1.set_size(ndata_class1);
57 samples2.set_size(ndata_class2);
58 sample_type mu1; mu1.set_size(fdim);
59 sample_type mu2; mu2.set_size(fdim);
60 for (size_t i = 0; i < fdim; ++i)
61 {
62 mu1(i) = 0;
63 mu2(i) = 0;
64 }
65
66 ndata_class1 = 0; ndata_class2 = 0;
67 for (size_t i = 0; i < nsamples; ++i)
68 {
69 if (labels[i] > 0)
70 {
71 samples1(ndata_class1) = samplesvec[i];
72 ++ndata_class1;
73 mu1 += samplesvec[i];
74 }
75 else
76 {
77 samples2(ndata_class2) = samplesvec[i];
78 ++ndata_class2;
79 mu2 += samplesvec[i];
80 }
81 }
82 if (ndata_class1 != 0)
83 {
84 mu1 /= ndata_class1;
85 }
86 if (ndata_class2 != 0)
87 {
88 mu2 /= ndata_class2;
89 }
90
91 // if you get a compilation error coming from here (with templates
92 // and a 'visual_studio_sucks_cov_helper' structure involved) then
93 // you may have to patch the dlib's file 'matrix_utilities.h":
94 //
95 // line 1611, replace
96 // const matrix<double,EXP::type::NR,EXP::type::NC, typename EXP::mem_manager_type> avg = mean(m);
97 // by
98 // const typename EXP::type avg = mean(m);
99 //
100 dlib::matrix<float> sigma1 = covariance(samples1);
101 dlib::matrix<float> sigma2 = covariance(samples2);
102
103 sample_type w_vect = pinv(sigma1 + sigma2) * (mu2 - mu1);
104
105 trained_function_type ret;
106 //ret.alpha.set_size(fdim);
107 //for (int i=0; i<fdim; ++i) ret.alpha(i) = w_vect(i);
108 ret.alpha = w_vect;
109 ret.b = dot(w_vect, (mu1 + mu2)*0.5);
110 // linear kernel idiocy
111 ret.basis_vectors.set_size(fdim);
112 for (size_t i = 0; i < fdim; ++i)
113 {
114 ret.basis_vectors(i).set_size(fdim);
115 for (size_t j = 0; j < fdim; ++j)
116 ret.basis_vectors(i)(j) = 0;
117 ret.basis_vectors(i)(i) = 1;
118 }
119 return ret;
120 }
121
122 #if 0
123 trained_function_type train(const trained_function_type::sample_vector_type& samplesvec, const trained_function_type::scalar_vector_type& labels) const
124 {
125 int fdim = samplesvec(0).size();
126 int nsamples = samplesvec.size();
127
128 int ndata_class1 = 0, ndata_class2 = 0;
129 for (int i=0; i<nsamples; ++i)
130 {
131 if (labels(i)>0)
132 ++ndata_class1;
133 else
134 ++ndata_class2;
135 }
136
137 dlib::matrix<sample_type,0,1> samples1, samples2;
138 samples1.set_size(ndata_class1);
139 samples2.set_size(ndata_class2);
140 sample_type mu1; mu1.set_size(fdim);
141 sample_type mu2; mu2.set_size(fdim);
142 for (int i=0; i<fdim; ++i)
143 {
144 mu1(i)=0;
145 mu2(i)=0;
146 }
147
148 ndata_class1 = 0; ndata_class2 = 0;
149 for (int i=0; i<nsamples; ++i)
150 {
151 if (labels(i)>0)
152 {
153 samples1(ndata_class1) = samplesvec(i);
154 ++ndata_class1;
155 mu1 += samplesvec(i);
156 }
157 else
158 {
159 samples2(ndata_class2) = samplesvec(i);
160 ++ndata_class2;
161 mu2 += samplesvec(i);
162 }
163 }
164 mu1 /= ndata_class1;
165 mu2 /= ndata_class2;
166
167 // if you get a compilation error coming from here (with templates
168 // and a 'visual_studio_sucks_cov_helper' structure involved) then
169 // you may have to patch the dlib's file 'matrix_utilities.h":
170 //
171 // line 1611, replace
172 // const matrix<double,EXP::type::NR,EXP::type::NC, typename EXP::mem_manager_type> avg = mean(m);
173 // by
174 // const typename EXP::type avg = mean(m);
175 //
176 dlib::matrix<float> sigma1 = covariance(samples1);
177 dlib::matrix<float> sigma2 = covariance(samples2);
178
179 sample_type w_vect = pinv(sigma1+sigma2) * (mu2 - mu1);
180
181 trained_function_type ret;
182 //ret.alpha.set_size(fdim);
183 //for (int i=0; i<fdim; ++i) ret.alpha(i) = w_vect(i);
184 ret.alpha = w_vect;
185 ret.b = dot(w_vect,(mu1+mu2)*0.5);
186 // linear kernel idiocy
187 ret.basis_vectors.set_size(fdim);
188 for (int i=0; i<fdim; ++i)
189 {
190 ret.basis_vectors(i).set_size(fdim);
191 for (int j=0; j<fdim; ++j)
192 ret.basis_vectors(i)(j)=0;
193 ret.basis_vectors(i)(i) = 1;
194 }
195 return ret;
196 /*LinearPredictor classifier;
197 classifier.weights.resize(fdim+1);
198 for (int i=0; i<fdim; ++i) classifier.weights[i] = w_vect(i);
199 classifier.weights[fdim] = -dot(w_vect,(mu1+mu2)*0.5);
200 return classifier;*/
201 }
202 #endif
203
204 void train(int nfolds, const std::vector<sample_type>& samples, const std::vector<float>& labels)
205 {
206 dlib::probabilistic_decision_function<kernel_type> pdecfun = dlib::train_probabilistic_decision_function(*this, samples, labels, nfolds);
207 dlib::decision_function<kernel_type>& decfun = pdecfun.decision_funct;
208 int dim = samples.back().size();
209 // see comments in linearSVM.hpp
210 m_weights.clear();
211 m_weights.resize(dim + 1, 0);
212 dlib::matrix<float> w(dim, 1);
213 w = 0;
214 for (int i = 0; i < decfun.alpha.nr(); ++i)
215 {
216 w += decfun.alpha(i) * decfun.basis_vectors(i);
217 }
218 for (int i = 0; i < dim; ++i)
219 m_weights[i] = w(i);
220 m_weights[dim] = -decfun.b;
221 for (int i = 0; i <= dim; ++i)
222 m_weights[i] *= pdecfun.alpha;
223 m_weights[dim] += pdecfun.beta;
224
225 // TODO: check if necessary here
226 for (int i = 0; i <= dim; ++i)
227 m_weights[i] = -m_weights[i];
228 }
229
230 double predict(const sample_type& data) const
231 {
232 assert(!m_weights.empty());
233 double ret = m_weights.back();
234 for (size_t d = 0; d < m_weights.size() - 1; ++d)
235 ret += static_cast<double>(m_weights[d]) * data(d);
236 return ret;
237 }
238
239 //! Classifier weights
240 std::vector<float> m_weights;
241
242 };
243
244 //! Gram-Schmidt process to re-orthonormalise the basis
245 static void GramSchmidt(dlib::matrix<LDATrainer::sample_type,0,1>& basis, LDATrainer::sample_type& newX)
246 {
247 // goal: find a basis so that the given vector is the new X
248 // principle: at least one basis vector is not orthogonal with newX (except if newX is null but we suppose this is not the case)
249 // => use the max dot product vector, and replace it by newX. this forms a set of
250 // linearly independent vectors.
251 // then apply the Gram-Schmidt process
252 long dim = basis.size();
253 double maxabsdp = -1.0;
254 long selectedCoord = 0;
255 for (long i = 0; i < dim; ++i)
256 {
257 double absdp = std::abs(dot(basis(i), newX));
258 if (absdp > maxabsdp)
259 {
260 absdp = maxabsdp;
261 selectedCoord = i;
262 }
263 }
264 // swap basis vectors to use the selected coord as the X vector, then replaced by newX
265 basis(selectedCoord) = basis(0);
266 basis(0) = newX;
267 // Gram-Schmidt process to re-orthonormalise the basis.
268 // Thanks Wikipedia for the stabilized version
269 for (long j = 0; j < dim; ++j)
270 {
271 for (long i = 0; i < j; ++i)
272 basis(j) -= (dot(basis(j), basis(i)) / dot(basis(i), basis(i))) * basis(i);
273
274 basis(j) /= sqrt(dot(basis(j), basis(j)));
275 }
276 }
277
278 //! Compute pos. and neg. reference points
279 static void ComputeReferencePoints( Classifier::Point2D& refpt_pos,
280 Classifier::Point2D& refpt_neg,
281 const std::vector<float>& proj1,
282 const std::vector<float>& proj2,
283 const std::vector<float>& labels,
284 unsigned* _npos = 0,
285 unsigned* _nneg = 0)
286 {
287 assert(proj1.size() == proj2.size() && proj1.size() == labels.size());
288
289 refpt_neg = refpt_pos = Classifier::Point2D(0, 0);
290
291 size_t npos = 0;
292 size_t nneg = 0;
293 for (size_t i = 0; i < labels.size(); ++i)
294 {
295 if (labels[i] < 0)
296 {
297 refpt_neg += Classifier::Point2D(proj1[i], proj2[i]);
298 ++nneg;
299 }
300 else
301 {
302 refpt_pos += Classifier::Point2D(proj1[i], proj2[i]);
303 ++npos;
304 }
305 }
306 if (npos)
307 refpt_pos /= static_cast<PointCoordinateType>(npos);
308 if (nneg)
309 refpt_neg /= static_cast<PointCoordinateType>(nneg);
310
311 if (_npos)
312 *_npos = npos;
313 if (_nneg)
314 *_nneg = nneg;
315 }
316
317 //! Experimental (same as Brodu's code): dilatation to highlight the internal data structure
318 static bool DilateClassifier( Classifier& classifier,
319 std::vector<float>& proj1,
320 std::vector<float>& proj2,
321 const std::vector<float>& labels,
322 const std::vector<LDATrainer::sample_type>& samples,
323 LDATrainer& trainer,
324 LDATrainer& orthoTrainer)
325 {
326 //m_app->dispToConsole("[Cloud dilatation]");
327 Classifier::Point2D e1 = classifier.refPointPos - classifier.refPointNeg;
328 e1.normalize();
329 Classifier::Point2D e2(-e1.y, e1.x);
330 Classifier::Point2D ori = (classifier.refPointPos + classifier.refPointNeg) / 2;
331
332 float m11 = 0, m21 = 0, m12 = 0, m22 = 0; // m12, m22 null by construction
333 float v11 = 0, v12 = 0, v21 = 0, v22 = 0;
334 size_t nsamples1 = 0;
335 size_t nsamples2 = 0;
336 size_t nsamples = proj1.size();
337 assert(proj1.size() == proj2.size());
338 for (size_t i = 0; i < nsamples; ++i)
339 {
340 Classifier::Point2D p(proj1[i], proj2[i]);
341 p -= ori;
342 float p1 = p.dot(e1);
343 float p2 = p.dot(e2);
344 if (labels[i] < 0)
345 {
346 m11 += p1; v11 += p1 * p1;
347 m12 += p2; v12 += p2 * p2;
348 ++nsamples1;
349 }
350 else
351 {
352 m21 += p1; v21 += p1 * p1;
353 m22 += p2; v22 += p2 * p2;
354 ++nsamples2;
355 }
356 }
357
358 if (nsamples1 < 2 || nsamples2 < 2)
359 {
360 assert(false);
361 return false;
362 }
363
364 m11 /= nsamples1;
365 v11 = (v11 - m11 * m11*nsamples1) / (nsamples1 - 1);
366 m21 /= nsamples2;
367 v21 = (v21 - m21 * m21*nsamples2) / (nsamples2 - 1);
368 m12 /= nsamples1;
369 v12 = (v12 - m12 * m12*nsamples1) / (nsamples1 - 1);
370 m22 /= nsamples2;
371 v22 = (v22 - m22 * m22*nsamples2) / (nsamples2 - 1);
372
373 float d1 = sqrt(v11 / v12);
374 float d2 = sqrt(v21 / v22);
375 classifier.axisScaleRatio = sqrt(d1*d2);
376
377 float bdValues[4] { e1.x, e1.y, e2.x / classifier.axisScaleRatio, e2.y / classifier.axisScaleRatio };
378 dlib::matrix<float, 2, 2> bd(bdValues);
379
380 float biValues[4] { e1.x, e2.x, e1.y, e2.y };
381 dlib::matrix<float, 2, 2> bi(biValues);
382 dlib::matrix<float, 2, 2> c = inv(trans(bd)) /* bi * bd */;
383
384 std::vector<float>& w1 = trainer.m_weights;
385 std::vector<float>& w2 = orthoTrainer.m_weights;
386 assert(w1.size() == w2.size());
387
388 std::vector<float> wn1, wn2;
389 try
390 {
391 wn1.resize(w1.size());
392 wn2.resize(w2.size());
393 }
394 catch (const std::bad_alloc&)
395 {
396 //not enough memory
397 return false;
398 }
399
400 // first shift so the center of the figure is at the midpoint
401 w1.back() -= ori.x;
402 w2.back() -= ori.y;
403 // now transform / scale along e2
404 {
405 for (size_t i = 0; i < w1.size(); ++i)
406 {
407 wn1[i] = c(0, 0) * w1[i] + c(0, 1) * w2[i];
408 wn2[i] = c(1, 0) * w1[i] + c(1, 1) * w2[i];
409 }
410 }
411
412 trainer.m_weights = wn1;
413 orthoTrainer.m_weights = wn2;
414
415 // reset projections
416 {
417 for (size_t i = 0; i < nsamples; ++i)
418 {
419 proj1[i] = trainer.predict(samples[i]);
420 proj2[i] = orthoTrainer.predict(samples[i]);
421 }
422 }
423
424 classifier.weightsAxis1 = wn1;
425 classifier.weightsAxis2 = wn2;
426
427 //update reference points
428 ComputeReferencePoints( classifier.refPointPos,
429 classifier.refPointNeg,
430 proj1,
431 proj2,
432 labels);
433
434 return true;
435 }
436
437 #endif //QCANUPO_CLASSIFIER_HEADER