KSquare Utilities
TrainingConfiguration2.cpp
Go to the documentation of this file.
1 #include "FirstIncludes.h"
2 #include <stdio.h>
3 #include <fstream>
4 #include <iostream>
5 #include <map>
6 #include <string>
7 #include <vector>
8 #include "MemoryDebug.h"
9 using namespace std;
10 
11 #include "GlobalGoalKeeper.h"
12 #include "KKBaseTypes.h"
13 #include "KKException.h"
14 #include "OSservices.h"
15 #include "RunLog.h"
16 using namespace KKB;
17 
19 #include "BinaryClassParms.h"
20 #include "FactoryFVProducer.h"
21 #include "FeatureFileIO.h"
22 #include "FeatureNumList.h"
23 #include "FeatureVector.h"
24 #include "FileDesc.h"
26 #include "MLClass.h"
27 #include "KKMLVariables.h"
28 #include "Model.h"
29 #include "ModelParamDual.h"
30 #include "ModelParamKnn.h"
31 #include "ModelParamOldSVM.h"
32 #include "ModelParamSvmBase.h"
35 using namespace KKMLL;
36 
37 
38 
39 void TrainingConfiguration2::CreateModelParameters (const KKStr& _parameterStr,
40  const FeatureNumList& _selFeatures,
41  kkint32 _sectionLineNum,
42  kkint32 _parametersLineNum,
43  kkint32 _featuresIncludedLineNum,
44  RunLog& _log
45  )
46 {
47  delete modelParameters;
48  modelParameters = NULL;
49 
50  if (_parametersLineNum < 0)
51  {
52  KKStr errMsg = "'Parameters' setting was not specified.";
53  _log.Level (-1) << endl << endl << "CreateModelParameters ***ERROR*** " << errMsg << endl << endl;
54  FormatErrorsAdd (_sectionLineNum, errMsg);
55  FormatGood (false);
56  }
57 
58  switch (modelingMethod)
59  {
60  case Model::ModelTypes::Dual: modelParameters = new ModelParamDual (); break;
61  case Model::ModelTypes::KNN: modelParameters = new ModelParamKnn (); break;
62  case Model::ModelTypes::OldSVM: modelParameters = new ModelParamOldSVM (); break;
63  case Model::ModelTypes::SvmBase: modelParameters = new ModelParamSvmBase (); break;
64  case Model::ModelTypes::UsfCasCor: modelParameters = new ModelParamUsfCasCor (); break;
65 
66  default:
67  _log.Level (-1) << endl << endl
68  << "TrainingConfiguration2::CreateModelParameters ***ERROR*** Invalid modeling method["
69  << Model::ModelTypeToStr (modelingMethod) << "] selected at this time." << endl
70  << endl;
71  break;
72  }
73 
74  if (modelParameters)
75  {
76  bool validParameterFormat = false;
77  // We apply '_selFeatures' first; this way if features were specified in '_parameterStr' they
78  // will override what '_selFeatures'. This is important because quite often the caller does
79  // not know the features so they assume all.
80  modelParameters->SelectedFeatures (_selFeatures);
81  modelParameters->ParseCmdLine (_parameterStr, validParameterFormat, _log);
82 
83  if (!modelParameters->ValidParam ())
84  {
85  KKStr errMsg = "Parameter setting is invalid";
86  _log.Level (-1) << endl
87  << "TrainingConfiguration2::CreateModelParameters ***ERROR*** " << errMsg << endl
88  << endl;
89  FormatErrorsAdd (_parametersLineNum, errMsg);
90  FormatGood (false);
91  }
92 
93  else if (_featuresIncludedLineNum > 0)
94  {
95  modelParameters->SelectedFeatures (_selFeatures);
96  }
97  }
98 } /* CreateModelParameters */
99 
100 
101 
104 
105  configFileNameSpecified (),
106  configRootName (),
107  fileDesc (NULL),
108  fvFactoryProducer (NULL),
109  fvFactoryProducerSpecified (false),
110  mlClasses (NULL),
111  mlClassesWeOwnIt (false),
112  modelingMethod (Model::ModelTypes::Null),
113  examplesPerClass (0),
114  modelParameters (NULL),
115  noiseMLClass (NULL),
116  noiseTrainingClass (NULL),
117  otherClass (NULL),
118  otherClassLineNum (-1),
119  rootDir (),
120  rootDirExpanded (),
121  subClassifiers (NULL),
122  subClassifierNameList (NULL),
123  trainingClasses ("", true),
124  validateDirectories (true)
125 {
126 }
127 
128 
129 
130 void TrainingConfiguration2::Load (const KKStr& _configFileName,
131  bool _validateDirectories,
132  RunLog& log
133  )
134 {
135  KKStr effectiveConfigName = GetEffectiveConfigFileName (_configFileName);
136 
137  Configuration::Load (effectiveConfigName, log);
138 
139  configFileNameSpecified = _configFileName;
140  configRootName = KKB::osGetRootName (_configFileName);
141  validateDirectories = _validateDirectories;
142  if (!FormatGood ())
143  {
144  log.Level (-1) << endl
145  << "TrainingConfiguration2 ***ERROR*** Format of Configuration File is Invalid." << endl
146  << endl;
147  return;
148  }
149 
150  mlClasses = new MLClassList ();
151  mlClassesWeOwnIt = true;
152 
153  ValidateConfiguration (log);
154  if (examplesPerClass < 1)
155  {
156  log.Level (10) << "TrainingConfiguration2 - examplesPerClass not specified. Defaulting to 1300." << endl;
157  examplesPerClass = 1300;
158  }
159 
160  if (!FormatGood ())
161  log.Level (-1) << endl
162  << "TrainingConfiguration2 ***ERROR*** Format of Configuration File is Invalid." << endl
163  << endl;
164 
165  else if (rootDir.Empty ())
166  DetermineWhatTheRootDirectoryIs ();
167 
168 } /* Load */
169 
170 
171 
173  FactoryFVProducerPtr _fvFactoryProducer,
174  const KKStr& _parameterStr,
175  RunLog& _log
176  ):
178  configFileNameSpecified (""),
179  configRootName (),
180  fileDesc (NULL),
181  fvFactoryProducer (_fvFactoryProducer),
182  fvFactoryProducerSpecified (true),
183  modelingMethod (Model::ModelTypes::Null),
184  mlClasses (NULL),
185  mlClassesWeOwnIt (false),
186  examplesPerClass (0),
187  modelParameters (NULL),
188  noiseMLClass (NULL),
189  noiseTrainingClass (NULL),
190  otherClass (NULL),
191  otherClassLineNum (-1),
192  rootDir (),
193  rootDirExpanded (),
194  subClassifiers (NULL),
195  subClassifierNameList (NULL),
196  trainingClasses ("", true),
197  validateDirectories (false)
198 {
199  if (!fvFactoryProducer)
200  fvFactoryProducer = DefaultFeatureVectorProducer (_log);
201  fileDesc = fvFactoryProducer->FileDesc ();
202 
203  if (_mlClasses)
204  mlClasses = new MLClassList (*_mlClasses);
205  else
206  mlClasses = new MLClassList ();
207 
208  mlClassesWeOwnIt = true;
209 
210  {
211  MLClassList::iterator idx;
212  for (idx = mlClasses->begin (); idx != mlClasses->end (); idx++)
213  {
214  MLClassPtr mlClass = *idx;
215  VectorKKStr directories;
216  TrainingClassPtr tc = new TrainingClass (directories, mlClass->Name (), 1.0f, 1.0f, NULL, *mlClasses);
217  trainingClasses.PushOnBack (tc);
218  }
219  }
220 
221  if (modelingMethod == Model::ModelTypes::Null)
222  modelingMethod = Model::ModelTypes::OldSVM;
223 
224  {
225  examplesPerClass = int32_max;
226  FeatureNumList selectedFeatures (fileDesc);
227  selectedFeatures.SetAllFeatures (fileDesc);
228  CreateModelParameters (_parameterStr, selectedFeatures, 1, 1, 1, _log);
229  if (!modelParameters || (!modelParameters->ValidParam ()))
230  {
231  _log.Level (-1) << endl
232  << "TrainingConfiguration2 ***ERROR*** Invalid Parameters." << endl
233  << " Parameters[" << _parameterStr << "]" << endl
234  << endl;
235  FormatGood (false);
236  }
237  }
238 }
239 
240 
241 
243  FileDescPtr _fileDesc,
244  const KKStr& _parameterStr,
245  RunLog& _log
246  ):
248  configFileNameSpecified (""),
249  configRootName (),
250  fileDesc (_fileDesc),
251  fvFactoryProducer (NULL),
252  fvFactoryProducerSpecified (false),
253  mlClasses (NULL),
254  mlClassesWeOwnIt (false),
255  modelingMethod (Model::ModelTypes::Null),
256  examplesPerClass (0),
257  modelParameters (NULL),
258  noiseMLClass (NULL),
259  noiseTrainingClass (NULL),
260  otherClass (NULL),
261  otherClassLineNum (-1),
262  rootDir (),
263  rootDirExpanded (),
264  subClassifiers (NULL),
265  subClassifierNameList (NULL),
266  trainingClasses ("", true),
267  validateDirectories (false)
268 {
269  if (_mlClasses)
270  mlClasses = new MLClassList (*_mlClasses);
271  else
272  mlClasses = new MLClassList ();
273 
274  mlClassesWeOwnIt = true;
275 
276  {
277  MLClassList::iterator idx;
278  for (idx = mlClasses->begin (); idx != mlClasses->end (); idx++)
279  {
280  MLClassPtr mlClass = *idx;
281  VectorKKStr directories;
282  TrainingClassPtr tc = new TrainingClass (directories, mlClass->Name (), 1.0f, 1.0f, NULL, *mlClasses);
283  trainingClasses.PushOnBack (tc);
284  }
285  }
286 
287  if (modelingMethod == Model::ModelTypes::Null)
288  modelingMethod = Model::ModelTypes::OldSVM;
289 
290  {
291  examplesPerClass = int32_max;
292  FeatureNumList selectedFeatures (fileDesc);
293  selectedFeatures.SetAllFeatures (fileDesc);
294  CreateModelParameters (_parameterStr, selectedFeatures, 1, 1, 1, _log);
295  if (!modelParameters || (!modelParameters->ValidParam ()))
296  {
297  _log.Level (-1) << endl
298  << "TrainingConfiguration2 ***ERROR*** Invalid Parameters." << endl
299  << " Parameters[" << _parameterStr << "]" << endl
300  << endl;
301  FormatGood (false);
302  }
303  }
304 }
305 
306 
307 
309  FileDescPtr _fileDesc,
310  ModelParamPtr _modelParameters,
311  RunLog& _log
312  ):
314  configFileNameSpecified (""),
315  configRootName (""),
316  fileDesc (_fileDesc),
317  fvFactoryProducer (NULL),
318  fvFactoryProducerSpecified (false),
319  mlClasses (NULL),
320  mlClassesWeOwnIt (false),
321  modelingMethod (Model::ModelTypes::Null),
322  examplesPerClass (0),
323  modelParameters (_modelParameters),
324  noiseMLClass (NULL),
325  noiseTrainingClass (NULL),
326  otherClass (NULL),
327  otherClassLineNum (-1),
328  rootDir (),
329  rootDirExpanded (),
330  subClassifiers (NULL),
331  subClassifierNameList (NULL),
332  trainingClasses ("", true),
333  validateDirectories (false)
334 {
335  if (_mlClasses)
336  mlClasses = new MLClassList (*_mlClasses);
337  else
338  mlClasses = new MLClassList ();
339  mlClassesWeOwnIt = true;
340 
341  {
342  MLClassList::iterator idx;
343  for (idx = mlClasses->begin (); idx != mlClasses->end (); idx++)
344  {
345  MLClassPtr mlClass = *idx;
346  VectorKKStr directories;
347  TrainingClassPtr tc = new TrainingClass (directories, mlClass->Name (), 1.0f, 1.0f, NULL, *mlClasses);
348  trainingClasses.PushOnBack (tc);
349  }
350  }
351 
352  switch (_modelParameters->ModelParamType ())
353  {
354  case ModelParam::ModelParamTypes::Dual: modelingMethod = Model::ModelTypes::Dual; break;
355  case ModelParam::ModelParamTypes::KNN: modelingMethod = Model::ModelTypes::KNN; break;
359  }
360 }
361 
362 
363 
365  Configuration (tc),
366  configFileNameSpecified (tc.configFileNameSpecified),
367  configRootName (tc.configRootName),
368  fileDesc (tc.fileDesc),
369  fvFactoryProducer (tc.fvFactoryProducer),
370  fvFactoryProducerSpecified (tc.fvFactoryProducerSpecified),
371  mlClasses (NULL),
372  mlClassesWeOwnIt (false),
373  modelingMethod (tc.modelingMethod),
374  examplesPerClass (tc.examplesPerClass),
375  modelParameters (NULL),
376  noiseMLClass (tc.noiseMLClass),
377  noiseTrainingClass (tc.noiseTrainingClass),
378  otherClass (tc.otherClass),
379  otherClassLineNum (tc.otherClassLineNum),
380  rootDir (tc.rootDir),
381  rootDirExpanded (tc.rootDirExpanded),
382  subClassifiers (NULL),
383  subClassifierNameList (NULL),
384  trainingClasses (tc.rootDir, true),
385  validateDirectories (tc.validateDirectories)
386 {
387  {
388  kkint32 x;
389 
390  for (x = 0; x < tc.trainingClasses.QueueSize (); x++)
391  {
392  TrainingClassPtr trainingClass = tc.trainingClasses.IdxToPtr (x);
393  trainingClasses.PushOnBack (new TrainingClass (*trainingClass));
394  }
395  }
396 
397  if (tc.mlClasses)
398  {
399  mlClasses = new MLClassList (*tc.mlClasses);
400  mlClassesWeOwnIt = true;
401  }
402 
403  if (tc.modelParameters)
404  modelParameters = tc.modelParameters->Duplicate ();
405 
406  if (tc.subClassifiers)
407  {
408  subClassifiers = new TrainingConfiguration2List (true);
409  TrainingConfiguration2List::const_iterator idx;
410  for (idx = tc.subClassifiers->begin (); idx != tc.subClassifiers->end (); ++idx)
411  {
412  TrainingConfiguration2Ptr subClassifier = *idx;
413  subClassifiers->PushOnBack (new TrainingConfiguration2 (*subClassifier));
414  }
415  }
416 }
417 
418 
419 
421 {
422  delete noiseTrainingClass; noiseTrainingClass = NULL;
423  delete modelParameters; modelParameters = NULL;
424  delete subClassifierNameList; subClassifierNameList = NULL;
425  delete subClassifiers; subClassifiers = NULL;
426 
427  if (mlClassesWeOwnIt)
428  {
429  delete mlClasses;
430  mlClasses = NULL;
431  }
432 }
433 
434 
435 
436 TrainingConfiguration2Ptr TrainingConfiguration2::Duplicate () const
437 {
438  return new TrainingConfiguration2 (*this);
439 }
440 
441 
442 
443 FactoryFVProducerPtr TrainingConfiguration2::FvFactoryProducer (RunLog& log) const
444 {
445  if (!fvFactoryProducerSpecified)
447  else
448  return fvFactoryProducer;
449 }
450 
451 
452 FactoryFVProducerPtr TrainingConfiguration2::DefaultFeatureVectorProducer (RunLog& runLog) const
453 {
455 }
456 
457 
458 
459 ModelParamOldSVMPtr TrainingConfiguration2::OldSvmParameters () const
460 {
461  if (modelParameters && (modelingMethod == Model::ModelTypes::OldSVM))
462  return dynamic_cast<ModelParamOldSVMPtr>(modelParameters);
463  else
464  return NULL;
465 }
466 
467 
468 
470 {
471  return rootDirExpanded;
472 }
473 
474 
475 
477 {
478  TrainingClassList::const_iterator idx;
479  for (idx = trainingClasses.begin (); idx != trainingClasses.end (); idx++)
480  {
481  const TrainingClassPtr tc = *idx;
482  if (tc->MLClass () == mlClass)
483  return tc->ExpandedDirectory (rootDir, 0);
484  }
485 
486  return KKStr::EmptyStr ();
487 } /* DirectoryPathForClass */
488 
489 
490 
492 {
493  TrainingClassList::const_iterator idx;
494 
495  kkuint16 numHierarchialLevels = 0;
496 
497  for (idx = trainingClasses.begin (); idx != trainingClasses.end (); idx++)
498  {
499  TrainingClassPtr tc = *idx;
500  numHierarchialLevels = Max (numHierarchialLevels, tc->MLClass ()->NumHierarchialLevels ());
501  }
502 
503  return numHierarchialLevels;
504 } /* NumHierarchialLevels */
505 
506 
507 
508 void TrainingConfiguration2::SyncronizeMLClassListWithTrainingClassList ()
509 {
510  if (mlClassesWeOwnIt)
511  {
512  delete mlClasses;
513  mlClasses = NULL;
514  }
515 
516  mlClasses = new MLClassList ();
517  mlClassesWeOwnIt = true;
518  TrainingClassList::const_iterator idx;
519 
520  for (idx = trainingClasses.begin (); idx != trainingClasses.end (); idx++)
521  {
522  MLClassPtr ic = (*idx)->MLClass ();
523  if (mlClasses->PtrToIdx (ic) < 0)
524  mlClasses->AddMLClass (ic);
525  }
526 } /* SyncronizeMLClassListWithTrainingClassList */
527 
528 
529 
531 {
532  MLClassListPtr classes = new MLClassList ();
533  TrainingClassList::const_iterator idx;
534 
535  for (idx = trainingClasses.begin (); idx != trainingClasses.end (); idx++)
536  {
537  MLClassPtr ic = (*idx)->MLClass ();
538  MLClassPtr claassForGivenLevel = ic->MLClassForGivenHierarchialLevel (level);
539  if (classes->PtrToIdx (claassForGivenLevel) < 0)
540  classes->AddMLClass (claassForGivenLevel);
541  }
542 
543  return classes;
544 } /* ExtractListOfClassesForAGivenHierarchialLevel */
545 
546 
547 
549  RunLog& log
550  ) const
551 {
552  log.Level (10) << "TrainingConfiguration2::GenerateAConfiguraionForAHierarchialLevel level[" << level << "]" << endl;
553  TrainingConfiguration2Ptr hierarchialConfig = new TrainingConfiguration2 (*this);
554  hierarchialConfig->EmptyTrainingClasses ();
555 
557 
558  TrainingClassList::const_iterator idx;
559 
560  for (idx = trainingClasses.begin (); idx != trainingClasses.end (); idx++)
561  {
562  const TrainingClassPtr tc = *idx;
564  hierarchialConfig->AddATrainingClass (new TrainingClass (tc->Directories (), ic->Name (), 1.0f, 1.0f, NULL, *hierarchialClassList));
565  }
566 
567  hierarchialConfig->SyncronizeMLClassListWithTrainingClassList ();
568 
569  delete hierarchialClassList;
570  return hierarchialConfig;
571 } /* GenerateAConfiguraionForAHierarchialLevel */
572 
573 
574 
575 void TrainingConfiguration2::Save (ostream& o) const
576 {
577  {
578  // Global Section
579  o << "[Global]" << endl
580  << "MODELING_METHOD = " << ModelTypeToStr (modelingMethod) << endl
581  << "ROOT_DIR = " << rootDir << endl
582  << "Parameters=" << modelParameters->ToCmdLineStr () << endl;
583 
584  if (examplesPerClass > 0)
585  o << "Examples_Per_Class=" << examplesPerClass << endl;
586 
587  if (modelParameters->SelectedFeatures ())
588  o << "Features_Included=" << modelParameters->SelectedFeatures ()->ToString () << endl;
589 
590  if (otherClass != NULL)
591  o << "OtherClass=" << otherClass->Name () << endl;
592  o << endl;
593  }
594 
595  if (noiseTrainingClass)
596  {
597  o << "[NOISE_IMAGES]" << endl;
598  o << "Class_Name=" << noiseTrainingClass->Name () << endl;
599  for (kkuint32 zed = 0; zed < noiseTrainingClass->DirectoryCount (); ++zed)
600  o << "Dir=" << noiseTrainingClass->Directory (zed) << endl;
601 
602  o << endl;
603  }
604 
605  TrainingClassList::const_iterator tcIDX;
606  for (tcIDX = trainingClasses.begin (); tcIDX != trainingClasses.end (); tcIDX++)
607  {
608  TrainingClassPtr tc = *tcIDX;
609 
610  o << "[TRAINING_CLASS]" << endl;
611 
612  o << "Class_Name=" << tc->Name () << endl;
613  if (tc->Weight () != 1.0f)
614  o << "Weight=" << tc->Weight () << endl;
615 
616  if (tc->CountFactor () > 0.0f)
617  o << "Count_Factor=" << tc->CountFactor () << endl;
618 
619  TrainingConfiguration2Ptr subClassifier = tc->SubClassifier ();
620  if (subClassifier)
621  o << "Sub_Classifier=" << subClassifier->ConfigRootName () << endl;
622 
623  for (kkuint32 zed = 0; zed < tc->DirectoryCount (); ++zed)
624  {
625  const KKStr& trainClassDir = tc->Directory (zed);
626  if (!trainClassDir.StartsWith (rootDir))
627  {
628  KKStr dirStr = tc->Directory (zed);
629  dirStr.TrimLeft ();
630  dirStr.TrimRight ();
631  if (!dirStr.Empty ())
632  o << "Dir=" << dirStr << endl;
633  }
634  }
635  o << endl;
636  }
637 
638  ModelParamOldSVMPtr oldSVMParams = OldSvmParameters ();
639  if (oldSVMParams)
640  {
641  const BinaryClassParmsListPtr binaryParms = oldSVMParams->BinaryParmsList ();
642  if (binaryParms)
643  {
644  BinaryClassParmsList::const_iterator idx;
645 
646  for (idx = binaryParms->begin (); idx != binaryParms->end (); idx++)
647  {
648  const BinaryClassParmsPtr binaryClass = *idx;
649  o << "[TWO_CLASS_PARAMETERS]" << endl;
650  o << "CLASS1=" << binaryClass->Class1Name () << endl;
651  o << "CLASS2=" << binaryClass->Class2Name () << endl;
652  o << "Parameters=" << binaryClass->Param ().ToCmdLineStr () << endl;
653  o << "Features_Included=" << binaryClass->SelectedFeatures () << endl;
654  o << "Weight=" << binaryClass->Weight () << endl;
655  o << endl;
656  }
657  }
658 
659  o << endl;
660  }
661 } /* Save */
662 
663 
664 
665 void TrainingConfiguration2::Save (const KKStr& fileName) const
666 {
667  ofstream o (fileName.Str ());
668  Save (o);
669  o.close ();
670 } /* Save */
671 
672 
673 void TrainingConfiguration2::RootDir (const KKStr& _rootDir)
674 {
675  rootDir = _rootDir;
676  rootDirExpanded = KKB::osSubstituteInEnvironmentVariables (rootDir);
677  trainingClasses.RootDir (rootDir);
678 }
679 
680 
681 
682 void TrainingConfiguration2::ModelParameters (ModelParamPtr _modelParameters)
683 {
684  delete modelParameters;
685  modelParameters = _modelParameters->Duplicate ();
686 }
687 
688 
689 
691 {
692  ModelParamPtr p = ModelParameters ();
693  if (!p)
694  return "";
695  else
696  return p->ToCmdLineStr ();
697 } /* ModelParameterCmdLine */
698 
699 
700 
702 {
703  TrainingClassList::const_iterator idx;
704 
705  MLClassListPtr classes = new MLClassList ();
706 
707  for (idx = trainingClasses.begin (); idx != trainingClasses.end (); idx++)
708  {
709  TrainingClassPtr tc = *idx;
710 
711  if (classes->PtrToIdx (tc->MLClass ()) < 0)
712  classes->PushOnBack (tc->MLClass ());
713  }
714 
715  classes->SortByName ();
716 
717  return classes;
718 } /* ExtractClassList */
719 
720 
721 
723 {
724  TrainingClassList::const_iterator idx;
725 
726  MLClassListPtr classes = new MLClassList ();
727 
728  for (idx = trainingClasses.begin (); idx != trainingClasses.end (); idx++)
729  {
730  TrainingClassPtr tc = *idx;
731  if (tc->SubClassifier () == NULL)
732  {
733  if (classes->PtrToIdx (tc->MLClass ()) < 0)
734  classes->PushOnBack (tc->MLClass ());
735  }
736  else
737  {
739  MLClassList::const_iterator idx2;
740  for (idx2 = subClassifierClasses->begin(); idx2 != subClassifierClasses->end (); ++idx2)
741  {
742  MLClassPtr subClass = *idx2;
743  if (classes->PtrToIdx (subClass) < 0)
744  classes->PushOnBack (subClass);
745  }
746  delete subClassifierClasses;
747  subClassifierClasses = NULL;
748  }
749  }
750 
751  classes->SortByName ();
752  return classes;
753 } /* ExtractFullHierachyOfClasses */
754 
755 
756 
757 TrainingConfiguration2Ptr TrainingConfiguration2::CreateFromFeatureVectorList
758  (FeatureVectorList& _examples,
759  FileDescPtr _fileDesc,
760  const KKStr& _parameterStr,
761  RunLog& _log
762  )
763 {
764  _log.Level (10) << "TrainingConfiguration2::CreateFromFeatureVectorList" << endl;
765  FileDescPtr fileDesc = _examples.FileDesc ();
766 
767  MLClassListPtr mlClasses = _examples.ExtractListOfClasses ();
768  mlClasses->SortByName ();
769  KKStr parameterStr = _parameterStr;
770  if (parameterStr.Empty ())
771  parameterStr = "-m 200 -s 0 -n 0.11 -t 2 -g 0.024717 -c 10 -u 100 -up -mt OneVsOne -sm P";
772 
774  = new TrainingConfiguration2 (mlClasses,
775  _fileDesc,
776  parameterStr,
777  _log
778  );
779 
780  config->SetFeatureNums (_examples.AllFeatures ());
781 
782  delete mlClasses; mlClasses = NULL;
783 
784  return config;
785 } /* CreateFromFeatureVectorList */
786 
787 
788 
789 TrainingConfiguration2Ptr TrainingConfiguration2::CreateFromDirectoryStructure
790  (const KKStr& _existingConfigFileName,
791  const KKStr& _subDir,
792  FactoryFVProducerPtr _fvFactoryProducer,
793  RunLog& _log,
794  bool& _successful,
795  KKStr& _errorMessage
796  )
797 {
798  _log.Level (10) << "TrainingConfiguration2::CreateFromDirectoryStructure" << endl
799  << " Feature Data from SubDir[" << _subDir << "]." << endl
800  << endl;
801 
802  _successful = true;
803 
804  KKStr directoryConfigFileName = osGetRootNameOfDirectory (_subDir);
805  if (directoryConfigFileName.Empty ())
806  directoryConfigFileName = osAddSlash (KKMLVariables::TrainingModelsDir ()) + "Root.cfg";
807  else
808  directoryConfigFileName = osAddSlash (KKMLVariables::TrainingModelsDir ()) + directoryConfigFileName + ".cfg";
809 
810  TrainingConfiguration2Ptr config = NULL;
811 
812  if (!_existingConfigFileName.Empty ())
813  {
814  if (osFileExists (_existingConfigFileName))
815  {
816  config = _fvFactoryProducer->ManufacturTrainingConfiguration ();
817  config->Load (_existingConfigFileName,
818  false, // false = DO NOT Validate Directories.
819  _log
820  );
821  config->RootDir (_subDir);
822  if (!(config->FormatGood ()))
823  {
824  delete config;
825  config = NULL;
826  }
827  }
828  }
829 
830  if (!config)
831  {
832  if (osFileExists (directoryConfigFileName))
833  {
834  config = _fvFactoryProducer->ManufacturTrainingConfiguration ();
835  config->Load (directoryConfigFileName,
836  false, // false = Do Not Validate Directories.
837  _log
838  );
839 
840  config->RootDir (_subDir);
841  if (!(config->FormatGood ()))
842  {
843  delete config;
844  config = NULL;
845  }
846  }
847  }
848 
849  if (!config)
850  {
851  if (_fvFactoryProducer != NULL)
852  _fvFactoryProducer = GrayScaleImagesFVProducerFactory::Factory (&_log);
853  config = new TrainingConfiguration2 (NULL, // Not supplying the MLClassList
854  _fvFactoryProducer,
855  "=-s 0 -n 0.11 -t 2 -g 0.01507 -c 12 -u 100 -up -mt OneVsOne -sm P",
856  _log
857  );
858  config->RootDir (_subDir);
859  }
860 
862  _successful,
863  _errorMessage,
864  _log
865  );
866 
867  if (config->Gamma () == 0.0)
868  config->Gamma (0.01507);
869 
870  config->Save (directoryConfigFileName);
871 
872  return config;
873 } /* CreateFromDirectoryTree */
874 
875 
876 
878  bool& _successful,
879  KKStr& _errorMessage,
880  RunLog& _log
881  )
882 {
883  _log.Level (10) << "TrainingConfiguration2::BuildTrainingClassListFromDirectoryStructure" << endl
884  << " Feature Data from SubDir[" << _subDir << "]." << endl
885  << endl;
886 
887  _successful = true;
888 
889  if (ModelParameters () == NULL)
890  {
891  bool _validFormat = true;
892  KKStr svmParameterStr = "-s 0 -n 0.11 -t 2 -g 0.01507 -c 12 -u 100 -up -mt OneVsOne -sm P";
893 
894  ModelParamOldSVMPtr oldSVMparameters = new ModelParamOldSVM ();
895  oldSVMparameters->ParseCmdLine (svmParameterStr, _validFormat, _log);
896  ModelParameters (oldSVMparameters);
897  ImagesPerClass (1000);
898  delete oldSVMparameters;
899  oldSVMparameters = NULL;
900  }
901 
903 
905 
906  if (mlClasses)
907  {
908  while (mlClasses->QueueSize () > 1)
909  mlClasses->PopFromBack ();
910  }
911 
912  KKStr subDirUnderRoot = "";
913  BuildTrainingClassListFromDirectoryEntry (_subDir,
914  subDirUnderRoot,
915  _successful,
916  _errorMessage,
917  _log
918  );
919 
920  {
921  // We can now update the traningClasses found with that which is in origTraniningClasses.
922  TrainingClassList::iterator idx;
923 
924  for (idx = trainingClasses.begin (); idx != trainingClasses.end (); idx++)
925  {
926  TrainingClassPtr tc = *idx;
927 
928  // I am not sure about this line. Might need to use rootDir from original configuration file.
929  TrainingClassPtr origTC = origTraniningClasses->LocateByDirectory (tc->ExpandedDirectory (_subDir, 0));
930  if (origTC)
931  {
932  tc->MLClass (origTC->MLClass ());
934  }
935  }
936  }
937 
938  delete origTraniningClasses;
939  origTraniningClasses = NULL;
940 } /* BuildTrainingClassListFromDirectoryStructure */
941 
942 
943 
944 void TrainingConfiguration2::BuildTrainingClassListFromDirectoryEntry (const KKStr& rootDir,
945  const KKStr& subDir,
946  bool& successful,
947  KKStr& errorMessage,
948  RunLog& log
949  )
950 {
951  log.Level (10) << "BuildTrainingClassListFromDirectoryEntry subDir[" << subDir << "]" << endl;
952 
953  KKStr currentDirectory = osAddSlash (rootDir) + subDir;
954 
955  KKStr dirSearchPath = osAddSlash (currentDirectory) + "*.*";
956  {
957  // Are there any image files in this directory ?
958  KKStrListPtr imageFilesInDir = osGetListOfImageFiles (dirSearchPath);
959  bool thereAreImageFilesInDir = (imageFilesInDir->QueueSize () > 0);
960  delete imageFilesInDir;
961 
962  if (thereAreImageFilesInDir)
963  {
964  KKStr className = MLClass::GetClassNameFromDirName (currentDirectory);
965  VectorKKStr subDirs;
966  subDirs.push_back (subDir);
967  AddATrainingClass (new TrainingClass (subDirs, className, 1.0f, 1.0f, NULL, *mlClasses));
968  }
969  }
970 
971  successful = true;
972  KKStrListPtr subDirectories = osGetListOfDirectories (dirSearchPath);
973  KKStrList::iterator sdIDX = subDirectories->begin ();
974  for (sdIDX = subDirectories->begin (); ((sdIDX != subDirectories->end ()) && successful); ++sdIDX)
975  {
976  KKStrPtr subDirName = *sdIDX;
977  KKStr newDirPath = "";
978  if (subDir.Empty ())
979  newDirPath = *subDirName;
980  else
981  newDirPath = osAddSlash (subDir) + (*subDirName);
982  BuildTrainingClassListFromDirectoryEntry (rootDir, newDirPath, successful, errorMessage, log);
983  }
984  delete subDirectories;
985 } /* BuildTrainingClassListFromDirectoryEntry */
986 
987 
988 
989 /**
990  * @brief Add a Training class to configuration
991  * Will take ownership of allocation.
992  */
994 {
995  trainingClasses.PushOnBack (_trainClass);
996 } /* AddATrainingClass */
997 
998 
999 
1000 /**
1001  *@brief Will assume that images for this class will be saved off the RootDirectory using its own
1002  name for the subdirectory name.
1003  */
1005 {
1006  VectorKKStr directories;
1007  TrainingClassPtr tc
1008  = new TrainingClass (directories,
1009  _newClass->Name (),
1010  1.0f, /**< Weight given to this Class during training */
1011  1.0f, /**< CountFactor. */
1012  NULL, /**< Sub-Classifier. */
1013  *mlClasses
1014  );
1016 }
1017 
1018 
1019 
1021 {
1022  ModelParamOldSVMPtr oldSVMparms = OldSvmParameters ();
1023  if (oldSVMparms)
1024  {
1025  SVMparamPtr s = oldSVMparms->SvmParameters ();
1026  return *s;
1027  }
1028  else
1029  {
1030  KKStr errMsg = "TrainingConfiguration2::SVMparamREF ***ERROR*** (modelingMethod != mmOldSVM)";
1031  log.Level (-1) << endl << errMsg << endl << endl;
1032  throw new KKException (errMsg);
1033  }
1034 } /* SVMparam */
1035 
1036 
1037 
1038 SVMparamPtr TrainingConfiguration2::SVMparamToUse () const
1039 {
1040  ModelParamOldSVMPtr oldSVMparms = OldSvmParameters ();
1041  if (oldSVMparms)
1042  {
1043  SVMparamPtr s = oldSVMparms->SvmParameters ();
1044  return s;
1045  }
1046  else
1047  {
1048  return NULL;
1049  }
1050 } /* SVMparamToUse */
1051 
1052 
1053 
1055 {
1056  if (modelParameters)
1057  return modelParameters->A_Param ();
1058  else
1059  return 0.0f;
1060 }
1061 
1062 
1063 
1064 void TrainingConfiguration2::A_Param (float _aParam)
1065 {
1066  if (modelParameters)
1067  modelParameters->A_Param (_aParam);
1068 } /* A_Param */
1069 
1070 
1071 
1073 {
1074  if (modelParameters)
1075  return modelParameters->Gamma ();
1076  else
1077  return 0.0;
1078 } /* Gamma */
1079 
1080 
1081 
1082 void TrainingConfiguration2::Gamma (double _gamma)
1083 {
1084  if (modelParameters)
1085  modelParameters->Gamma (_gamma);
1086 } /* Gamma */
1087 
1088 
1089 
1091 {
1092  if (modelParameters)
1093  return modelParameters->C_Param ();
1094  else
1095  return 0.0;
1096 }
1097 
1098 
1099 
1100 void TrainingConfiguration2::C_Param (double _CCC)
1101 {
1102  if (modelParameters)
1103  modelParameters->C_Param (_CCC);
1104 }
1105 
1106 
1107 
1109 {
1110  if (modelParameters && (modelParameters->ModelParamType () == ModelParam::ModelParamTypes::UsfCasCor))
1111  {
1112  return dynamic_cast<ModelParamUsfCasCor*>(modelParameters)->Number_of_rounds ();
1113  }
1114  else
1115  {
1116  return -1;
1117  }
1118 }
1119 
1120 
1121 
1123 {
1124  if (modelParameters && (modelParameters->ModelParamType () == ModelParam::ModelParamTypes::UsfCasCor))
1125  {
1126  dynamic_cast<ModelParamUsfCasCor*>(modelParameters)->Number_of_rounds (_number_of_rounds);
1127  }
1128 }
1129 
1130 
1131 
1133 {
1134  ModelParamOldSVMPtr oldSVMparms = OldSvmParameters ();
1135  if (oldSVMparms)
1136  oldSVMparms->MachineType (_machineType);
1137 
1138 } /* MachineType */
1139 
1140 
1141 
1143 {
1144  ModelParamOldSVMPtr oldSVMparms = OldSvmParameters ();
1145  if (oldSVMparms)
1146  return oldSVMparms->MachineType ();
1147  else
1148  return SVM_MachineType::Null;
1149 } /* MachineType */
1150 
1151 
1152 
1154 {
1155  ModelParamOldSVMPtr oldSVMparms = OldSvmParameters ();
1156  if (oldSVMparms)
1157  oldSVMparms->SelectionMethod (_selectionMethod);
1158 } /* SelectionMethod */
1159 
1160 
1161 
1163 {
1164  ModelParamOldSVMPtr oldSVMparms = OldSvmParameters ();
1165  if (oldSVMparms)
1166  return (SVM_SelectionMethod)oldSVMparms->SelectionMethod ();
1167  else
1169 } /* SelectionMethod */
1170 
1171 
1172 
1174 {
1175  if (modelParameters)
1176  modelParameters->SelectedFeatures (features);
1177 } /* SetFeatureNums */
1178 
1180  MLClassPtr class2,
1181  const FeatureNumList& _features,
1182  float _weight
1183  )
1184 {
1185  ModelParamOldSVMPtr oldSVMparms = OldSvmParameters ();
1186  if (oldSVMparms)
1187  {
1188  oldSVMparms->SetFeatureNums (class1, class2, &_features, _weight);
1189  }
1190 } /* SetFeatureNums */
1191 
1192 
1193 
1195 {
1196  if (modelParameters)
1197  modelParameters->EncodingMethod ((ModelParam::EncodingMethodType)_encodingMethod);
1198 }
1199 
1200 
1201 
1203 {
1204  const SVMparamPtr param = SVMparamToUse ();
1205  if (param)
1206  return param->EncodingMethod ();
1207  else
1209 } /* EncodingMethod */
1210 
1211 
1212 
1214  MLClassPtr class2
1215  ) const
1216 {
1217  ModelParamOldSVMPtr oldSVMparms = OldSvmParameters ();
1218  if (oldSVMparms)
1219  return oldSVMparms->C_Param (class1, class2);
1220  else
1221  return 0.0;
1222 }
1223 
1224 
1225 
1227  MLClassPtr class2,
1228  double cParam
1229  )
1230 {
1231  ModelParamOldSVMPtr oldSVMparms = OldSvmParameters ();
1232  if (oldSVMparms)
1233  oldSVMparms->C_Param (class1, class2, cParam);
1234 } /* C_Param */
1235 
1236 
1237 
1239  MLClassPtr class2,
1240  const SVM233::svm_parameter& _param,
1241  const FeatureNumList& _features,
1242  float _weight
1243  )
1244 {
1245  ModelParamOldSVMPtr oldSVMparms = OldSvmParameters ();
1246  if (oldSVMparms)
1247  oldSVMparms->SetBinaryClassFields (class1, class2, _param, &_features, _weight);
1248 } /* SetBinaryClassFields */
1249 
1250 
1251 
1253 {
1255  TrainingClassList::iterator idx;
1256 
1257  for (idx = _trainingClasses->begin (); idx != _trainingClasses->end (); idx++)
1258  AddATrainingClass (*idx);
1259 } /* SetTrainingClasses */
1260 
1261 
1262 
1264 {
1265  if (modelParameters)
1266  return modelParameters->AvgMumOfFeatures ();
1267  return 0.0f;
1268 } /* AvgMumOfFeatures */
1269 
1270 
1271 
1272 float TrainingConfiguration2::AvgNumOfFeatures (FeatureVectorListPtr trainExamples) const
1273 {
1274  const SVMparamPtr param = SVMparamToUse ();
1275  if (param)
1276  return param->AvgNumOfFeatures (trainExamples);
1277  else
1278  return 0.0f;
1279 }
1280 
1281 
1282 
1284 {
1285  const SVMparamPtr param = SVMparamToUse ();
1286  if (param)
1287  return param->KernalType ();
1288  return SVM_KernalType::Linear;
1289 } /* KernalType */
1290 
1291 
1292 
1294 {
1295  const SVMparamPtr param = SVMparamToUse ();
1296  if (param)
1297  return param->KernalType (_kernalType);
1298 } /* KernalType */
1299 
1300 
1301 
1303 {
1304  if (modelParameters)
1305  {
1306  FeatureNumListConstPtr fnl = modelParameters->SelectedFeatures ();
1307  if (fnl)
1308  return *fnl;
1309  }
1310  if (fileDesc)
1311  return FeatureNumList (fileDesc);
1312  else
1313  return FeatureNumList (1);
1314 } /* GetFeatureNums */
1315 
1316 
1317 
1319 {
1320  if (modelParameters)
1321  return modelParameters->NumOfFeaturesAfterEncoding (fileDesc, log);
1322  else
1323  return 0;
1324 } /* NumOfFeaturesAfterEncoding */
1325 
1326 
1327 
1329 {
1330  examplesPerClass = _examplesPerClass;
1331 }
1332 
1333 
1334 
1336 {
1337  return examplesPerClass;
1338 } /* ImagesPerClass */
1339 
1340 
1341 
1343  MLClassPtr class2
1344  )
1345 {
1346  ModelParamOldSVMPtr oldSVMparms = OldSvmParameters ();
1347  if (oldSVMparms)
1348  {
1349  FeatureNumListConstPtr fnl = oldSVMparms->GetFeatureNums (fileDesc, class1, class2);
1350  if (fnl)
1351  return *fnl;
1352  }
1353 
1354  return FeatureNumList::AllFeatures (fileDesc);
1355 } /* GetFeatureNums */
1356 
1357 
1358 
1359 void TrainingConfiguration2::SetModelParameters (ModelParamPtr _svmParanters,
1360  kkint32 _examplesPerClass
1361  )
1362 {
1363  delete modelParameters;
1364  modelParameters = _svmParanters->Duplicate ();
1365  examplesPerClass = _examplesPerClass;
1366 } /* SetModel3Parameters */
1367 
1368 
1369 
1370 TrainingConfiguration2Ptr TrainingConfiguration2::ValidateSubClassifier (const KKStr& subClassifierName,
1371  bool& errorsFound,
1372  RunLog& log
1373  )
1374 {
1375  errorsFound = false;
1376  KKStr rootName = KKB::osGetRootName (subClassifierName);
1377  if (!subClassifiers)
1378  subClassifiers = new TrainingConfiguration2List (true);
1379 
1380  TrainingConfiguration2Ptr config = subClassifiers->LookUp (subClassifierName);
1381  if (!config)
1382  {
1383  config = fvFactoryProducer->ManufacturTrainingConfiguration ();
1384  config->Load (subClassifierName, true, log);
1385  subClassifiers->PushOnBack (config);
1386  if (!config->FormatGood ())
1387  {
1388  errorsFound = true;
1389  const VectorKKStr& errors = config->FormatErrors ();
1390  const VectorInt& lineNums = config->FormatErrorsLineNums ();
1391  kkuint32 zed = Max (errors.size (), lineNums.size ());
1392  for (kkuint32 x = 0; x < zed; ++x)
1393  FormatErrorsAdd (lineNums[x], errors[x]);
1394  }
1395  }
1396 
1397  return config;
1398 } /* ValidateSubClassifier */
1399 
1400 
1401 
1402 TrainingClassPtr TrainingConfiguration2::ValidateClassConfig (kkint32 sectionNum,
1403  RunLog& log
1404  )
1405 {
1406  kkint32 numOfSettings = NumOfSettings ((kkint32)sectionNum);
1407 
1408  kkint32 classNameLineNum = 0;
1409  kkint32 dirLineNum = 0;
1410  kkint32 weightLineNum = 0;
1411  kkint32 countFactorLineNum = 0;
1412  kkint32 subClassifierLineNum = 0;
1413 
1414  kkint32 sectionLineNum = SectionLineNum (sectionNum);
1415 
1416  VectorKKStr directories;
1417  KKStr className;
1418  KKStr subClassifierName;
1419  float weight = 1.0f;
1420  float countFactor = 0.0f;
1421 
1422  for (kkint32 settingNum = 0; settingNum < numOfSettings; ++settingNum)
1423  {
1424  KKStrConstPtr settingNamePtr = SettingName (sectionNum, settingNum);
1425  if (!settingNamePtr)
1426  continue;
1427 
1428  kkint32 settingLineNum = 0;
1429  KKStrConstPtr setingValuePtr = SettingValue (sectionNum, settingNum, settingLineNum);
1430  KKStr settingValue = "";
1431  if (setingValuePtr)
1432  settingValue = *setingValuePtr;
1433 
1434  if (settingNamePtr->EqualIgnoreCase ("CLASS_NAME"))
1435  {
1436  className = settingValue;
1437  classNameLineNum = settingLineNum;
1438  }
1439 
1440  else if (settingNamePtr->EqualIgnoreCase ("SUB_CLASSIFIER"))
1441  {
1442  subClassifierName = settingValue;
1443  subClassifierLineNum = settingLineNum;
1444  }
1445 
1446  else if (settingNamePtr->EqualIgnoreCase ("WEIGHT"))
1447  {
1448  weight = settingValue.ToFloat ();
1449  weightLineNum = settingLineNum;
1450  }
1451 
1452  else if (settingNamePtr->EqualIgnoreCase ("COUNT_FACTOR"))
1453  {
1454  countFactor = settingValue.ToFloat ();
1455  countFactorLineNum = settingLineNum;
1456  }
1457 
1458  else if (settingNamePtr->EqualIgnoreCase ("DIR"))
1459  {
1460  if (!settingValue.Empty ())
1461  directories.push_back (settingValue);
1462 
1463  else if (!className.Empty ())
1464  directories.push_back (className);
1465  }
1466  }
1467 
1468  if (directories.size () < 1)
1469  {
1470  directories.push_back (className);
1471  }
1472 
1473  if (className.Empty ())
1474  {
1475  KKStr errMsg = "'TRAINING_CLASS' section, CLASS_NAME not defined.";
1476  log.Level (-1) << "ValidateClassConfig " << errMsg << endl;
1477  FormatErrorsAdd (sectionLineNum, errMsg);
1478  FormatGood (false);
1479  return NULL;
1480  }
1481 
1482  TrainingConfiguration2Ptr subClassifer = NULL;
1483  if (!subClassifierName.Empty ())
1484  {
1485  bool errorsFound = false;
1486  subClassifer = ValidateSubClassifier (subClassifierName, errorsFound, log);
1487  if (errorsFound)
1488  {
1489  KKStr errMsg = "Sub-Classifier [" + (subClassifierName) + "] has a format error: " + subClassifer->FileName ();
1490  FormatErrorsAdd (subClassifierLineNum, errMsg);
1491  VectorKKStr subClassifierErrors = subClassifer->FormatErrorsWithLineNumbers ();
1492  VectorKKStr::const_iterator idx;
1493  for (idx = subClassifierErrors.begin (); idx != subClassifierErrors.end (); ++idx)
1494  FormatErrorsAdd (subClassifierLineNum, " " + subClassifierName + ": " + *idx);
1495  }
1496  }
1497 
1498  if (weight <= 0.0f)
1499  {
1500  KKStr errMsg = "Class[" + className + "] Invalid Weight Parameter.";
1501  log.Level (-1) << "ValidateClassConfig " << errMsg << endl;
1502  FormatErrorsAdd (weightLineNum, errMsg);
1503  FormatGood (false);
1504  return NULL;
1505  }
1506 
1507  TrainingClassPtr tc = new TrainingClass (directories, className, weight, countFactor, subClassifer, *mlClasses);
1508 
1509  if (validateDirectories)
1510  {
1511  KKStr rootDirExpanded = osSubstituteInEnvironmentVariables (rootDir);
1512  for (kkuint32 zed = 0; zed < tc->DirectoryCount (); ++zed)
1513  {
1514  KKStr expandedDir = tc->ExpandedDirectory (rootDirExpanded, zed);
1515  if (!osValidDirectory (expandedDir))
1516  {
1517  KKStr errMsg = "Invalid Directory Specified[" + expandedDir + "].";
1518  log.Level (-1) << endl << "ValidateClassConfig ***ERROR*** " << errMsg << endl << endl;
1519  FormatErrorsAdd (dirLineNum, errMsg);
1520  FormatGood (false);
1521  delete tc; tc = NULL;
1522  return NULL;
1523  }
1524  }
1525  }
1526 
1527  return tc;
1528 } /* ValidateClassConfig */
1529 
1530 
1531 
1532 void TrainingConfiguration2::ValidateOtherClass (MLClassPtr otherClass,
1533  kkint32 otherClassLineNum,
1534  RunLog& log
1535  )
1536 {
1537  KKStr classDirToUse = osAddSlash (rootDir) + otherClass->Name ();
1538  if (!osValidDirectory (classDirToUse))
1539  {
1540  KKStr errMsg = "OtherClass Directory [" + classDirToUse + "] does not exist.";
1541  log.Level (-1) << endl << "ValidateOtherClass ***ERROR*** " << errMsg << endl << endl;
1542  FormatErrorsAdd (otherClassLineNum, errMsg);
1543  FormatGood (false);
1544  }
1545 } /* ValidateOtherClass */
1546 
1547 
1548 
1549 void TrainingConfiguration2::ValidateTrainingClassConfig (kkint32 sectionNum,
1550  RunLog& log
1551  )
1552 {
1553  TrainingClassPtr trainingClass = ValidateClassConfig (sectionNum, log);
1554  if (trainingClass)
1555  {
1556  trainingClasses.AddTrainingClass (trainingClass);
1557  }
1558 
1559 } /* ValidateTrainingClassConfig */
1560 
1561 
1562 
1563 FeatureNumListPtr TrainingConfiguration2::DeriveFeaturesSelected (kkint32 sectionNum)
1564 {
1565  kkint32 sectionLineNum = SectionLineNum (sectionNum);
1566 
1567  kkint32 featuresIncludedLineNum = 0;
1568  kkint32 featuresExcludedLineNum = 0;
1569 
1570  KKStr includedFeaturesStr (SettingValueToStr (sectionNum, "FEATURES_INCLUDED", featuresIncludedLineNum));
1571 
1572  FeatureNumListPtr selectedFeatures = NULL;
1573 
1574  if (includedFeaturesStr.Empty () || includedFeaturesStr.EqualIgnoreCase ("ALL"))
1575  {
1576  // We will assume user want's all features.
1577  selectedFeatures = new FeatureNumList (FeatureNumList::AllFeatures (fileDesc));
1578  }
1579 
1580  else
1581  {
1582  bool valid = false;
1583  selectedFeatures = new FeatureNumList (includedFeaturesStr, valid);
1584  }
1585 
1586  if (!selectedFeatures)
1587  {
1588  FormatGood (false);
1589  delete selectedFeatures;
1590  return NULL;
1591  }
1592 
1593  return selectedFeatures;
1594 } /* DeriveFeaturesSelected */
1595 
1596 
1597 
1598 void TrainingConfiguration2::ValidateGlobalSection (kkint32 sectionNum,
1599  RunLog& log
1600  )
1601 {
1602  kkint32 methodLineNum = 0;
1603  kkint32 rootDirLineNum = 0;
1604  kkint32 sectionLineNum = SectionLineNum (sectionNum);
1605  kkint32 fvFactoryLineNum = 0;
1606 
1607  KKStr modelingMethodStr (SettingValueToStr (sectionNum, "MODELING_METHOD", methodLineNum));
1608  modelingMethodStr.Upper ();
1609 
1610  log.Level (30) << "ValidateGlobalSection - ModelingMethod[" << Model::ModelTypeToStr (modelingMethod) << "] LineNum[" << methodLineNum << "]." << endl;
1611 
1612  modelingMethod = ModelTypeFromStr (modelingMethodStr);
1613 
1614  if (methodLineNum < 0)
1615  {
1616  KKStr errMsg = "No Modeling_Method was specified.";
1617  log.Level (-1) << endl
1618  << "ValidateGlobalSection ***ERROR*** " << errMsg << endl
1619  << endl;
1620  FormatErrorsAdd (sectionLineNum, errMsg);
1621  FormatGood (false);
1622  }
1623 
1624  if (modelingMethod == Model::ModelTypes::Null)
1625  {
1626  // We have a invalid Modeling Method Parameter.
1627  KKStr errMsg = "Invalid Modeling Method[" + modelingMethodStr + "] was specified.";
1628  log.Level (-1) << endl
1629  << "ValidateGlobalSection ***ERROR*** " << errMsg << endl
1630  << endl;
1631  FormatErrorsAdd (methodLineNum, errMsg);
1632  FormatGood (false);
1633  }
1634 
1635  KKStr fvFactoryProducerName (SettingValueToStr (sectionNum, "FEATURE_COMPUTER", fvFactoryLineNum));
1636  if (fvFactoryLineNum < 0)
1637  {
1638  fvFactoryProducerSpecified = false;
1639  if (!fvFactoryProducer)
1640  {
1641  fvFactoryProducer = DefaultFeatureVectorProducer (log);
1642  log.Level (-1) << "No Feature-Computer Specified; defaulting to '" << fvFactoryProducer->Name () << "'." << endl;
1643  }
1644  }
1645  else
1646  {
1647  KKStr defaultName = "None";
1648  if (!fvFactoryProducer)
1649  {
1650  fvFactoryProducer = DefaultFeatureVectorProducer (log);
1651  defaultName = fvFactoryProducer->Name ();
1652  }
1653  FactoryFVProducerPtr factorySpecified = FactoryFVProducer::LookUpFactory (fvFactoryProducerName);
1654  if (!factorySpecified)
1655  {
1656  log.Level (-1) << endl << "ValidateGlobalSection ***ERROR*** Factory[" << fvFactoryProducerName << "] on lineNum[" << fvFactoryLineNum << "] not defined" << endl
1657  << " defaulting to: " << defaultName << endl
1658  << endl;
1659  fvFactoryProducerSpecified = false;
1660  }
1661  else
1662  {
1663  fvFactoryProducer = factorySpecified;
1664  fvFactoryProducerSpecified = true;
1665  }
1666  }
1667 
1668  KKStr rootDirStr (SettingValueToStr (sectionNum, "ROOT_DIR", rootDirLineNum));
1669  if (rootDirLineNum < 0)
1670  {
1671  // No Root Directory was specified.
1672  rootDir = osAddSlash (KKMLVariables::TrainingLibrariesDir ()) + osGetRootName (this->FileName ());
1673  log.Level (10) << endl
1674  << "ValidateGlobalSection 'Root_Dir' Was not specified defaulting to[" << rootDir << "]" << endl
1675  << endl;
1676  }
1677  else
1678  {
1679  rootDir = rootDirStr;
1680  rootDirExpanded = osSubstituteInEnvironmentVariables (rootDir);
1681  if (!rootDir.Empty () && (!osValidDirectory (rootDirExpanded)) && validateDirectories)
1682  {
1683  KKStr errMsg = "Invalid RootDir[" + rootDirStr + "] Specified on line[" + StrFormatInt (rootDirLineNum, "ZZZ0") + "]. Expanded to[" + RootDirExpanded () + "]";
1684  log.Level (-1) << endl
1685  << "ValidateGlobalSection ***ERROR*** " << errMsg << endl
1686  << endl;
1687  FormatErrorsAdd (rootDirLineNum, errMsg);
1688  FormatGood (false);
1689  }
1690  }
1691 
1692  kkint32 parametersLineNum = -1;
1693  kkint32 featuresIncludedLineNum = -1;
1694  kkint32 examplesPerClassLineNum = -1;
1695 
1696  KKStr modelParametersStr = SettingValueToStr (sectionNum, "Parameters", parametersLineNum);
1697  KKStr featuresIncludedStr = SettingValueToStr (sectionNum, "Features_Included", featuresIncludedLineNum);
1698 
1699  if ((parametersLineNum < 0) && (modelingMethod == Model::ModelTypes::OldSVM))
1700  modelParametersStr = SettingValueToStr ("Model3", "Parameters", parametersLineNum);
1701 
1702  if ((featuresIncludedLineNum < 0) && (modelingMethod == Model::ModelTypes::OldSVM))
1703  featuresIncludedStr = SettingValueToStr ("Model3", "Features_Included", featuresIncludedLineNum);
1704 
1705  if (parametersLineNum < 0)
1706  {
1707  KKStr errMsg = "'Parameters' setting was not specified.";
1708  log.Level (-1) << endl
1709  << "ValidateGlobalSection ***ERROR*** " << errMsg << endl
1710  << endl;
1711  FormatErrorsAdd (sectionLineNum, errMsg);
1712  FormatGood (false);
1713  }
1714 
1715  if (featuresIncludedStr.Empty ())
1716  featuresIncludedStr = "All";
1717 
1718  bool validFeaturesNums = false;
1719  FeatureNumList selFeatures (featuresIncludedStr, validFeaturesNums);
1720  if (!validFeaturesNums)
1721  {
1722  KKStr errMsg = "Invalid Features_Included[" + featuresIncludedStr + "].";
1723  log.Level (-1) << endl
1724  << "ValidateGlobalSection ***ERROR*** " << errMsg << endl
1725  << endl;
1726  FormatErrorsAdd (featuresIncludedLineNum, errMsg);
1727  FormatGood (false);
1728  }
1729 
1730  {
1731  KKStr examplesPerClassStr = SettingValueToStr (sectionNum, "Examples_Per_Class", examplesPerClassLineNum);
1732  if (examplesPerClassStr.Empty ())
1733  examplesPerClassStr = SettingValueToStr (sectionNum, "Images_Per_Class", examplesPerClassLineNum);
1734 
1735  if ((examplesPerClassLineNum < 0) && (modelingMethod == Model::ModelTypes::OldSVM))
1736  {
1737  examplesPerClassStr = SettingValueToStr ("Model3", "Examples_Per_Class", examplesPerClassLineNum);
1738  if (examplesPerClassStr.Empty ())
1739  examplesPerClassStr = SettingValueToStr ("Model3", "Images_Per_Class", examplesPerClassLineNum);
1740  }
1741 
1742  if (examplesPerClassStr.Empty ())
1743  examplesPerClass = int32_max;
1744 
1745  else
1746  examplesPerClass = examplesPerClassStr.ToInt ();
1747 
1748  if (examplesPerClass < 1)
1749  {
1750  KKStr errMsg = "Invalid Examples_Per_Class[" + examplesPerClassStr + "].";
1751  log.Level (-1) << endl
1752  << "ValidateGlobalSection ***ERROR*** " << errMsg << endl
1753  << endl;
1754  FormatErrorsAdd (examplesPerClassLineNum, errMsg);
1755  FormatGood (false);
1756  }
1757  }
1758 
1759  CreateModelParameters (modelParametersStr, selFeatures, sectionLineNum, parametersLineNum, featuresIncludedLineNum, log);
1760  if (modelParameters)
1761  {
1762  if (examplesPerClassLineNum >= 0)
1763  modelParameters->ExamplesPerClass (examplesPerClass);
1764  else
1765  examplesPerClass = modelParameters->ExamplesPerClass ();
1766  }
1767 
1768  KKStr otherClassName (SettingValueToStr (sectionNum, "OtherClass", otherClassLineNum));
1769  if (otherClassLineNum >= 0)
1770  {
1771  if (otherClassName.Empty ())
1772  {
1773  KKStr errMsg = "OtherClass specified but no name provided.";
1774  log.Level (-1) << endl << "ValidateGlobalSection ***ERROR*** " << errMsg << endl;
1775  FormatErrorsAdd (examplesPerClassLineNum, errMsg);
1776  FormatGood (false);
1777  }
1778 
1779  otherClass = MLClass::CreateNewMLClass (otherClassName, -1);
1780  ValidateOtherClass (otherClass, otherClassLineNum, log);
1781  }
1782 } /* ValidateGlobalSection */
1783 
1784 
1785 
1786 void TrainingConfiguration2::ValidateTwoClassParameters (kkint32 sectionNum,
1787  RunLog& log
1788  )
1789 {
1790  if (!modelParameters)
1791  {
1792  log.Level (-1) << "ValidateTwoClassParameters - Global Parameters must be defined first."
1793  << endl;
1794  FormatGood (false);
1795  }
1796 
1797  kkint32 class1NameLineNum = -1;
1798  kkint32 class2NameLineNum = -1;
1799  kkint32 parameterLinenum = -1;
1800  kkint32 weightLineNum = -1;
1801 
1802  kkint32 sectionLineNum = SectionLineNum (sectionNum);
1803 
1804  KKStr class1Name (SettingValueToStr (sectionNum, "CLASS1", class1NameLineNum));
1805  KKStr class2Name (SettingValueToStr (sectionNum, "CLASS2", class2NameLineNum));
1806  KKStr parameterStr (SettingValueToStr (sectionNum, "PARAMETERS", parameterLinenum));
1807  KKStr weightStr (SettingValueToStr (sectionNum, "WEIGHT", weightLineNum));
1808 
1809  if (class1NameLineNum < 0)
1810  {
1811  KKStr errMsg = "'Class1' setting was not defined.";
1812  log.Level (-1) << endl << "ValidateTwoClassParameters ***ERROR*** " << errMsg << endl << endl;
1813  FormatErrorsAdd (sectionLineNum, errMsg);
1814  FormatGood (false);
1815  }
1816 
1817  if (class2NameLineNum < 0)
1818  {
1819  KKStr errMsg = "'Class2' setting was not defined.";
1820  log.Level (-1) << endl << "ValidateTwoClassParameters ***ERROR*** " << errMsg << endl << endl;
1821  FormatErrorsAdd (sectionLineNum, errMsg);
1822  FormatGood (false);
1823  }
1824 
1825  MLClassPtr class1 = mlClasses->LookUpByName (class1Name);
1826  MLClassPtr class2 = mlClasses->LookUpByName (class2Name);
1827 
1828  if (!class1)
1829  {
1830  log.Level (20) << "ValidateTwoClassParameters LineNum[" << class1NameLineNum << "] Class[" << class1Name << "] not part of classifier." << endl;
1831  return;
1832  }
1833 
1834  if (!class2)
1835  {
1836  log.Level (20) << "ValidateTwoClassParameters LineNum[" << class2NameLineNum << "] Class[" << class2Name << "] not part of classifier." << endl;
1837  return;
1838  }
1839 
1840  FeatureNumListConstPtr selectedFeatures = DeriveFeaturesSelected (sectionNum);
1841  if (!selectedFeatures)
1842  selectedFeatures = modelParameters->SelectedFeatures ();
1843 
1844  if (!selectedFeatures)
1845  selectedFeatures = new FeatureNumList (fileDesc);
1846 
1847  if ((class1NameLineNum > 0) && (!class1))
1848  {
1849  KKStr errMsg = "Class[" + class1Name + "] is not defined.";
1850  log.Level (-1) << endl << "ValidateTwoClassParameters ***ERROR*** " << errMsg << endl << endl;
1851  FormatErrorsAdd (class1NameLineNum, errMsg);
1852  FormatGood (false);
1853  }
1854 
1855  if ((class2NameLineNum > 0) && (!class2))
1856  {
1857  KKStr errMsg = "Class[" + class2Name + "] is not defined.";
1858  log.Level (-1) << endl << "ValidateTwoClassParameters ***ERROR*** " << errMsg << endl << endl;
1859  FormatErrorsAdd (class2NameLineNum, errMsg);
1860  FormatGood (false);
1861  }
1862 
1863  if (!FormatGood ())
1864  return;
1865 
1866  if (class1 && class2)
1867  {
1868  float weight = 1.0f;
1869  if (!weightStr.Empty ())
1870  weight = (float)atof (weightStr.Str ());
1871 
1872  ModelParamOldSVMPtr oldSvmParameters = OldSvmParameters ();
1873  if (oldSvmParameters)
1874  {
1875  SVM233::svm_parameter binaryParam (oldSvmParameters->Param ());
1876  if (!parameterStr.Empty ())
1877  {
1878  SVM233::svm_parameter tempParam (parameterStr);
1879  binaryParam = tempParam;
1880  }
1881 
1882  oldSvmParameters->AddBinaryClassParms (class1, class2, binaryParam, selectedFeatures, weight);
1883  }
1884  }
1885  delete selectedFeatures;
1886 } /* ValidateTwoClassParameters */
1887 
1888 
1889 
1890 void TrainingConfiguration2::ValidateConfiguration (RunLog& log)
1891 {
1892  // Validate TrainingClasses
1893 
1894  this->FormatErrorsClear ();
1895 
1896  kkint32 numOfSections = NumOfSections ();
1897 
1898  for (kkint32 sectionNum = 0; sectionNum < numOfSections; sectionNum++)
1899  {
1900  KKStr sectionName (*SectionName (sectionNum));
1901  sectionName.Upper ();
1902 
1903  if (sectionName == "TRAINING_CLASS")
1904  {
1905  ValidateTrainingClassConfig (sectionNum, log);
1906  }
1907 
1908  else if (sectionName == "NOISE_IMAGES")
1909  {
1910  noiseTrainingClass = ValidateClassConfig (sectionNum, log);
1911  if (noiseTrainingClass)
1912  {
1913  kkint32 noiseGuaranteedSizeLineNum = -1;
1914  noiseMLClass = noiseTrainingClass->MLClass ();
1915  noiseMLClass->UnDefined (true);
1916  }
1917  else
1918  {
1919  log.Level (-1) << "ValidateConfiguration *** Invalid Noise Class Definition ***"
1920  << endl;
1921  FormatGood (false);
1922  }
1923  }
1924 
1925  else if (sectionName == "GLOBAL")
1926  {
1927  ValidateGlobalSection (sectionNum, log);
1928  }
1929 
1930  else if ((sectionName == "TWO_CLASS_PARAMETERS") ||
1931  (sectionName == "TWOCLASSPARAMETERS") ||
1932  (sectionName == "TWO_CLASSPARAMETERS")
1933  )
1934  {
1935  ValidateTwoClassParameters (sectionNum, log);
1936  }
1937  }
1938 
1939  if (trainingClasses.QueueSize () < 1)
1940  {
1941  log.Level (-1) << endl << "ValidateConfiguration ***ERROR*** No Training Classes defined." << endl;
1942  FormatGood (false);
1943  }
1944 
1945 
1946  if (modelParameters == NULL)
1947  {
1948  log.Level (-1) << "ValidateConfiguration ***ERROR*** SVM Parameters not specified." << endl;
1949  FormatGood (false);
1950  }
1951 
1952  if (otherClass != NULL)
1953  {
1954  if (trainingClasses.LocateByMLClass (otherClass) != NULL)
1955  {
1956  KKStr errMsg = "OtherClass[" + otherClass->Name () + "] was also defined as a TrainingClass.";
1957  log.Level (-1) << endl << "ValidateConfiguration ***ERROR*** " << errMsg << endl << endl;
1958  FormatErrorsAdd (otherClassLineNum, errMsg);
1959  FormatGood (false);
1960  }
1961  }
1962 
1963 } /* ValidateConfiguration */
1964 
1965 
1966 
1968 {
1969  return trainingClasses.LocateByMLClassName (className);
1970 }
1971 
1972 
1973 
1975 {
1976  while (trainingClasses.QueueSize () > 0)
1977  {
1978  TrainingClassPtr trainingClass = trainingClasses.PopFromBack ();
1979  delete trainingClass;
1980  }
1981 } /* DeleteTrainingClasses */
1982 
1983 
1984 
1986 {
1987  ModelParamOldSVMPtr oldSvmParameters = OldSvmParameters ();
1988  if (oldSvmParameters)
1989  return oldSvmParameters->NormalizeNominalFeatures ();
1990 
1991  else if (modelParameters)
1992  return modelParameters->NormalizeNominalFeatures ();
1993 
1994  else
1995  return false;
1996 } /* NormalizeNominalFeatures */
1997 
1998 
1999 
2000 namespace KKMLL
2001 {
2002  KKStr& operator<< (KKStr& left,
2003  TrainingConfiguration2::ModelTypes modelingMethod
2004  )
2005  {
2007  return left;
2008  }
2009 
2010 
2011 
2012  ostream& KKMLL::operator<< (std::ostream& os,
2013  TrainingConfiguration2::ModelTypes modelingMethod
2014  )
2015  {
2016  os << TrainingConfiguration2::ModelTypeToStr (modelingMethod);
2017  return os;
2018  }
2019 }
2020 
2021 
2022 
2024 {
2025  if (!otherClass)
2026  return NULL;
2027 
2028  KKStr otherClassDirName = "";
2029 
2030  if (rootDir.Empty ())
2031  otherClassDirName = otherClass->Name ();
2032  else
2033  otherClassDirName = osAddSlash (rootDir) + otherClass->Name ();
2034 
2035  otherClassDirName = osSubstituteInEnvironmentVariables (otherClassDirName);
2036 
2037  MLClassList tempClasses;
2038  bool cancelFlag = false;
2039  bool changesMade = false;
2040  DateTime latestTimeStamp;
2041 
2042  FeatureVectorListPtr otherClassExamples = fvFactoryProducer->DefaultFeatureFileIO ()->FeatureDataReSink
2043  (fvFactoryProducer,
2044  otherClassDirName,
2045  otherClass->Name () + ".data",
2046  otherClass,
2047  true, // true = Use-Directory-name-For-Class-Name (otherClass->Name ())
2048  tempClasses,
2049  cancelFlag,
2050  changesMade,
2051  latestTimeStamp,
2052  runLog
2053  );
2054 
2055  return otherClassExamples;
2056 } /* LoadOtherClasssExamples */
2057 
2058 
2059 
2060 /**
2061  *@brief Load training data from the training library directories.
2062  *@details Loads all the FeatureData from the Training Library. The images in the sub-directories
2063  * specified by the 'TrainingClass' entries will be used as the primary source. Data from existing
2064  * FeatureData files will be used unless they are out of date. In that case the data will be
2065  * recomputed from the original images.<p>
2066  *
2067  * The 'ExampleFileName' A field that is in each 'FeatureVector' instance will reflect the sub-directory
2068  * from where it was retrieved. Between that and the 'rootDir' field you will be able to get the full
2069  * path to then original image.
2070  *
2071  *@param[out] latestImageTimeStamp Time-stamp of the most current image loaded.
2072  *@param[out] changesMadeToTrainingLibraries True if any image needed to have its features recalculated
2073  * or images were removed or added to a training directory.
2074  *@param[in] cancelFlag Will monitor this flag; if turns true will terminate the load and return.
2075  *@param[in] log Logging File.
2076  */
2077 FeatureVectorListPtr TrainingConfiguration2::LoadFeatureDataFromTrainingLibraries (DateTime& latestImageTimeStamp,
2078  bool& changesMadeToTrainingLibraries,
2079  VolConstBool& cancelFlag,
2080  RunLog& log
2081  )
2082 {
2083  log.Level (10) << "TrainingConfiguration2::LoadFeatureDataFromTrainingLibraries - Starting." << endl;
2084 
2085  bool errorOccured = false;
2086 
2087  FeatureVectorListPtr featureData = fvFactoryProducer->ManufacturFeatureVectorList (true, log);
2088 
2089  changesMadeToTrainingLibraries = false;
2090 
2091  //****************************************************************************
2092  // Make sure that there are no existing *.data files that we are going to use.
2093  // We need to do this in a separate pass because more than one entry may refer
2094  // to the same Class and hence the same *.data file.
2095 
2096 
2097  //***********************************************************
2098  // We will first extract the Raw features from each Class
2099 
2100  TrainingClassList::const_iterator tcIDX;
2101 
2102  DateTime latestTimeStamp;
2103  bool changesMadeToThisTrainingClass = false;
2104 
2105  for (tcIDX = trainingClasses.begin (); (tcIDX != trainingClasses.end () && (!cancelFlag) && (!errorOccured)); tcIDX++)
2106  {
2107  const TrainingClassPtr trainingClass = *tcIDX;
2108 
2109  log.Level (20) << "LoadFeatureDataFromTrainingLibraries Starting on Class[" << trainingClass->Name () << "]." << endl;
2110 
2111  FeatureVectorListPtr featureDataThisClass = ExtractFeatures (trainingClass, latestTimeStamp, changesMadeToThisTrainingClass, cancelFlag, log);
2112 
2113  if (!featureDataThisClass)
2114  {
2115  log.Level (-1) << endl
2116  << "Error Loading Feature data for class[" << trainingClass->Name () << "]." << endl
2117  << endl;
2118  errorOccured = true;
2119  }
2120  else
2121  {
2122  if (latestTimeStamp > latestImageTimeStamp)
2123  latestImageTimeStamp = latestTimeStamp;
2124 
2125  if (changesMadeToThisTrainingClass)
2126  changesMadeToTrainingLibraries = true;
2127 
2128  featureData->AddQueue (*featureDataThisClass);
2129  featureDataThisClass->Owner (false);
2130  }
2131  delete featureDataThisClass; featureDataThisClass = NULL;
2132  }
2133 
2134  if (NoiseTrainingClass () && (!cancelFlag) && (!errorOccured))
2135  {
2136  log.Level (30) << "LoadFeatureDataFromTrainingLibraries Loading Noise Class [" << NoiseTrainingClass ()->ExpandedDirectory (rootDir, 0) << "]" << endl;
2137  FeatureVectorListPtr noiseFeatureData = ExtractFeatures (NoiseTrainingClass (), latestTimeStamp, changesMadeToThisTrainingClass, cancelFlag, log);
2138  if (!noiseFeatureData)
2139  {
2140  log.Level (-1) << endl
2141  << "TrainingConfiguration2::LoadFeatureDataFromTrainingLibraries ***ERROR*** Error Loading feature data for Noise Images, Directory["
2142  << NoiseTrainingClass ()->ExpandedDirectory (rootDir, 0)
2143  << "]."
2144  << endl
2145  << endl;
2146  delete featureData; featureData = NULL;
2147  errorOccured = true;
2148  }
2149  else
2150  {
2151  if (latestTimeStamp > latestImageTimeStamp)
2152  latestImageTimeStamp = latestTimeStamp;
2153 
2154  if (changesMadeToThisTrainingClass)
2155  changesMadeToTrainingLibraries = true;
2156 
2157  featureData->AddQueue (*noiseFeatureData);
2158  noiseFeatureData->Owner (false);
2159  delete noiseFeatureData; noiseFeatureData = NULL;
2160  }
2161  }
2162 
2163  if (cancelFlag || errorOccured)
2164  {
2165  log.Level (-1) << "LoadFeatureDataFromTrainingLibraries ***ERROR*** CancelFlag or ErrorOcured set to 'true'." << endl;
2166  delete featureData;
2167  featureData = NULL;
2168  }
2169 
2170  log.Level (20) << "LoadFeatureDataFromTrainingLibraries Exiting" << endl;
2171  return featureData;
2172 } /* LoadFeatureDataFromTrainingLibraries */
2173 
2174 
2175 
2176 FeatureVectorListPtr TrainingConfiguration2::ExtractFeatures (const TrainingClassPtr trainingClass,
2177  DateTime& latestTimeStamp,
2178  bool& changesMade,
2179  VolConstBool& cancelFlag,
2180  RunLog& log
2181  )
2182 {
2183  log.Level (30) << "TrainingConfiguration2::ExtractFeatures - Extracting Features For Class["
2184  << trainingClass->Name () << "], into file["
2185  << trainingClass->FeatureFileName () << "]."
2186  << endl;
2187 
2188  FeatureVectorListPtr extractedExamples = fvFactoryProducer->ManufacturFeatureVectorList (true, log);
2189 
2190  FeatureFileIOPtr driver = NULL;
2191  if (fvFactoryProducer)
2192  driver = fvFactoryProducer->DefaultFeatureFileIO ();
2193 
2194  for (kkuint32 zed = 0; zed < trainingClass->DirectoryCount (); ++zed)
2195  {
2196  KKStr expandedDir = trainingClass->ExpandedDirectory (rootDir, zed);
2197  log.Level (30) << "ExtractFeatures Directory: " << expandedDir << endl;
2198  FeatureVectorListPtr extractedExamplesThisDir = driver->FeatureDataReSink
2199  (fvFactoryProducer,
2200  expandedDir,
2201  trainingClass->FeatureFileName (),
2202  trainingClass->MLClass (),
2203  true, // Make all entries in this directory 'trainingClass->MLClass ()'
2204  *mlClasses,
2205  cancelFlag,
2206  changesMade,
2207  latestTimeStamp,
2208  log
2209  );
2210  {
2211  // We now want to reset the ImageFileNames stored in each 'FeatureVector' instance so that it
2212  // reflects the sub-directory from where it was retrieved. Between that and the 'rootDir'
2213  // field you will be able to get the full path to then original image.
2214 
2215  KKStr subDirName = trainingClass->Directory (zed);
2216  if (!subDirName.Empty ())
2217  subDirName = osAddSlash (subDirName);
2218 
2219  FeatureVectorList::iterator idx;
2220  for (idx = extractedExamplesThisDir->begin (); idx != extractedExamplesThisDir->end (); ++idx)
2221  {
2222  FeatureVectorPtr fv = *idx;
2223  KKStr newFileName = subDirName + osGetRootNameWithExtension (fv->ExampleFileName ());
2224  fv->ExampleFileName (newFileName);
2225  }
2226  }
2227 
2228  extractedExamples->AddQueue (*extractedExamplesThisDir);
2229  extractedExamplesThisDir->Owner (false);
2230  delete extractedExamplesThisDir;
2231  extractedExamplesThisDir = NULL;
2232  }
2233 
2234  log.Level (30) << "ExtractFeatures Exiting" << endl;
2235  return extractedExamples;
2236 } /* ExtractFeatures */
2237 
2238 
2239 
2240 /**
2241  *@brief Determine the correct configuration file name.
2242  *@details
2243  *@code
2244  * If no extension then add ".cfg" to end of file name.
2245  *
2246  * if Path Provided
2247  * {
2248  * Return name as submitted with added extension.
2249  * }
2250  * else
2251  * {
2252  * a. If file exists in default directory; then return name with default directory path.
2253  * b. If file exists in Training Model Directory $(HomeDir) + "\\DataFiles\\TrainingModels"
2254  * then return with Training Model Directory.
2255  * c. Since not found then we will return name passed in with extension.
2256  * }
2257  *@endcode
2258  */
2260 {
2261  if (osFileExists (configFileName))
2262  return configFileName;
2263 
2264  KKStr rootNameEithExtension = osGetRootNameWithExtension (configFileName);
2265  KKStr extension = osGetFileExtension (configFileName);
2266  KKStr path = osGetPathPartOfFile (configFileName);
2267 
2268  KKStr configFileNameWithExtension = configFileName;
2269  if (extension.Empty ())
2270  {
2271  configFileNameWithExtension = osRemoveExtension (configFileName) + ".cfg";
2272  }
2273 
2274  if (!path.Empty ())
2275  {
2276  // Caller is telling us which directory to look in. In this case there is nothing to do
2277  return configFileNameWithExtension;
2278  }
2279 
2280  // See if file exists
2281  KKStr configFileNameInDefaultDirectory = osAddSlash (osGetCurrentDirectory ()) + configFileNameWithExtension;
2282  if (osFileExists (configFileNameInDefaultDirectory))
2283  return configFileNameInDefaultDirectory;
2284 
2285  KKStr configNameInTrainingModelDir = osAddSlash (KKMLVariables::TrainingModelsDir ()) + configFileNameWithExtension;
2286  if (osFileExists (configNameInTrainingModelDir))
2287  {
2288  return configNameInTrainingModelDir;
2289  }
2290 
2291  return configFileNameInDefaultDirectory;
2292 } /* GetEffectiveConfigFileName */
2293 
2294 
2295 
2296 bool TrainingConfiguration2::ConfigFileExists (const KKStr& _configFileName)
2297 {
2298  KKStr effectiveName = GetEffectiveConfigFileName (_configFileName);
2299  return osFileExists (effectiveName);
2300 } /* ConfigFileExists */
2301 
2302 
2303 
2304 void TrainingConfiguration2::DetermineWhatTheRootDirectoryIs ()
2305 {
2306  TrainingClassList::iterator idx;
2307 
2308  rootDir = "";
2309 
2310  if (trainingClasses.QueueSize () < 0)
2311  return;
2312 
2313  kkuint32 zed = 0;
2314 
2315  VectorKKStr rootDirParts = osSplitDirectoryPathIntoParts (trainingClasses[0].ExpandedDirectory (rootDir, 0));
2316  for (idx = trainingClasses.begin (); idx != trainingClasses.end (); idx++)
2317  {
2318  TrainingClassPtr tc = *idx;
2319 
2320  for (kkuint32 dirIdx = 0; dirIdx < tc->DirectoryCount (); ++dirIdx)
2321  {
2323 
2324  while (rootDirParts.size () > parts.size ())
2325  rootDirParts.pop_back ();
2326 
2327  zed = 0;
2328  while (zed < rootDirParts.size ())
2329  {
2330  if (!(rootDirParts[zed].EqualIgnoreCase (parts[zed])))
2331  break;
2332  zed++;
2333  }
2334 
2335  while (zed < rootDirParts.size ())
2336  rootDirParts.pop_back ();
2337  }
2338 }
2339 
2340 
2341 
2342 //***********************************************************************************
2343 // We need to update the 'trainingClasses' structure before the 'rootDir' variable.
2344 // This is because the following code that updates the 'TrainingClass' objects in
2345 // 'trainingClasses' will use the 'rootDir' variable in the 'ExpandedDirectory'
2346 // method.
2347 for (idx = trainingClasses.begin (); idx != trainingClasses.end (); idx++)
2348 {
2349  TrainingClassPtr tc = *idx;
2350 
2351  for (kkuint32 dirIdx = 0; dirIdx < tc->DirectoryCount (); ++dirIdx)
2352  {
2354 
2355  KKStr newTrainClassSubDir = "";
2356  for (zed = (kkuint32)rootDirParts.size (); zed < (kkuint32)parts.size (); zed++)
2357  newTrainClassSubDir << parts[zed];
2358  tc->Directory (dirIdx, newTrainClassSubDir);
2359  }
2360  }
2361 
2362  rootDir = "";
2363  for (zed = 0; zed < rootDirParts.size (); zed++)
2364  rootDir << rootDirParts[zed];
2365 } /* DetermineWhatTheRootDirectoryIs */
2366 
2367 
2368 
2369 const
2371  MLClassPtr class2
2372  ) const
2373 {
2374  const SVMparamPtr param = SVMparamToUse ();
2375  if (!param)
2376  return NULL;
2377 
2378  return param->GetParamtersToUseFor2ClassCombo (class1, class2);
2379 } /* BinaryClassParms */
2380 
2381 
2383  MLClassPtr class2
2384  )
2385 {
2386  const SVMparamPtr param = SVMparamToUse ();
2387  if (!param)
2388  return NULL;
2389 
2390  return param->GetBinaryClassParms (class1, class2);
2391 }
2392 
2393 
2394 TrainingConfiguration2Ptr TrainingConfiguration2List::LookUp (const KKStr& configFileName) const
2395 {
2396  KKStr rootName = KKB::osGetRootName (configFileName);
2397  TrainingConfiguration2List::const_iterator idx;
2398  for (idx = begin (); idx != end (); ++idx)
2399  {
2400  TrainingConfiguration2Ptr c = *idx;
2401  if (c->ConfigRootName ().EqualIgnoreCase (rootName))
2402  return c;
2403  }
2404  return NULL;
2405 }
2406 
2407 
2408 
2409 map<KKStr,TrainingConfiguration2::Factory*>* TrainingConfiguration2::registeredFactories = NULL;
2410 
2411 
2413 
2414 
2416 {
2417  if (factoryInstace)
2418  return factoryInstace;
2419 
2421  factoryInstace = new Factory ();
2422  RegisterFatory ("TrainingConfiguration2", factoryInstace );
2424  return factoryInstace;
2425 }
2426 
2427 
2428 
2429 TrainingConfiguration2Ptr TrainingConfiguration2::Manufacture
2430  (const KKStr& className,
2431  const KKStr& configFileName,
2432  bool validateDirectories,
2433  RunLog& log
2434  )
2435 {
2436  if (!registeredFactories)
2437  {
2438  log.Level (-1) << endl << "TrainingConfiguration2::Manufacture ***ERROR*** registeredFactories == NULL Will construct default 'TrainingConfiguration2' instance." << endl << endl;
2439  TrainingConfiguration2Ptr config = new TrainingConfiguration2 ();
2440  config->Load (configFileName, validateDirectories, log);
2441  return config;
2442  }
2443 
2445 
2446  TrainingConfiguration2Ptr newInstance = NULL;
2447 
2448  map<KKStr,Factory*>::const_iterator idx;
2449  idx = registeredFactories->find (className);
2450  if (idx == registeredFactories->end ())
2451  {
2452  log.Level (-1) << endl << "TrainingConfiguration2::Manufacture Factory: " << className << " Is not defined; will return instance of 'TrainingConfiguration2'." << endl << endl;
2453  newInstance = new TrainingConfiguration2 ();
2454  newInstance->Load (configFileName, validateDirectories, log);
2455  }
2456  else
2457  {
2458  newInstance = idx->second->Manufacture (configFileName, validateDirectories, log);
2459  }
2460 
2462  return newInstance;
2463 } /* Manufacture */
2464 
2465 
2466 
2468  Factory* factory
2469  )
2470 {
2472  if (!registeredFactories)
2473  {
2474  registeredFactories = new map<KKStr,Factory*> ();
2475  atexit (FinalCleanUp);
2476  }
2477 
2478  map<KKStr,Factory*>::const_iterator idx;
2479  idx = registeredFactories->find (className);
2480  if (idx == registeredFactories->end ())
2481  registeredFactories->insert (pair<KKStr,Factory*> (className, factory));
2482  else
2483  {
2484  cerr << endl << "TrainingConfiguration2::RegisterFatory ***ERROR*** 'TrainingConfiguration2::Factory with same name[" << className << "]" << endl << endl;
2485  }
2486 
2488 }
2489 
2490 
2491 
2492 TrainingConfiguration2Ptr TrainingConfiguration2::Factory::Manufacture
2493  (const KKStr& configFileName,
2494  bool validateDirectories,
2495  RunLog& log
2496  )
2497 {
2499  config->Load (configFileName, validateDirectories, log);
2500  return config;
2501 }
2502 
2503 
2504 
2505 void TrainingConfiguration2::FinalCleanUp ()
2506 {
2507  delete registeredFactories;
2508  registeredFactories = NULL;
2509 }
2510 
2511 
2512 
2513 void TrainingConfiguration2::WriteXMLFields (ostream& o) const
2514 {
2515  if (!configFileNameSpecified.Empty ())
2516  XmlElementKKStr::WriteXML (configFileNameSpecified, "ConfigFileNameSpecified", o);
2517 
2518  if (!configRootName.Empty ())
2519  XmlElementKKStr::WriteXML (configFileNameSpecified, "ConfigRootName", o);
2520 
2521  XmlElementInt32::WriteXML (examplesPerClass, "ExamplesPerClass", o);
2522 
2523  if (fvFactoryProducer)
2524  XmlElementKKStr::WriteXML (fvFactoryProducer->Name (), "FvFactoryProducer", o);
2525 
2526  XmlElementBool::WriteXML (fvFactoryProducerSpecified, "FvFactoryProducerSpecified", o);
2527 
2528  if (mlClasses)
2529  XmlElementMLClassNameList::WriteXML (*mlClasses, "MLClasses", o);
2530 
2531  XmlElementKKStr::WriteXML (Model::ModelTypeToStr (modelingMethod), "ModelingMethod", o);
2532 
2533  if (modelParameters)
2534  modelParameters->WriteXML ("ModelParameters", o);
2535 
2536  if (noiseMLClass)
2537  XmlElementKKStr::WriteXML (noiseMLClass->Name (), "NoiseMLClass", o);
2538 
2539  if (noiseTrainingClass)
2540  XmlElementTrainingClass::WriteXML (*noiseTrainingClass, "NoiseTrainingClass", o);
2541 
2542  if (otherClass)
2543  XmlElementKKStr::WriteXML (otherClass->Name (), "OtherClass", o);
2544 
2545  if (!rootDir.Empty ())
2546  XmlElementKKStr::WriteXML (rootDir, "RootDir", o);
2547 
2548  if (!rootDirExpanded.Empty ())
2549  XmlElementKKStr::WriteXML (rootDirExpanded, "RootDirExpanded", o);
2550 
2551  XmlElementBool::WriteXML (validateDirectories, "validateDirectories", o);
2552 
2553  trainingClasses.WriteXML ("TrainingClasses", o);
2554 
2555  if (subClassifiers)
2556  {
2557  VectorKKStr subClassifierList;
2558  TrainingConfiguration2List::const_iterator idx;
2559  for (idx = subClassifiers->begin (); idx != subClassifiers->end (); ++idx)
2560  {
2561  TrainingConfiguration2Ptr sc = *idx;
2562  subClassifierList.push_back (sc->ConfigFileNameSpecified ());
2563  }
2564  XmlElementVectorKKStr::WriteXML (subClassifierList, "subClassifiers", o);
2565  }
2566 } /* WriteXMLFields */
2567 
2568 
2569 
2570 void TrainingConfiguration2::WriteXML (const KKStr& varName,
2571  ostream& o
2572  ) const
2573 {
2574  XmlTag startTag ("TrainingConfiguration2", XmlTag::TagTypes::tagStart);
2575  if (!varName.Empty ())
2576  startTag.AddAtribute ("VarName", varName);
2577  startTag.WriteXML (o);
2578  o << endl;
2579 
2580  WriteXMLFields (o);
2581 
2582  XmlTag endTag ("TrainingConfiguration2", XmlTag::TagTypes::tagEnd);
2583  endTag.WriteXML (o);
2584  o << endl;
2585 } /* WriteXML */
2586 
2587 
2588 
2590  VolConstBool& cancelFlag,
2591  RunLog& log
2592  )
2593 {
2594  const KKStr& varName = t->VarName ();
2596  {
2597  bool tokenFound = true;
2598 
2599  XmlElementPtr e = dynamic_cast<XmlElementPtr> (t);
2600 
2601  const KKStr& varName = e->VarName ();
2602 
2603  if (typeid (*e) == typeid (XmlElementKKStr))
2604  {
2605  XmlElementKKStrPtr s = dynamic_cast<XmlElementKKStrPtr> (e);
2606  if (s && s->Value ())
2607  {
2608  KKStrConstPtr str = s->Value ();
2609  if (varName.EqualIgnoreCase ("ConfigFileNameSpecified"))
2610  configFileNameSpecified = *str;
2611 
2612  else if (varName.EqualIgnoreCase ("configRootName"))
2613  configRootName = *str;
2614 
2615  else if (varName.EqualIgnoreCase ("FvFactoryProducer"))
2616  fvFactoryProducer = FactoryFVProducer::LookUpFactory (*str);
2617 
2618  else if (varName.EqualIgnoreCase ("ModelingMethod"))
2619  modelingMethod = Model::ModelTypeFromStr (*str);
2620 
2621  else if (varName.EqualIgnoreCase ("NoiseMLClass"))
2622  noiseMLClass = MLClass::CreateNewMLClass (*str);
2623 
2624  else if (varName.EqualIgnoreCase ("otherClass"))
2625  otherClass = MLClass::CreateNewMLClass (*str);
2626 
2627  else if (varName.EqualIgnoreCase ("RootDir"))
2628  rootDir = *str;
2629 
2630  else if (varName.EqualIgnoreCase ("RootDirExpanded"))
2631  rootDirExpanded = *str;
2632 
2633  else
2634  tokenFound = false;
2635  }
2636  else
2637  {
2638  tokenFound = false;
2639  }
2640  }
2641 
2642  else if (varName.EqualIgnoreCase ("ExamplesPerClass"))
2643  {
2644  XmlElementInt32Ptr i = dynamic_cast<XmlElementInt32Ptr> (e);
2645  if (i)
2646  examplesPerClass = i->Value ();
2647  }
2648 
2649  else if (varName.EqualIgnoreCase ("MLClasses"))
2650  {
2651  XmlElementMLClassNameListPtr listOfClasses = dynamic_cast<XmlElementMLClassNameListPtr> (e);
2652  if (listOfClasses)
2653  {
2654  if (mlClassesWeOwnIt)
2655  delete mlClasses;
2656  mlClasses = listOfClasses->TakeOwnership ();
2657  mlClassesWeOwnIt = true;
2658  }
2659  }
2660 
2661  else if (varName.EqualIgnoreCase ("ModelParameters"))
2662  {
2663  /** KKKK
2664  modelParameters
2665  ***/
2666  }
2667 
2668  else if (varName.EqualIgnoreCase ("NoiseTrainingClass"))
2669  {
2670  XmlElementTrainingClassPtr ntc = dynamic_cast<XmlElementTrainingClassPtr> (e);
2671  if (ntc)
2672  {
2673  delete noiseTrainingClass;
2674  noiseTrainingClass = NULL;
2675  noiseTrainingClass = ntc->TakeOwnership ();
2676  }
2677  }
2678 
2679  else if (varName.EqualIgnoreCase ("FvFactoryProducerSpecified"))
2680  {
2681  XmlElementBoolPtr vBool = dynamic_cast<XmlElementBoolPtr> (e);
2682  if (vBool)
2683  fvFactoryProducerSpecified = vBool->Value ();
2684  }
2685 
2686  else if (varName.EqualIgnoreCase ("ValidateDirectories"))
2687  {
2688  XmlElementBoolPtr vd = dynamic_cast<XmlElementBoolPtr> (e);
2689  if (vd)
2690  validateDirectories = vd->Value ();
2691  }
2692 
2693  else if (varName.EqualIgnoreCase ("TrainingClasses"))
2694  {
2695  XmlElementTrainingClassListPtr tcl = dynamic_cast<XmlElementTrainingClassListPtr> (e);
2696  if (tcl)
2697  {
2698  TrainingClassListPtr xmlTrainClasses = tcl->TakeOwnership ();
2699  if (xmlTrainClasses)
2700  {
2701  trainingClasses.DeleteContents ();
2702  while (xmlTrainClasses->QueueSize () > 0)
2703  {
2704  TrainingClassPtr tc = xmlTrainClasses->PopFromBack ();
2705  trainingClasses.PushOnFront (tc);
2706  }
2707  delete xmlTrainClasses;
2708  xmlTrainClasses = NULL;
2709  }
2710  }
2711  }
2712 
2713  else if (varName.EqualIgnoreCase ("SubClassifiers"))
2714  {
2715  XmlElementVectorKKStrPtr sc = dynamic_cast<XmlElementVectorKKStrPtr> (e);
2716  if (sc)
2717  {
2718  delete subClassifierNameList;
2719  subClassifierNameList = sc->TakeOwnership ();
2720  }
2721  }
2722 
2723  else
2724  {
2725  tokenFound = false;
2726  }
2727 
2728  if (tokenFound)
2729  {
2730  delete t;
2731  t = NULL;
2732  }
2733  }
2734 
2735  return t;
2736 } /* ReadXMLBaseToken */
2737 
2738 
2739 
2741  RunLog& log
2742  )
2743 {
2744  if (!fvFactoryProducer)
2745  fvFactoryProducer = DefaultFeatureVectorProducer (log);
2746 
2747  fileDesc = fvFactoryProducer->FileDesc ();
2748 
2749  TrainingClassList::iterator idx;
2750  for (idx = trainingClasses.begin (); (idx != trainingClasses.end ()) && (!cancelFlag); ++idx)
2751  {
2752  TrainingClassPtr tc = *idx;
2754  {
2755  bool errorsFound = false;
2756 
2757  TrainingConfiguration2Ptr subClassifeir =
2758  ValidateSubClassifier (tc->SubClassifierName (), errorsFound, log);
2759  tc->SubClassifier (subClassifeir);
2760  }
2761  }
2762 } /* ReadXMLPost */
2763 
2764 
2765 
2767  XmlTagConstPtr tag,
2768  VolConstBool& cancelFlag,
2769  RunLog& log
2770  )
2771 
2772 {
2773  fileDesc = NULL;
2774  fvFactoryProducer = NULL;
2775  if (mlClassesWeOwnIt)
2776  delete mlClasses;
2777  mlClasses = NULL;
2778  otherClass = NULL;
2779  delete noiseTrainingClass; noiseTrainingClass = NULL;
2780  delete subClassifiers; subClassifiers = NULL;
2781  trainingClasses.DeleteContents ();
2782 
2783  VectorKKStr* subClassifierNameList = NULL;
2784 
2785  XmlTokenPtr t = s.GetNextToken (cancelFlag, log);
2786  while (t && (!cancelFlag))
2787  {
2788  t = ReadXMLBaseToken (t, cancelFlag, log);
2789  delete t;
2790  if (cancelFlag)
2791  t = NULL;
2792  else
2793  t = s.GetNextToken (cancelFlag, log);
2794  }
2795  delete t;
2796  t = NULL;
2797  if (!cancelFlag)
2798  ReadXMLPost (cancelFlag, log);
2799 } /* ReadXML */
2800 
2801 
2802 XmlFactoryMacro(TrainingConfiguration2)
const KKStr & FeatureFileName() const
Definition: TrainingClass.h:69
bool operator>(const DateTime &right) const
Definition: DateTime.cpp:1255
virtual void Load(const KKStr &_configFileName, bool _validateDirectories, RunLog &log)
XmlTag(const KKStr &_name, TagTypes _tagType)
Definition: XmlStream.cpp:586
void ExampleFileName(const KKStr &_exampleFileName)
Name of source of feature vector, ex: file name of image that the feature vector was computed from...
Definition: FeatureVector.h:75
Base class to all Learning Algorithms.
Definition: Model.h:82
MLClass * MLClassPtr
Definition: MLClass.h:46
void AddQueue(const FeatureVectorList &examplesToAdd)
Add the contents of &#39;examplesToAdd&#39; to the end of this list.
void FeatureFileName(const KKStr &_featureFileName)
Definition: TrainingClass.h:85
virtual double Gamma() const
Definition: ModelParam.cpp:187
virtual const svm_parameter & Param() const
bool EqualIgnoreCase(const char *s2) const
Definition: KKStr.cpp:1257
virtual KKStr ToCmdLineStr() const
Creates a a Command Line String that represents these parameters.
Definition: ModelParam.cpp:367
static TrainingConfiguration2 * CreateFromDirectoryStructure(const KKStr &_existingConfigFileName, const KKStr &_subDir, FactoryFVProducerPtr _fvFactoryProducer, RunLog &_log, bool &_successful, KKStr &_errorMessage)
Will create a instance using a sub-directory tree to drive the TraningClassList.
const BinaryClassParmsListPtr BinaryParmsList() const
KKStr osRemoveExtension(const KKStr &_fullFileName)
SVM_SelectionMethod
Definition: SVMparam.h:34
__int32 kkint32
Definition: KKBaseTypes.h:88
SVM_KernalType
Definition: SVMparam.h:54
void SetBinaryClassFields(MLClassPtr class1, MLClassPtr class2, const SVM233::svm_parameter &_param, const FeatureNumList &_features, float _weight)
static KKStr ModelTypeToStr(ModelTypes _modelType)
bool osValidDirectory(const KKStr &_name)
Definition: OSservices.cpp:398
const KKStr & ConfigRootName() const
const BinaryClassParmsPtr GetParamtersToUseFor2ClassCombo(MLClassPtr class1, MLClassPtr class2) const
KKStr osGetPathPartOfFile(KKStr fullFileName)
Get the path part of a full file name specification.
TrainingClassPtr LocateByMLClassName(const KKStr &className)
static KKStr TrainingModelsDir()
KKStr & TrimRight(const char *whiteSpaceChars="\n\r\t ")
Definition: KKStr.cpp:1695
bool Value() const
Definition: XmlStream.cpp:1028
decision_function svm_train_one(const svm_problem *prob, const svm_parameter *param, double Cp, double Cn, std::set< kkint32 > &BSVIndex)
Definition: svm.cpp:3154
void AddATrainingClass(TrainingClassPtr _trainClass)
Adds specified Training Class to list taking ownership of it.
Keeps track of selected features.
virtual double C_Param() const
Definition: ModelParam.cpp:177
FeatureNumList(FileDescPtr _fileDesc)
const KKStr & Directory(kkuint32 idx) const
TrainingConfiguration2Ptr GenerateAConfiguraionForAHierarchialLevel(kkuint32 level, RunLog &log) const
SVM_MachineType
Definition: SVMparam.h:26
TrainingClassPtr LocateByDirectory(const KKStr &directory)
virtual void ExamplesPerClass(kkint32 _examplesPerClass)
Definition: ModelParam.h:129
TrainingClass(const VectorKKStr &_directories, KKStr _name, float _weight, float _countFactor, TrainingConfiguration2Ptr _subClassifier, MLClassList &_mlClasses)
Constructor, Creates a new instance of TrainingClass and populates fields with respective data from p...
void BuildTrainingClassListFromDirectoryStructure(const KKStr &_subDir, bool &_successful, KKStr &_errorMessage, RunLog &_log)
XmlElementBool * XmlElementBoolPtr
Definition: XmlStream.h:524
SVM_EncodingMethod EncodingMethod() const
MLClassListPtr ExtractListOfClasses() const
void ReadXMLPost(VolConstBool &cancelFlag, RunLog &log)
unsigned __int16 kkuint16
16 bit unsigned integer.
Definition: KKBaseTypes.h:86
KKStr & operator=(const char *src)
Definition: KKStr.cpp:1442
Represents a "Class" in the Machine Learning Sense.
Definition: MLClass.h:52
void SetModelParameters(ModelParamPtr _svmParanters, kkint32 _examplesPerClass)
static void WriteXML(const MLClassList &mlClassList, const KKStr &varName, std::ostream &o)
Definition: MLClass.cpp:1499
void WriteXMLFields(std::ostream &o) const
To be used by both Base Class and Derived classes to write fields that are specific to &#39;TrainingConfi...
BinaryClassParmsPtr GetParamtersToUseFor2ClassCombo(MLClassPtr class1, MLClassPtr class2)
Definition: SVMparam.cpp:394
FeatureNumList AllFeatures()
Will return a FeatureNumList instance with all features selected.
void SetFeatureNums(const FeatureNumList &features)
kkint32 ToInt() const
Definition: KKStr.cpp:3565
const FileDescPtr FileDesc() const
TrainingConfiguration2 * TrainingConfiguration2Ptr
SVM_KernalType KernalType() const
Definition: SVMparam.h:149
virtual bool NormalizeNominalFeatures() const
Definition: ModelParam.h:115
bool operator==(const char *rtStr) const
Definition: KKStr.cpp:1588
static KKStr GetClassNameFromDirName(const KKStr &subDir)
Definition: MLClass.cpp:372
static FactoryFVProducerPtr LookUpFactory(const KKStr &name)
Returns pointer to existing instance of &#39;FactoryFVProducer&#39; that was previously registered with &#39;name...
virtual void EncodingMethod(EncodingMethodType _encodingMethod)
Definition: ModelParam.h:128
void SetTrainingClasses(TrainingClassListPtr _trainingClasses)
virtual MLClassPtr LookUpByName(const KKStr &_name) const
Returns a pointer of MLClass object with name (_name); if none in list will then return NULL...
Definition: MLClass.cpp:830
KKStrListPtr osGetListOfImageFiles(KKStr fileSpec)
XmlElementVectorKKStr * XmlElementVectorKKStrPtr
Definition: XmlStream.h:675
SVMparam * SVMparamPtr
Definition: SVMparam.h:286
virtual void WriteXML(const KKStr &varName, std::ostream &o) const =0
SVM_EncodingMethod
Definition: SVMparam.h:46
TrainingConfiguration2Ptr LookUp(const KKStr &rootName) const
Returns the instance that has the same root name as &#39;rootName&#39; if none found returns NULL...
virtual SVM_MachineType MachineType() const
void Number_of_rounds(int _number_of_rounds)
virtual void C_Param(MLClassPtr class1, MLClassPtr class2, double cParam)
static void WriteXML(const bool b, const KKStr &varName, std::ostream &o)
Definition: XmlStream.cpp:1035
KKStr operator+(const char *right) const
Definition: KKStr.cpp:3986
virtual void Save(std::ostream &o) const
bool EqualIgnoreCase(const KKStr &s2) const
Definition: KKStr.cpp:1250
SVM_EncodingMethod EncodingMethod() const
Definition: SVMparam.h:143
FeatureVectorListPtr LoadFeatureDataFromTrainingLibraries(KKB::DateTime &latestImageTimeStamp, bool &changesMadeToTrainingLibraries, VolConstBool &cancelFlag, RunLog &log)
Load training data from the training library directories.
kkuint32 DirectoryCount() const
XmlToken * XmlTokenPtr
Definition: XmlStream.h:18
void MachineType(SVM_MachineType _machineType)
void SetBinaryClassFields(MLClassPtr class1, MLClassPtr class2, const svm_parameter &_param, FeatureNumListConstPtr _features, float _weight)
unsigned __int32 kkuint32
Definition: KKBaseTypes.h:89
virtual ModelParamPtr Duplicate() const =0
KKStr osGetFileExtension(KKStr fullFileName)
const SVMparam & SVMparamREF(RunLog &log) const
KKStr ExpandedDirectory(const KKStr &rootDir, kkuint32 idx)
BinaryClassParmsPtr GetBinaryClassParms(MLClassPtr class1, MLClassPtr class2)
void KernalType(SVM_KernalType _kernalType)
Definition: SVMparam.h:185
KKStr & operator=(KKStr &&src)
Definition: KKStr.cpp:1369
virtual FactoryFVProducerPtr DefaultFeatureVectorProducer(RunLog &runLog) const
Container class for FeatureVector derived objects.
KKB::KKStr osAddSlash(const KKStr &fileSpec)
void SelectionMethod(SVM_SelectionMethod _selectionMethod)
void MLClass(MLClassPtr _mlClass)
Definition: TrainingClass.h:86
KKTHread * KKTHreadPtr
svm_parameter(KKStr &paramStr)
Definition: svm.cpp:983
static TrainingConfiguration2 * CreateFromFeatureVectorList(FeatureVectorList &_examples, FileDescPtr _fileDesc, const KKStr &_parameterStr, RunLog &_log)
FeatureNumListConstPtr GetFeatureNums(FileDescPtr fileDesc, MLClassPtr class1, MLClassPtr class2) const
KKStr operator+(const char *left, const KKStr &right)
Definition: KKStr.cpp:3976
float AvgNumOfFeatures(FeatureVectorListPtr trainExamples) const
void ModelParameters(ModelParamPtr _modelParameters)
void ImagesPerClass(kkint32 _imagesPerClass)
virtual void Gamma(double _gamma)
Definition: ModelParam.cpp:219
FeatureNumList * FeatureNumListPtr
XmlElementTrainingClass * XmlElementTrainingClassPtr
KKStr(const KKStr &str)
Copy Constructor.
Definition: KKStr.cpp:561
XmlElement * XmlElementPtr
Definition: XmlStream.h:21
void AddAtribute(const KKStr &attributeName, const KKStr &attributeValue)
Definition: XmlStream.cpp:602
void AddATrainingClass(MLClassPtr _newClass)
Will assume that images for this class will be saved off the RootDirectory using its own name for the...
void SetFeatureNums(MLClassPtr class1, MLClassPtr class2, const FeatureNumList &_features, float _weight=-1)
void AddBinaryClassParms(MLClassPtr class1, MLClassPtr class2, const svm_parameter &_param, FeatureNumListConstPtr _selectedFeatures, float _weight)
Add a Binary parameters using svm_parametr cmd line str. Typically used by TrainingConfiguration.
FeatureFileIO * FeatureFileIOPtr
Definition: FileDesc.h:45
virtual FeatureVectorListPtr ManufacturFeatureVectorList(bool owner, RunLog &runLog) const
Manufactures a instance of a derived &#39;FeatureVectorList&#39; class that is appropriate for containing ins...
virtual float A_Param() const
Definition: ModelParam.cpp:172
void SetFeatureNums(MLClassPtr class1, MLClassPtr class2, FeatureNumListConstPtr _features, float _weight=-1)
void TrimLeft(const char *whiteSpaceChars="\n\r\t ")
Definition: KKStr.cpp:1745
static bool ConfigFileExists(const KKStr &_configFileName)
bool Empty() const
Definition: KKStr.h:241
virtual SVM_SelectionMethod SelectionMethod() const
virtual FeatureNumListConstPtr SelectedFeatures() const
Definition: ModelParam.h:116
XmlTag const * XmlTagConstPtr
Definition: KKStr.h:45
void WriteXML(const KKStr &varName, std::ostream &o) const
virtual ModelParamTypes ModelParamType() const =0
MLClassListPtr TakeOwnership()
Definition: MLClass.cpp:1491
Manages the reading and writing of objects in a simple XML format. For a class to be supported by Xml...
Definition: XmlStream.h:46
VectorKKStr osSplitDirectoryPathIntoParts(const KKStr &path)
virtual void ReadXML(XmlStream &s, XmlTagConstPtr tag, VolConstBool &cancelFlag, RunLog &log)
This class encapsulates are the information necessary to build a UsfCasCor class. ...
void SetAllFeatures(FileDescPtr fileDesc)
Selects all features except those flagged as &#39;IgnoreAttribute&#39; in the associated FileDesc.
virtual float AvgMumOfFeatures() const
Definition: ModelParam.cpp:99
static KKStr GetEffectiveConfigFileName(const KKStr &configFileName)
Determine the correct configuration file name.
BinaryClassParmsPtr GetBinaryClassParms(MLClassPtr class1, MLClassPtr class2)
Definition: SVMparam.cpp:423
TrainingConfiguration2(MLClassListPtr _mlClasses, FactoryFVProducerPtr _fvFactoryProducer, const KKStr &_parameterStr, RunLog &_log)
Use this one if you want to create a default Configuration object.
void SubClassifier(TrainingConfiguration2Ptr _subClassifier)
Definition: TrainingClass.h:87
static KKStr Concat(const std::vector< std::string > &values)
Concatenates the list of &#39;std::string&#39; strings.
Definition: KKStr.cpp:1082
void Upper()
Converts all characters in string to their Upper case equivalents via &#39;toupper&#39;.
Definition: KKStr.cpp:2461
void ExamplesPerClass(kkint32 _examplesPerClass)
void Number_of_rounds(kkint32 _number_of_rounds)
static const KKStr & EmptyStr()
Static method that returns an Empty String.
Definition: KKStr.cpp:3453
FeatureNumList GetFeatureNums(MLClassPtr class1, MLClassPtr class2)
Returns features selected for the specified class-pairIf none were specified for that pair will retur...
double C_Param(MLClassPtr class1, MLClassPtr class2) const
General purpose Configuration File manager class.
Definition: Configuration.h:45
XmlElementTrainingClassList * XmlElementTrainingClassListPtr
KKStr DirectoryPathForClass(MLClassPtr mlClass) const
Fully expanded directory path for specified class.
This class encapsulates are the information necessary to build a SVMModel class.
Definition: SVMparam.h:74
static void RegisterFatory(const KKStr &className, Factory *factory)
void RootDir(const KKStr &_rootDir)
const TrainingClassList & TrainingClasses() const
MLClassListPtr ExtractClassList() const
static FeatureNumList AllFeatures(FileDescPtr fileDesc)
Create a FeatureNumList object where all features are selected, except ones that are flagged as Ignor...
KKStr osGetRootNameOfDirectory(KKStr fullDirName)
FeatureNumList(kkuint32 _maxFeatureNum)
virtual const KKStr & VarName() const
Definition: XmlStream.cpp:794
KKStr StrFormatInt(kkint32 val, const char *mask)
Definition: KKStr.cpp:5004
virtual void SelectedFeatures(FeatureNumListConst &_selectedFeatures)
Definition: ModelParam.cpp:109
const KKStr & Name() const
Definition: MLClass.h:154
KKStr(const char *str)
Definition: KKStr.cpp:537
virtual void SelectionMethod(SVM_SelectionMethod _selectionMethod)
const KKStr & Name() const
std::ostream &__cdecl operator<<(std::ostream &os, const KKStr &str)
FeatureVectorListPtr LoadOtherClasssExamples(RunLog &runLog)
ModelParamPtr ModelParameters() const
KKStr operator+(const KKStr &right) const
Definition: KKStr.cpp:3998
TrainingConfiguration2Ptr SubClassifier() const
Definition: TrainingClass.h:72
const MLClassPtr MLClass() const
Definition: TrainingClass.h:70
TrainingClassList * TrainingClassListPtr
static MLClassPtr CreateNewMLClass(const KKStr &_name, kkint32 _classId=-1)
Static method used to create a new instance of a MLClass object.
Definition: MLClass.cpp:100
KKB::KKStr osSubstituteInEnvironmentVariables(const KKStr &src)
Substitute in the value of the environment variables into &#39;src&#39;.
Definition: OSservices.cpp:977
void EncodingMethod(SVM_EncodingMethod _encodingMethod)
virtual TrainingConfiguration2Ptr Duplicate() const
SVM_SelectionMethod SelectionMethod() const
virtual void MachineType(SVM_MachineType _machineType)
MLClassList(const MLClassList &_mlClasses)
Copy constructor; will copy list but not own the contents.
Definition: MLClass.cpp:570
Specify where training examples and other related data for a MLClass that is needed to train a classi...
Definition: TrainingClass.h:38
virtual TrainingConfiguration2Ptr Manufacture(const KKStr &_configFileName, bool _validateDirectories, RunLog &_log)
TrainingConfiguration2(const TrainingConfiguration2 &tc)
void Directory(kkuint32 idx, const KKStr &directory)
virtual TrainingConfiguration2Ptr ManufacturTrainingConfiguration() const
Returns a &#39;TrainingConfiguration2&#39; derived instance.
float AvgNumOfFeatures(FeatureVectorListPtr trainExamples) const
Returns back the class weighted average number of features per training example.
Definition: SVMparam.cpp:508
bool osFileExists(const KKStr &_fileName)
Definition: OSservices.cpp:568
KKStrListPtr osGetListOfDirectories(KKStr fileSpec)
FeatureNumList(const KKStr &_featureListStr, bool &_valid)
Constructs a &#39;FeatureNumList&#39; instance from a string that contains a list of selected features...
void Append(const KKStr &str)
Definition: KKStr.cpp:1887
XmlElementKKStr * XmlElementKKStrPtr
Definition: XmlStream.h:670
TrainingConfiguration2(MLClassListPtr _mlClasses, FileDescPtr _fileDesc, const KKStr &_parameterStr, RunLog &_log)
Use this one if you want to create a default Configuration object.
virtual kkint32 NumOfFeaturesAfterEncoding(FileDescPtr fileDesc, RunLog &log) const
Definition: ModelParam.cpp:387
void WriteXML(std::ostream &o)
Definition: XmlStream.cpp:723
FeatureNumListConst * FeatureNumListConstPtr
KKStr & operator=(const KKStr &src)
Definition: KKStr.cpp:1390
Used for logging messages.
Definition: RunLog.h:49
void EncodeProblem(const struct svm_paramater &param, struct svm_problem &prob_in, struct svm_problem &prob_out)
bool StartsWith(const KKStr &value) const
Definition: KKStr.cpp:1137
MLClassList * MLClassListPtr
Definition: MLClass.h:49
KKStr osGetCurrentDirectory()
Definition: OSservices.cpp:319
const TrainingClassPtr NoiseTrainingClass() const
MLClassListPtr ExtractFullHierachyOfClasses() const
void UnDefined(bool _unDefined)
Definition: MLClass.h:184
const KKStr & SubClassifierName() const
Definition: TrainingClass.h:73
virtual TokenTypes TokenType()=0
Responsible for creating a FeatureFectorProducer instance.
KKStr osGetRootNameWithExtension(const KKStr &fullFileName)
static TrainingConfiguration2Ptr Manufacture(const KKStr &_className, const KKStr &_configFileName, bool _validateDirectories, RunLog &_log)
virtual double C_Param(MLClassPtr class1, MLClassPtr class2) const
static GrayScaleImagesFVProducerFactory * Factory(RunLog *runLog)
Returns instance of "GrayScaleImagesFVProducerFactory" that is registered with "FactoryFVProducer::Re...
TrainingConfiguration2(MLClassListPtr _mlClasses, FileDescPtr _fileDesc, ModelParamPtr _modelParameters, RunLog &_log)
Creates a configuration file using the parameters specified in &#39;_modelParameters&#39;; does not read from...
svm_parameter & operator=(const svm_parameter &right)
Definition: svm.cpp:828
float ToFloat() const
Definition: KKStr.cpp:3553
virtual XmlTokenPtr GetNextToken(VolConstBool &cancelFlag, RunLog &log)
Definition: XmlStream.cpp:116
void ParseCmdLine(KKStr _cmdLineStr, bool &_validFormat, RunLog &_log)
KKException(const KKStr &_exceptionStr)
Definition: KKException.cpp:45
virtual void A_Param(float _prob)
Definition: ModelParam.cpp:201
svm_parameter(const svm_parameter &parameters)
Definition: svm.cpp:768
Maintains a list of MLClass instances.
Definition: MLClass.h:233
static ModelTypes ModelTypeFromStr(const KKStr &_modelTypeStr)
const VectorKKStr & Directories() const
Definition: TrainingClass.h:68
MLClassListPtr ExtractListOfClassesForAGivenHierarchialLevel(kkuint32 level) const
virtual void C_Param(double _cost)
Definition: ModelParam.cpp:207
Will only write the ClassName rather than complete MLClass instances.
Definition: MLClass.h:580
XmlTokenPtr ReadXMLBaseToken(XmlTokenPtr t, VolConstBool &cancelFlag, RunLog &log)
virtual FeatureVectorListPtr FeatureDataReSink(FactoryFVProducerPtr _fvProducerFactory, const KKStr &_dirName, const KKStr &_fileName, MLClassPtr _unknownClass, bool _useDirectoryNameForClassName, MLClassList &_mlClasses, VolConstBool &_cancelFlag, bool &_changesMade, KKB::DateTime &_timeStamp, RunLog &_log)
Synchronizes the contents of a feature data file with a directory of images.
void KernalType(SVM_KernalType _kernalType)
#define int32_max
Definition: KKBaseTypes.h:119
Maintains one instance of a GoalKeeper object that can be used anywhere in the application.
Abstract Base class for Machine Learning parameters.
Definition: ModelParam.h:35
MLClassPtr MLClassForGivenHierarchialLevel(KKB::kkuint16 level) const
Definition: MLClass.cpp:427
TrainingClass * TrainingClassPtr
virtual FileDescPtr FileDesc() const =0
virtual kkint32 ExamplesPerClass() const
Definition: ModelParam.h:113
virtual const KKStr & VarName() const
Definition: XmlStream.h:269
#define XmlFactoryMacro(NameOfClass)
Definition: XmlStream.h:688
void C_Param(MLClassPtr class1, MLClassPtr class2, double cParam)
void EmptyTrainingClasses()
Removes all training classes from the configuration; example use would be to remove all classes and t...
kkint32 NumOfFeaturesAfterEncoding(RunLog &log) const
TrainingClassList * DuplicateListAndContents() const
const KKStr & ExampleFileName() const
Name of file that this FeatureVector was computed from.
virtual SVMparamPtr SvmParameters() const
virtual bool ValidParam() const
Definition: ModelParam.h:117
KKStr osGetRootName(const KKStr &fullFileName)
XmlElementMLClassNameList * XmlElementMLClassNameListPtr
Definition: MLClass.h:603
DateTime & operator=(const DateTime &right)
Definition: DateTime.cpp:1231
FactoryFVProducerPtr FvFactoryProducer(RunLog &log) const
virtual void ParseCmdLine(KKStr _cmdLineStr, bool &_validFormat, RunLog &_log)
Definition: ModelParam.cpp:234
virtual FeatureFileIOPtr DefaultFeatureFileIO() const =0
virtual void Save(const KKStr &fileName) const
volatile const bool VolConstBool
Definition: KKBaseTypes.h:163