~ubuntu-branches/ubuntu/trusty/weka/trusty-proposed

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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
/*
 *    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., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 *    SubsetSizeForwardSelection.java
 *    Copyright (C) 2007 Martin Gütlein
 *
 */
package weka.attributeSelection;

import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.SelectedTag;
import weka.core.Tag;
import weka.core.Utils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformationHandler;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;

import java.util.BitSet;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;


/**
 <!-- globalinfo-start -->
 * SubsetSizeForwardSelection :<br/>
 * Class for performing a subset size forward selection
 * <p>
 <!-- globalinfo-end -->
 *
 <!-- options-start -->
 * Valid options are:
 * <p>
 *
 * <pre> -I
 * Perform initial ranking to select top-ranked attributes.</pre>
 *
 * <pre> -K &lt;num&gt;
 * Number of top-ranked attributes that are taken into account.</pre>
 *
 * <pre> -T &lt;0 = fixed-set | 1 = fixed-width&gt;
 * Type of Linear Forward Selection (default = 0).</pre>
 *
 * <pre> -S &lt;num&gt;
 * Size of lookup cache for evaluated subsets. Expressed as a multiple of the
 * number of attributes in the data set. (default = 1).</pre>
 *
 * <pre> -E &lt;string&gt;
 * class name of subset evaluator to use for subset size determination (default =
 * null, same subset evaluator as for ranking and final forward selection is
 * used). Place any evaluator options LAST on the command line following a "--".
 * eg. -A weka.attributeSelection.ClassifierSubsetEval ... -- -M<pre>
 *
 * <pre> -F &lt;num&gt;
 * Number of cross validation folds for subset size determination (default = 5).</pre>
 *
 * <pre> -R &lt;num&gt;
 * Seed for cross validation subset size determination. (default = 1)</pre>
 *
 * <pre> -Z
 * verbose on/off.</pre>
 *
 <!-- options-end -->
 *
 * @author Martin Guetlein (martin.guetlein@gmail.com)
 * @version $Revision: 1.1 $
 */
public class SubsetSizeForwardSelection extends ASSearch
  implements OptionHandler {
  /** search directions */
  protected static final int TYPE_FIXED_SET = 0;
  protected static final int TYPE_FIXED_WIDTH = 1;
  public static final Tag[] TAGS_TYPE = {
    new Tag(TYPE_FIXED_SET, "Fixed-set"),
    new Tag(TYPE_FIXED_WIDTH, "Fixed-width"),
  };

  // member variables
  /** perform initial ranking to select top-ranked attributes */
  protected boolean m_performRanking;

  /**
   * number of top-ranked attributes that are taken into account for the
   * search
   */
  protected int m_numUsedAttributes;

  /** 0 == fixed-set, 1 == fixed-width */
  protected int m_linearSelectionType;

  /** the subset evaluator to use for subset size determination */
  private SubsetEvaluator m_setSizeEval;

  /**
   * Number of cross validation folds for subset size determination (default =
   * 5).
   */
  protected int m_numFolds;

  /** Seed for cross validation subset size determination. (default = 1) */
  protected int m_seed;

  /** number of attributes in the data */
  protected int m_numAttribs;

  /** total number of subsets evaluated during a search */
  protected int m_totalEvals;

  /** for debugging */
  protected boolean m_verbose;

  /** holds the merit of the best subset found */
  protected double m_bestMerit;

  /** holds the maximum size of the lookup cache for evaluated subsets */
  protected int m_cacheSize;

  /**
   * Constructor
   */
  public SubsetSizeForwardSelection() {
    resetOptions();
  }

  /**
   * Returns a string describing this search method
   *
   * @return a description of the search method suitable for displaying in the
   *         explorer/experimenter gui
   */
  public String globalInfo() {
    return "SubsetSizeForwardSelection:\n\n" +
      "Extension of LinearForwardSelection. The search performs an interior " +
      "cross-validation (seed and number of folds can be specified). A " +
      "LinearForwardSelection is performed on each foldto determine the optimal " +
      "subset-size (using the given SubsetSizeEvaluator). Finally, a " +
      "LinearForwardSelection up to the optimal subset-size is performed on " +
      "the whole data.\n\n"
      + "For more information see:\n\n"
      + getTechnicalInformation().toString();
  }

  /**
   * Returns an instance of a TechnicalInformation object, containing 
   * detailed information about the technical background of this class,
   * e.g., paper reference or book this class is based on.
   * 
   * @return the technical information about this class
   */
  public TechnicalInformation getTechnicalInformation() {
    TechnicalInformation        result;
    
    result = new TechnicalInformation(Type.MASTERSTHESIS);
    result.setValue(Field.AUTHOR, "Martin Guetlein");
    result.setValue(Field.YEAR, "2006");
    result.setValue(Field.TITLE, "Large Scale Attribute Selection Using Wrappers");
    result.setValue(Field.SCHOOL, "Albert-Ludwigs-Universitat");
    result.setValue(Field.ADDRESS, "Freiburg, Germany");
    
    return result;
  }

  /**
   * Returns an enumeration describing the available options.
   *
   * @return an enumeration of all the available options.
   *
   */
  public Enumeration listOptions() {
    Vector newVector = new Vector(9);

    newVector.addElement(new Option("\tPerform initial ranking to select the" +
                                    "\n\ttop-ranked attributes.", "I", 0, "-I"));
    newVector.addElement(new Option(
                                    "\tNumber of top-ranked attributes that are " +
                                    "\n\ttaken into account by the search.", "K", 1, "-K <num>"));
    newVector.addElement(new Option(
                                    "\tType of Linear Forward Selection (default = 0).", "T", 1,
                                    "-T <0 = fixed-set | 1 = fixed-width>"));
    newVector.addElement(new Option(
                                    "\tSize of lookup cache for evaluated subsets." +
                                    "\n\tExpressed as a multiple of the number of" +
                                    "\n\tattributes in the data set. (default = 1)", "S", 1, "-S <num>"));
    newVector.addElement(new Option(
                                    "\tSubset-evaluator used for subset-size determination." + "-- -M",
                                    "E", 1, "-E <subset evaluator>"));
    newVector.addElement(new Option("\tNumber of cross validation folds" +
                                    "\n\tfor subset size determination (default = 5).", "F", 1, "-F <num>"));
    newVector.addElement(new Option("\tSeed for cross validation" +
                                    "\n\tsubset size determination. (default = 1)", "R", 1, "-R <num>"));
    newVector.addElement(new Option("\tverbose on/off", "Z", 0, "-Z"));

    if ((m_setSizeEval != null) && (m_setSizeEval instanceof OptionHandler)) {
      newVector.addElement(new Option("", "", 0,
                                      "\nOptions specific to " + "evaluator " +
                                      m_setSizeEval.getClass().getName() + ":"));

      Enumeration enu = ((OptionHandler) m_setSizeEval).listOptions();

      while (enu.hasMoreElements()) {
        newVector.addElement(enu.nextElement());
      }
    }

    return newVector.elements();
  }

  /**
   * Parses a given list of options.
   *
   * Valid options are:
   * <p>
   *
   * -I <br>
   * Perform initial ranking to select top-ranked attributes.
   * <p>
   *
   * -K <num> <br>
   * Number of top-ranked attributes that are taken into account.
   * <p>
   *
   * -T <0 = fixed-set | 1 = fixed-width> <br>
   * Typ of Linear Forward Selection (default = 0).
   * <p>
   *
   * -S <num> <br>
   * Size of lookup cache for evaluated subsets. Expressed as a multiple of
   * the number of attributes in the data set. (default = 1).
   * <p>
   *
   * -E <string> <br>
   * class name of subset evaluator to use for subset size determination
   * (default = null, same subset evaluator as for ranking and final forward
   * selection is used). Place any evaluator options LAST on the command line
   * following a "--". eg. -A weka.attributeSelection.ClassifierSubsetEval ... --
   * -M
   *
   * </pre>
   *
   * -F <num> <br>
   * Number of cross validation folds for subset size determination (default =
   * 5).
   * <p>
   *
   * -R <num> <br>
   * Seed for cross validation subset size determination. (default = 1)
   * <p>
   *
   * -Z <br>
   * verbose on/off.
   * <p>
   *
   * @param options
   *            the list of options as an array of strings
   * @exception Exception
   *                if an option is not supported
   *
   */
  public void setOptions(String[] options) throws Exception {
    String optionString;
    resetOptions();

    setPerformRanking(Utils.getFlag('I', options));

    optionString = Utils.getOption('K', options);

    if (optionString.length() != 0) {
      setNumUsedAttributes(Integer.parseInt(optionString));
    }

    optionString = Utils.getOption('T', options);

    if (optionString.length() != 0) {
      setType(new SelectedTag(Integer.parseInt(optionString), TAGS_TYPE));
    } else {
      setType(new SelectedTag(TYPE_FIXED_SET, TAGS_TYPE));
    }

    optionString = Utils.getOption('S', options);

    if (optionString.length() != 0) {
      setLookupCacheSize(Integer.parseInt(optionString));
    }

    optionString = Utils.getOption('E', options);

    if (optionString.length() == 0) {
      System.out.println(
                         "No subset size evaluator given, using evaluator that is used for final search.");
      m_setSizeEval = null;
    } else {
      setSubsetSizeEvaluator(ASEvaluation.forName(optionString,
                                                  Utils.partitionOptions(options)));
    }

    optionString = Utils.getOption('F', options);

    if (optionString.length() != 0) {
      setNumSubsetSizeCVFolds(Integer.parseInt(optionString));
    }

    optionString = Utils.getOption('R', options);

    if (optionString.length() != 0) {
      setSeed(Integer.parseInt(optionString));
    }

    m_verbose = Utils.getFlag('Z', options);
  }

  /**
   * Set the maximum size of the evaluated subset cache (hashtable). This is
   * expressed as a multiplier for the number of attributes in the data set.
   * (default = 1).
   *
   * @param size
   *            the maximum size of the hashtable
   */
  public void setLookupCacheSize(int size) {
    if (size >= 0) {
      m_cacheSize = size;
    }
  }

  /**
   * Return the maximum size of the evaluated subset cache (expressed as a
   * multiplier for the number of attributes in a data set.
   *
   * @return the maximum size of the hashtable.
   */
  public int getLookupCacheSize() {
    return m_cacheSize;
  }

  /**
   * Returns the tip text for this property
   *
   * @return tip text for this property suitable for displaying in the
   *         explorer/experimenter gui
   */
  public String lookupCacheSizeTipText() {
    return "Set the maximum size of the lookup cache of evaluated subsets. This is " +
      "expressed as a multiplier of the number of attributes in the data set. " +
      "(default = 1).";
  }

  /**
   * Returns the tip text for this property
   *
   * @return tip text for this property suitable for displaying in the
   *         explorer/experimenter gui
   */
  public String performRankingTipText() {
    return "Perform initial ranking to select top-ranked attributes.";
  }

  /**
   * Perform initial ranking to select top-ranked attributes.
   *
   * @param b
   *            true if initial ranking should be performed
   */
  public void setPerformRanking(boolean b) {
    m_performRanking = b;
  }

  /**
   * Get boolean if initial ranking should be performed to select the
   * top-ranked attributes
   *
   * @return true if initial ranking should be performed
   */
  public boolean getPerformRanking() {
    return m_performRanking;
  }

  /**
   * Returns the tip text for this property
   *
   * @return tip text for this property suitable for displaying in the
   *         explorer/experimenter gui
   */
  public String numUsedAttributesTipText() {
    return "Set the amount of top-ranked attributes that are taken into account by the search process.";
  }

  /**
   * Set the number of top-ranked attributes that taken into account by the
   * search process.
   *
   * @param k
   *            the number of attributes
   * @exception Exception
   *                if k is less than 2
   */
  public void setNumUsedAttributes(int k) throws Exception {
    if (k < 2) {
      throw new Exception("Value of -K must be >= 2.");
    }

    m_numUsedAttributes = k;
  }

  /**
   * Get the number of top-ranked attributes that taken into account by the
   * search process.
   *
   * @return the number of top-ranked attributes that taken into account
   */
  public int getNumUsedAttributes() {
    return m_numUsedAttributes;
  }

  /**
   * Returns the tip text for this property
   *
   * @return tip text for this property suitable for displaying in the
   *         explorer/experimenter gui
   */
  public String typeTipText() {
    return "Set the type of the search.";
  }

  /**
   * Set the type
   *
   * @param t
   *            the Linear Forward Selection type
   */
  public void setType(SelectedTag t) {
    if (t.getTags() == TAGS_TYPE) {
      m_linearSelectionType = t.getSelectedTag().getID();
    }
  }

  /**
   * Get the type
   *
   * @return the Linear Forward Selection type
   */
  public SelectedTag getType() {
    return new SelectedTag(m_linearSelectionType, TAGS_TYPE);
  }

  /**
   * Returns the tip text for this property
   *
   * @return tip text for this property suitable for displaying in the
   *         explorer/experimenter gui
   */
  public String subsetSizeEvaluatorTipText() {
    return "Subset evaluator to use for subset size determination.";
  }

  /**
   * Set the subset evaluator to use for subset size determination.
   *
   * @param eval
   *            the subset evaluator to use for subset size determination.
   */
  public void setSubsetSizeEvaluator(ASEvaluation eval)
    throws Exception {
    if (!SubsetEvaluator.class.isInstance(eval)) {
      throw new Exception(eval.getClass().getName() +
                          " is no subset evaluator.");
    }

    m_setSizeEval = (SubsetEvaluator) eval;
  }

  /**
   * Get the subset evaluator used for subset size determination.
   *
   * @return the evaluator used for subset size determination.
   */
  public ASEvaluation getSubsetSizeEvaluator() {
    return m_setSizeEval;
  }

  /**
   * Returns the tip text for this property
   *
   * @return tip text for this property suitable for displaying in the
   *         explorer/experimenter gui
   */
  public String numSubsetSizeCVFoldsTipText() {
    return "Number of cross validation folds for subset size determination";
  }

  /**
   * Set the number of cross validation folds for subset size determination
   * (default = 5).
   *
   * @param f
   *            number of folds
   */
  public void setNumSubsetSizeCVFolds(int f) {
    m_numFolds = f;
  }

  /**
   * Get the number of cross validation folds for subset size determination
   * (default = 5).
   *
   * @return number of folds
   */
  public int getNumSubsetSizeCVFolds() {
    return m_numFolds;
  }

  /**
   * Returns the tip text for this property
   *
   * @return tip text for this property suitable for displaying in the
   *         explorer/experimenter gui
   */
  public String seedTipText() {
    return "Seed for cross validation subset size determination. (default = 1)";
  }

  /**
   * Seed for cross validation subset size determination. (default = 1)
   *
   * @param s
   *            seed
   */
  public void setSeed(int s) {
    m_seed = s;
  }

  /**
   * Seed for cross validation subset size determination. (default = 1)
   *
   * @return seed
   */
  public int getSeed() {
    return m_seed;
  }

  /**
   * Returns the tip text for this property
   *
   * @return tip text for this property suitable for displaying in the
   *         explorer/experimenter gui
   */
  public String verboseTipText() {
    return "Turn on verbose output for monitoring the search's progress.";
  }

  /**
   * Set whether verbose output should be generated.
   *
   * @param d
   *            true if output is to be verbose.
   */
  public void setVerbose(boolean b) {
    m_verbose = b;
  }

  /**
   * Get whether output is to be verbose
   *
   * @return true if output will be verbose
   */
  public boolean getVerbose() {
    return m_verbose;
  }

  /**
   * Gets the current settings of LinearForwardSelection.
   *
   * @return an array of strings suitable for passing to setOptions()
   */
  public String[] getOptions() {
    String[] evaluatorOptions = new String[0];

    if ((m_setSizeEval != null) && (m_setSizeEval instanceof OptionHandler)) {
      evaluatorOptions = ((OptionHandler) m_setSizeEval).getOptions();
    }

    String[] options = new String[15 + evaluatorOptions.length];
    int current = 0;

    if (m_performRanking) {
      options[current++] = "-I";
    }

    options[current++] = "-K";
    options[current++] = "" + m_numUsedAttributes;
    options[current++] = "-T";
    options[current++] = "" + m_linearSelectionType;

    options[current++] = "-F";
    options[current++] = "" + m_numFolds;
    options[current++] = "-S";
    options[current++] = "" + m_seed;

    options[current++] = "-Z";
    options[current++] = "" + m_verbose;

    if (m_setSizeEval != null) {
      options[current++] = "-E";
      options[current++] = m_setSizeEval.getClass().getName();
    }

    options[current++] = "--";
    System.arraycopy(evaluatorOptions, 0, options, current,
                     evaluatorOptions.length);
    current += evaluatorOptions.length;

    while (current < options.length) {
      options[current++] = "";
    }

    return options;
  }

  /**
   * returns a description of the search as a String
   *
   * @return a description of the search
   */
  public String toString() {
    StringBuffer LFSString = new StringBuffer();

    LFSString.append("\tSubset Size Forward Selection.\n");

    LFSString.append("\tLinear Forward Selection Type: ");

    if (m_linearSelectionType == TYPE_FIXED_SET) {
      LFSString.append("fixed-set\n");
    } else {
      LFSString.append("fixed-width\n");
    }

    LFSString.append("\tNumber of top-ranked attributes that are used: " +
                     m_numUsedAttributes + "\n");

    LFSString.append(
                     "\tNumber of cross validation folds for subset size determination: " +
                     m_numFolds + "\n");
    LFSString.append("\tSeed for cross validation subset size determination: " +
                     m_seed + "\n");

    LFSString.append("\tTotal number of subsets evaluated: " + m_totalEvals +
                     "\n");
    LFSString.append("\tMerit of best subset found: " +
                     Utils.doubleToString(Math.abs(m_bestMerit), 8, 3) + "\n");

    return LFSString.toString();
  }

  /**
   * Searches the attribute subset space by subset size forward selection
   *
   * @param ASEvaluator
   *            the attribute evaluator to guide the search
   * @param data
   *            the training instances.
   * @return an array (not necessarily ordered) of selected attribute indexes
   * @exception Exception
   *                if the search can't be completed
   */
  public int[] search(ASEvaluation ASEval, Instances data)
    throws Exception {
    m_totalEvals = 0;

    if (!(ASEval instanceof SubsetEvaluator)) {
      throw new Exception(ASEval.getClass().getName() + " is not a " +
                          "Subset evaluator!");
    }

    if (m_setSizeEval == null) {
      m_setSizeEval = (SubsetEvaluator) ASEval;
    }

    m_numAttribs = data.numAttributes();

    if (m_numUsedAttributes > m_numAttribs) {
      System.out.println(
                         "Decreasing number of top-ranked attributes to total number of attributes: " +
                         data.numAttributes());
      m_numUsedAttributes = m_numAttribs;
    }

    Instances[] trainData = new Instances[m_numFolds];
    Instances[] testData = new Instances[m_numFolds];
    LFSMethods[] searchResults = new LFSMethods[m_numFolds];

    Random random = new Random(m_seed);
    Instances dataCopy = new Instances(data);
    dataCopy.randomize(random);

    if (dataCopy.classAttribute().isNominal()) {
      dataCopy.stratify(m_numFolds);
    }

    for (int f = 0; f < m_numFolds; f++) {
      trainData[f] = dataCopy.trainCV(m_numFolds, f, random);
      testData[f] = dataCopy.testCV(m_numFolds, f);
    }

    LFSMethods LSF = new LFSMethods();

    int[] ranking;

    if (m_performRanking) {
      ((SubsetEvaluator) ASEval).buildEvaluator(data);
      ranking = LSF.rankAttributes(data, (SubsetEvaluator) ASEval, m_verbose);
    } else {
      ranking = new int[m_numAttribs];

      for (int i = 0; i < ranking.length; i++) {
        ranking[i] = i;
      }
    }

    int maxSubsetSize = 0;

    for (int f = 0; f < m_numFolds; f++) {
      if (m_verbose) {
        System.out.println("perform search on internal fold: " + (f + 1) + "/" +
                           m_numFolds);
      }

      m_setSizeEval.buildEvaluator(trainData[f]);
      searchResults[f] = new LFSMethods();
      searchResults[f].forwardSearch(m_cacheSize, new BitSet(m_numAttribs),
                                     ranking, m_numUsedAttributes,
                                     m_linearSelectionType == TYPE_FIXED_WIDTH, 1, -1, trainData[f],
                                     m_setSizeEval, m_verbose);

      maxSubsetSize = Math.max(maxSubsetSize,
                               searchResults[f].getBestGroup().cardinality());
    }

    if (m_verbose) {
      System.out.println(
                         "continue searches on internal folds to maxSubsetSize (" +
                         maxSubsetSize + ")");
    }

    for (int f = 0; f < m_numFolds; f++) {
      if (m_verbose) {
        System.out.print("perform search on internal fold: " + (f + 1) + "/" +
                         m_numFolds + " with starting set ");
        LFSMethods.printGroup(searchResults[f].getBestGroup(),
                              trainData[f].numAttributes());
      }

      if (searchResults[f].getBestGroup().cardinality() < maxSubsetSize) {
        m_setSizeEval.buildEvaluator(trainData[f]);
        searchResults[f].forwardSearch(m_cacheSize,
                                       searchResults[f].getBestGroup(), ranking, m_numUsedAttributes,
                                       m_linearSelectionType == TYPE_FIXED_WIDTH, 1, maxSubsetSize,
                                       trainData[f], m_setSizeEval, m_verbose);
      }
    }

    double[][] testMerit = new double[m_numFolds][maxSubsetSize + 1];

    for (int f = 0; f < m_numFolds; f++) {
      for (int s = 1; s <= maxSubsetSize; s++) {
        if (HoldOutSubsetEvaluator.class.isInstance(m_setSizeEval)) {
          m_setSizeEval.buildEvaluator(trainData[f]);
          testMerit[f][s] = ((HoldOutSubsetEvaluator) m_setSizeEval).evaluateSubset(searchResults[f].getBestGroupOfSize(
                                                                                                                        s), testData[f]);
        } else {
          m_setSizeEval.buildEvaluator(testData[f]);
          testMerit[f][s] = m_setSizeEval.evaluateSubset(searchResults[f].getBestGroupOfSize(
                                                                                             s));
        }
      }
    }

    double[] avgTestMerit = new double[maxSubsetSize + 1];
    int finalSubsetSize = -1;

    for (int s = 1; s <= maxSubsetSize; s++) {
      for (int f = 0; f < m_numFolds; f++) {
        avgTestMerit[s] = ((avgTestMerit[s] * f) + testMerit[f][s]) / (double) (f +
                                                                                1);
      }

      if ((finalSubsetSize == -1) ||
          (avgTestMerit[s] > avgTestMerit[finalSubsetSize])) {
        finalSubsetSize = s;
      }

      if (m_verbose) {
        System.out.println("average merit for subset-size " + s + ": " +
                           avgTestMerit[s]);
      }
    }

    if (m_verbose) {
      System.out.println("performing final forward selection to subset-size: " +
                         finalSubsetSize);
    }

    ((SubsetEvaluator) ASEval).buildEvaluator(data);
    LSF.forwardSearch(m_cacheSize, new BitSet(m_numAttribs), ranking,
                      m_numUsedAttributes, m_linearSelectionType == TYPE_FIXED_WIDTH, 1,
                      finalSubsetSize, data, (SubsetEvaluator) ASEval, m_verbose);

    m_totalEvals = LSF.getNumEvalsTotal();
    m_bestMerit = LSF.getBestMerit();

    return attributeList(LSF.getBestGroup());
  }

  /**
   * Reset options to default values
   */
  protected void resetOptions() {
    m_performRanking = true;
    m_numUsedAttributes = 50;
    m_linearSelectionType = TYPE_FIXED_SET;
    m_setSizeEval = new ClassifierSubsetEval();
    m_numFolds = 5;
    m_seed = 1;
    m_totalEvals = 0;
    m_cacheSize = 1;
    m_verbose = false;
  }

  /**
   * converts a BitSet into a list of attribute indexes
   *
   * @param group
   *            the BitSet to convert
   * @return an array of attribute indexes
   */
  protected int[] attributeList(BitSet group) {
    int count = 0;

    // count how many were selected
    for (int i = 0; i < m_numAttribs; i++) {
      if (group.get(i)) {
        count++;
      }
    }

    int[] list = new int[count];
    count = 0;

    for (int i = 0; i < m_numAttribs; i++) {
      if (group.get(i)) {
        list[count++] = i;
      }
    }

    return list;
  }
}