File: knnga.hpp

package info (click to toggle)
gamera 1:3.4.2+git20160808.1725654-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 22,312 kB
  • ctags: 24,991
  • sloc: xml: 122,324; ansic: 52,869; cpp: 50,664; python: 35,034; makefile: 118; sh: 101
file content (546 lines) | stat: -rw-r--r-- 19,879 bytes parent folder | download | duplicates (2)
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
/*
 * Copyright (C) 2012 Tobias Bolten
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifndef gamodule201206
#define gamodule201206

#include "knncoremodule.hpp"
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <stdexcept>
#include <cmath>
#include <limits>
#include <algorithm>
#include <sstream>
#include <time.h>
#include <map>

#ifdef _OPENMP
#include <omp.h>
#endif

#include <eo>
#include <es.h>

#include <ga/eoBitOp.h>
#include <eoStochasticUniversalSelect.h>
#include <eoShiftMutation.h>
#include <eoSwapMutation.h>
#include <eoTwoOptMutation.h>

namespace Gamera { namespace GA {

    typedef eoBit<double> SelectionIndi;
    typedef eoReal<double> WeightingIndi;

    enum OperationMode {GA_SELECTION, GA_WEIGHTING};

    template <typename EOT>
    class SelectOneDefaultWorth : public eoSelectOne<EOT> {};

    /**************************************************************************/
    template<class EOT>
    class GATwoOptMutation : public eoMonOp<EOT> {
    /**************************************************************************/
        public:
            typedef typename EOT::AtomType GeneType;

            GATwoOptMutation(){}

            virtual std::string className() const { return "GATwoOptMutation"; }

            bool operator()(EOT& _eo) {
                // generate two different indices
                unsigned int i = eo::rng.random(_eo.size());
                unsigned int j;

                do {
                    j = eo::rng.random(_eo.size());
                } while(i == j);

                unsigned int from = std::min(i,j);
                unsigned int to = std::max(i,j);
                unsigned int idx = (to - from) / 2;

                // inverse between from and to
                for(unsigned k = 0; k <= idx; ++k) {
                    GeneType tmp = _eo[from+k];
                    _eo[from+k] = _eo[to-k];
                    _eo[to-k] = tmp;
                }
                return true;
            }
    };

    /**************************************************************************/
    template<class EOT>
    class GASwapMutation : public eoMonOp<EOT> {
    /**************************************************************************/
        public:
            typedef typename EOT::AtomType GeneType;

            GASwapMutation(const unsigned _howManySwaps=1): howManySwaps(_howManySwaps) {
                if(howManySwaps < 1) {
                    throw std::runtime_error("Invalid number of swaps in GASwapMutation");
                }
            }

            virtual std::string className() const { return "GASwapMutation"; }

            bool operator()(EOT& chrom) {
                unsigned i, j;

                for(unsigned int swap = 0; swap < howManySwaps; swap++) {
                    // generate two different indices
                    i=eo::rng.random(chrom.size());

                    do {
                        j = eo::rng.random(chrom.size());
                    } while (i == j);

                    // swap
                    GeneType tmp = chrom[i];
                    chrom[i] = chrom[j];
                    chrom[j] = tmp;
              }
              return true;
            }

        private:
                unsigned int howManySwaps;
    };

    /**************************************************************************/
    template <typename EOT>
    class GAManualStop : public eoContinue<EOT> {
    /**************************************************************************/
        protected:
            bool continueFlag;

        public:
            GAManualStop() {
                this->continueFlag = true;
            }

            virtual bool operator() ( const eoPop<EOT>& _vEO ) {
                return this->continueFlag;
            }

            bool getFlag() {
                return this->continueFlag;
            }

            void setFlag(bool flag) {
                this->continueFlag = flag;
            }
    };

    /**************************************************************************/
    template <typename EOT>
    class GABestIndiStat : public eoStat<EOT, std::string> {
    /**************************************************************************/
        public:
            using eoStat<EOT, std::string>::value;

            GABestIndiStat(std::string name = "bestIndi")
            : eoStat<EOT, std::string>(std::string(""), name)
            {}

            void operator()(const eoPop<EOT> &pop) {
                const EOT bestIndi = pop.best_element();
                typename EOT::const_iterator it;

                std::ostringstream indiStream;

                indiStream << "[";
                for (it = bestIndi.begin(); it != bestIndi.end(); ++it) {
                    indiStream << *it << " , ";
                }
                indiStream << "]";

                value() = indiStream.str();
            }

            virtual std::string className(void) const { return "GABestIndiStat"; }
    };

    /**************************************************************************/
    template <typename EOT>
    class GAClassifierUpdater : public eoContinue<EOT> {
    /**************************************************************************/
        protected:
            KnnObject *knn;
            double bestFitness;
            std::vector<EOT> bestSolution;
            std::map<unsigned int, unsigned int> *indexRelation;

        public:
            GAClassifierUpdater(KnnObject *knn, std::map<unsigned int, unsigned int> *indexRelation) {
                this->knn = knn;
                this->bestFitness = 0.0;
                this->bestSolution.resize(this->knn->num_features);
                this->indexRelation = indexRelation;
            }

            double getBestFitness() {
                return this->bestFitness;
            }

            virtual bool operator()(const eoPop<EOT>& pop);

            virtual std::string className(void) const { return "GAClassifierUpdater"; }
    };

    template <>
    bool GAClassifierUpdater<WeightingIndi>::operator() (const eoPop<WeightingIndi> &pop) {
        const WeightingIndi bestIndi = pop.best_element();
        WeightingIndi::const_iterator it;

        if (bestIndi.fitness() > this->bestFitness) {
            this->bestFitness = bestIndi.fitness();

            std::fill(this->knn->weight_vector, this->knn->weight_vector + this->knn->num_features, 0.0);
            std::fill(this->bestSolution.begin(), this->bestSolution.end(), 0.0);

            for (size_t i = 0; i < bestIndi.size(); ++i) {
                this->knn->weight_vector[(*this->indexRelation)[i]] = bestIndi[i];
                this->bestSolution[(*this->indexRelation)[i]] = bestIndi[i];
            }
        }

        return true;
    }

    template <>
    bool GAClassifierUpdater<SelectionIndi>::operator() (const eoPop<SelectionIndi> &pop) {
        const SelectionIndi bestIndi = pop.best_element();
        SelectionIndi::const_iterator it;

        if (bestIndi.fitness() > this->bestFitness) {
            this->bestFitness = bestIndi.fitness();

            std::fill(this->knn->selection_vector, this->knn->selection_vector + this->knn->num_features, 0);
            std::fill(this->bestSolution.begin(), this->bestSolution.end(), false);

            for (size_t i = 0; i < bestIndi.size(); ++i) {
                this->knn->selection_vector[(*this->indexRelation)[i]] = bestIndi[i];
                this->bestSolution[(*this->indexRelation)[i]] = bestIndi[i];
            }
        }

        return true;
    }

    // *************************************************************************
    template <typename EOT>
    class GAFitnessEval : public eoEvalFunc<EOT> {
    // *************************************************************************
        protected:
            KnnObject *knn;
            std::map<unsigned int, unsigned int> *indexRelation;

            typedef typename EOT::ContainerType ContainerType;
            typedef typename EOT::AtomType AtomType;

        public:
            GAFitnessEval(KnnObject *knn, std::map<unsigned int, unsigned int> *indexRelation) {
                this->knn = knn;
                this->indexRelation = indexRelation;
            }

            virtual std::string className(void) const { return "GAFitnessEval"; }

            virtual void operator()( EOT &individual );
    };

    // specialization for weighting individual
    template <>
    void GAFitnessEval<WeightingIndi>::operator()( WeightingIndi &individual ) {
        AtomType* convertedVector = new AtomType[this->knn->num_features];
        std::fill(convertedVector, convertedVector + this->knn->num_features, 0.0);

        for (size_t i = 0; i < individual.size(); ++i) {
            convertedVector[(*this->indexRelation)[i]] = individual[i];
        }

        std::pair<int, int> looEvalRes;
        looEvalRes = leave_one_out(this->knn, std::numeric_limits<int>::max(),
                                   NULL, convertedVector, NULL);

        individual.fitness( looEvalRes.first / (double) looEvalRes.second );
        delete [] convertedVector;
    }

    // specialization for selection individual
    template <>
    void GAFitnessEval<SelectionIndi>::operator()( SelectionIndi &individual ) {
        int* convertedVector = new int[this->knn->num_features];
        std::fill(convertedVector, convertedVector + this->knn->num_features, 0);

        for (size_t i = 0; i < individual.size(); ++i) {
            // ยง4.7/4 from the C++ Standard (Integral Conversion):
            // If the source type is bool, the value false is converted to zero
            // and the value true is converted to one.
            convertedVector[(*this->indexRelation)[i]] = (int) individual[i];
        }

        std::pair<int, int> looEvalRes;
        looEvalRes = leave_one_out(this->knn, std::numeric_limits<int>::max(),
                                   convertedVector, NULL, NULL);

        individual.fitness( looEvalRes.first / (double) looEvalRes.second );
        delete [] convertedVector;
    }

    ////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////

    /**************************************************************************/
    template <typename EOT, template <typename IndiType> class EO>
    class GAMultiSettingBase {
    /**************************************************************************/
        protected:
            std::vector<EO<EOT>*> *settings;

        public:
            GAMultiSettingBase<EOT, EO>();
            ~GAMultiSettingBase<EOT, EO>();

            std::vector<EO<EOT>*> * getSettings();
    };

    /**************************************************************************/
    template <typename EOT, template <typename IndiType> class EO>
    class GASingleSettingBase {
    /**************************************************************************/
        protected:
            EO<EOT> *setting;

        public:
            GASingleSettingBase<EOT, EO>();
            ~GASingleSettingBase<EOT, EO>();

            EO<EOT> * getSetting();
    };

    /**************************************************************************/
    class GABaseSetting {
    /**************************************************************************/
        protected:
            int opMode;
            unsigned int pSize;
            double cRate;
            double mRate;

        public:
            GABaseSetting(int opMode = GA_SELECTION,
                          unsigned int pSize = 75,
                          double cRate = 0.95, double mRate = 0.05);
            // getter
            int getOpMode();
            unsigned int getPopSize();
            double getCrossRate();
            double getMutRate();

            // setter
            void setOpMode(int opMode);
            void setPopSize(unsigned int pSize);
            void setCrossRate(double cRate);
            void setMutRate(double mRate);
    };

    /**************************************************************************/
    template <typename EOT, template <typename IndiType> class EO = SelectOneDefaultWorth>
    class GASelection : public GASingleSettingBase<EOT, EO> {
    /**************************************************************************/
        public:
            void setRoulettWheel();
            void setRoulettWheelScaled(double preasure = 2.0);
            void setStochUniSampling();
            void setRankSelection(double preasure = 2.0, double exponent = 1.0);
            void setTournamentSelection(unsigned int tSize = 3);
            void setRandomSelection();
    };

    /**************************************************************************/
    template <typename EOT, template <typename IndiType> class EO = eoQuadOp>
    class GACrossover : public GAMultiSettingBase<EOT, EO> {
    /**************************************************************************/
        protected:
            eoRealVectorBounds *bound;

        public:
            GACrossover();
            ~GACrossover();

            // generic functions
            void setNPointCrossover(unsigned int n = 1);
            void setUniformCrossover(double preference = 0.5);

            // weighting functions
            void setSBXcrossover(unsigned int numFeatures, double min,
                                 double max, double eta = 1.0);
            void setSegmentCrossover(unsigned int numFeatures, double min,
                                     double max, double alpha = 0.0);
            void setHypercubeCrossover(unsigned int numFeatures, double min,
                                       double max, double alpha = 0.0);
    };
    
    /**************************************************************************/
    template <typename EOT, template <typename IndiType> class EO = eoMonOp>
    class GAMutation : public GAMultiSettingBase<EOT, EO> {
    /**************************************************************************/
        protected:
            eoRealVectorBounds *bound;

        public:
            GAMutation();
            ~GAMutation();

            void setShiftMutation();
            void setSwapMutation();
            void setInversionMutation();

            // selection functions
            void setBinaryMutation(double rate = 0.05, bool normalize = false);

            // weighting functions
            void setGaussMutation(unsigned int numFeatures, double min,
                                  double max, double sigma, double p_change = 1.0);
    };

    /**************************************************************************/
    template <typename EOT, template <typename IndiType> class EO = eoReplacement>
    class GAReplacement : public GASingleSettingBase<EOT, EO> {
    /**************************************************************************/
        public:
            void setGenerationalReplacement();
            void setSSGAworse();
            void setSSGAdetTournament(unsigned int tSize = 3);
    };
    
    /**************************************************************************/
    template <typename EOT, template <typename IndiType> class EO = eoContinue>
    class GAStopCriteria : public GAMultiSettingBase<EOT, EO> {
    /**************************************************************************/
        public:
            void setBestFitnessStop(double optimum = 1.0);
            void setMaxGenerations(unsigned int n = 100);
            void setMaxFitnessEvals(unsigned int n = 5000);
            void setSteadyStateStop(unsigned int minGens = 40, unsigned int noChangeGens = 10);
    };

    /**************************************************************************/
    class GAParallelization {
    /**************************************************************************/
        protected:
            bool parallelMode;
            unsigned int threadNum;

        public:
            GAParallelization(bool mode = true, unsigned int threads = 2);

            bool isParallel();
            void changeMode(bool mode = true);

            unsigned int getThreadNum();
            void setThreadNum(unsigned int n = 2);
    };

    /**************************************************************************/
    template <typename EOT>
    class GAOptimization {
    /**************************************************************************/
        protected:
            bool running;

            // basic GA settings
            unsigned int popSize;
            double crossoverRate;
            double mutationRate;

            KnnObject *knn;
            GABaseSetting *baseSetting;
            GASelection<EOT> *selection;
            GACrossover<EOT> *crossover;
            GAMutation<EOT> *mutation;
            GAReplacement<EOT> *replacement;
            GAStopCriteria<EOT> *stop;
            GAParallelization *parallelization;

            GAManualStop<EOT> manualStop;

            eoIncrementorParam<unsigned int> *generationCounter;
            eoBestFitnessStat<EOT> *bestStat;
            GAClassifierUpdater<EOT> *kNNUpdater;

            std::ostringstream *monitorStream;
            std::ostringstream *bestIndiStream;

        public:
            GAOptimization<EOT>(KnnObject *knn,
                           GABaseSetting *baseSetting,
                           GASelection<EOT> *selection,
                           GACrossover<EOT> *crossover,
                           GAMutation<EOT> *mutation,
                           GAReplacement<EOT> *replacement,
                           GAStopCriteria<EOT> *stop,
                           GAParallelization *parallel);
            ~GAOptimization<EOT>();

            void StartCalculation();
            void StopCalculation();

            // getter
            bool getRunStatus();

            KnnObject *getKnnObject();

            GABaseSetting * getBaseSetting();
            GASelection<EOT> * getSelection();
            GACrossover<EOT> * getCrossover();
            GAMutation<EOT> * getMutation();
            GAReplacement<EOT> * getReplacement();
            GAStopCriteria<EOT> * getStopCriteria();
            GAParallelization * getParallelization();

            unsigned int getGenerationCount();
            double getBestFitnessValue();
            std::string getMonitorString();
            std::string getBestIndiString();

            // setter
            void setKnnObject(KnnObject *knn);

            void setBaseSetting(GABaseSetting * baseSetting);
            void setSelection(GASelection<EOT> *selection);
            void setCrossover(GACrossover<EOT> *crossover);
            void setMutation(GAMutation<EOT> *mutation);
            void setReplacement(GAReplacement<EOT> *replacement);
            void setStopCriteria(GAStopCriteria<EOT> *stop);
            void setParallelization(GAParallelization *parallel);
    };

#include "knnga.cpp"

}} // end of namespaces

#endif