34 using namespace KKMLL;
71 Model (_name
, _param
, _factoryFVProducer
),
127 return memoryConsumedEstimated;
139 result <<
" " << config1->ModelTypeStr () +
"(" + osGetRootName (config1->FileName ()) +
")";
144 result <<
" " << config2->ModelTypeStr () +
"(" + osGetRootName (config2->FileName ()) +
")";
178 bool _alreadyNormalized,
184 _log.Level (10) <<
"ModelDual::TrainModel Model[" << param->FileName () <<
"] _trainExamples->size()[" << _trainExamples->size() <<
"]" << endl;
189 KKStr errMsg =
"ModelDual::TrainModel (param == NULL)";
190 _log.Level (-1) << endl << errMsg << endl << endl;
203 KKStr errMsg =
"ModelDual::TrainModel ***ERROR*** Exception occurred calling 'Model::TrainModel'.";
204 _log.Level (-1) << endl << errMsg << endl << e.ToString () << endl << endl;
207 catch (
const exception& e2)
210 KKStr errMsg =
"ModelDual::TrainModel ***ERROR*** Exception occurred calling 'Model::TrainModel'.";
211 _log.Level (-1) << endl << errMsg << endl << e2.what () << endl << endl;
217 KKStr errMsg =
"ModelDual::TrainModel ***ERROR*** Exception occurred calling 'Model::TrainModel'.";
218 _log.Level (-1) << endl << errMsg << endl << endl;
235 _log.Level (-1) << endl << errMsg << endl << endl;
243 _log.Level (-1) << endl << errMsg << endl << endl;
253 if (!config1->FormatGood ())
256 KKStr errMsg =
"ModelDual::TrainModel ***ERROR*** Configuration[" + param->ConfigFileName1 () +
"] is not valid.";
257 _log.Level (-1) << endl << errMsg << endl << endl;
258 throw KKException (errMsg);
266 if (!config2->FormatGood ())
269 KKStr errMsg =
"ModelDual::TrainModel ***ERROR*** Configuration[" + param->ConfigFileName2 () +
"] is not valid.";
270 _log.Level (-1) << endl << errMsg << endl << endl;
271 throw KKException (errMsg);
291 _log.Level (-1) << endl << errMsg << endl << endl;
310 _log.Level (-1) << endl << errMsg << endl << endl;
340 log.Level (-1) <<
"ModelDual::ReconcilePredictions ***WARNING*** Classifier[" << param->ConfigFileName1 () <<
"] nor Classifier[" << param->ConfigFileName2 () <<
"] return predictions." << endl;
345 log.Level (-1) <<
"ModelDual::ReconcilePredictions ***WARNING*** Classifier[" << param->ConfigFileName1 () <<
"] did not return a prediction." << endl;
353 log.Level (-1) <<
"ModelDual::ReconcilePredictions ***WARNING*** Classifier[" << param->ConfigFileName2 () <<
"] did not return a prediction." << endl;
361 kkint32 maxLen = Min (name1.Len (), name2.Len ());
368 if (name1Token
== name2Token)
372 commonPart
+= name1Token;
380 if (commonPart
.Len () < 1)
397 MLClassPtr predClass,
399 double& predClassProb,
409 ClassProbList::iterator idx;
410 for (idx = predictions->begin (); idx != predictions->end (); ++idx)
436 log.Level (-1) << endl << endl <<
"ModelDual::Predict ***ERROR*** Both Classifiers are not defined." << endl << endl;
440 bool newExampleCreated =
false;
442 MLClassPtr pred1 = NULL;
443 MLClassPtr pred2 = NULL;
450 if (newExampleCreated)
452 delete encodedExample;
453 encodedExample = NULL;
463 MLClassPtr knownClass,
464 MLClassPtr& predClass1,
465 MLClassPtr& predClass2,
468 double& probOfKnownClass,
469 double& predClass1Prob,
470 double& predClass2Prob,
472 bool& knownClassOneOfTheWinners,
479 predClass1 = predClass2 = NULL;
480 log.Level (-1) << endl << endl <<
"ModelDual::Predict ***ERROR*** Both Classifiers are not defined." << endl << endl;
484 MLClassPtr predClass1C1 = NULL;
485 MLClassPtr predClass2C1 = NULL;
488 double probOfKnownClassC1 = 0.0;
489 double predClass1ProbC1 = 0.0;
490 double predClass2ProbC1 = 0.0;
492 bool knownClassOneOfTheWinnersC1 =
false;
493 double breakTieC1 = 0.0;
495 MLClassPtr predClass1C2 = NULL;
496 MLClassPtr predClass2C2 = NULL;
499 double probOfKnownClassC2 = 0.0;
500 double predClass1ProbC2 = 0.0;
501 double predClass2ProbC2 = 0.0;
503 bool knownClassOneOfTheWinnersC2 =
false;
504 double breakTieC2 = 0.0;
506 bool newExampleCreated =
false;
512 predClass1C1
, predClass2C1
, 513 predClass1VotesC1
, predClass2VotesC1
, 515 predClass1ProbC1
, predClass2ProbC1
, 521 predClass1C2
, predClass2C2
, 522 predClass1VotesC2
, predClass2VotesC2
, 524 predClass1ProbC2
, predClass2ProbC2
, 532 if (predClass1C1 != predClass1C2)
550 if (predClass2C1 != predClass2C2)
567 predClass1Prob = (predClass1ProbC1 + predClass1ProbC2) / 2.0;
568 predClass2Prob = (predClass2ProbC1 + predClass2ProbC2) / 2.0;
569 predClass1Votes = (
kkint32)((0.5f + predClass1VotesC1 + predClass1VotesC2) / 2.0f);
570 predClass2Votes = (
kkint32)((0.5f + predClass2VotesC1 + predClass2VotesC2) / 2.0f);
573 probOfKnownClass = (probOfKnownClassC1 + probOfKnownClassC2) / 2.0;
574 breakTie = (breakTieC1 + breakTieC2) / 2.0;
575 numOfWinners = (numOfWinnersC1 + numOfWinnersC2) / 2;
576 knownClassOneOfTheWinners = (knownClass == predClass1C1) || (knownClass == predClass1C2);
578 if (newExampleCreated)
580 delete encodedExample;
581 encodedExample = NULL;
597 log.Level (-1) << endl << endl <<
"ModelDual::ProbabilitiesByClass ***ERROR*** Both Classifiers are not defined." << endl << endl;
604 if (predictions1 == NULL)
607 else if (predictions2 == NULL)
610 ClassProbList::iterator idx;
611 for (idx = predictions2->begin (); idx != predictions2->end (); ++idx)
629 KKStr& classifier1Desc,
630 KKStr& classifier2Desc,
636 delete classifier1Results; classifier1Results = NULL;
637 delete classifier2Results; classifier2Results = NULL;
641 log.Level (-1) << endl << endl <<
"ModelDual::ProbabilitiesByClassDual ***ERROR*** Both Classifiers are not defined." << endl << endl;
649 bool newExampleCreated =
false;
652 if (newExampleCreated)
654 delete encodedExample;
655 encodedExample = NULL;
660 bool newExampleCreated =
false;
663 if (newExampleCreated)
665 delete encodedExample;
666 encodedExample = NULL;
679 double* _probabilities,
683 kkint32 numClasses = _mlClasses.QueueSize ();
684 for (
kkint32 idx = 0; idx < numClasses; idx++)
686 _probabilities[idx] = 0.0;
692 _log.Level (-1) << endl <<
"ModelDual::ProbabilitiesByClass ***ERROR*** Both Classifiers are not defined." << endl << endl;
699 if (predictions1 == NULL)
701 predictions1 = predictions2;
705 else if (predictions2 == NULL)
719 MLClassList::const_iterator idx2;
720 for (idx2 = _mlClasses.begin (), x = 0; idx2 != _mlClasses.end (); ++idx2, ++x)
743 double* _probabilities,
747 kkint32 numClasses = _mlClasses.QueueSize ();
748 for (
kkint32 idx = 0; idx < numClasses; idx++)
750 _probabilities[idx] = 0.0;
755 _log.Level (-1) << endl <<
"ModelDual::ProbabilitiesByClass ***ERROR*** Both Classifiers are not defined." << endl << endl;
762 if (predictions1 == NULL)
764 predictions1 = predictions2;
768 else if (predictions2 == NULL)
782 MLClassList::const_iterator idx2;
783 for (idx2 = _mlClasses.begin (), x = 0; idx2 != _mlClasses.end (); ++idx2, ++x)
801 double** _crossProbTable,
807 _log.Level (-1) << endl <<
"ModelDual::RetrieveCrossProbTable ***ERROR*** Both Classifiers are not defined." << endl << endl;
813 kkint32 numClasses = _classes.QueueSize ();
815 double** crossProbTableC1 =
new double*[numClasses];
816 double** crossProbTableC2 =
new double*[numClasses];
818 for (x = 0; x < numClasses; ++x)
820 crossProbTableC1[x] =
new double[numClasses];
821 crossProbTableC2[x] =
new double[numClasses];
827 for (x = 0; x < numClasses; ++x)
829 for (y = 0; y < numClasses; ++y)
830 _crossProbTable[x][y] = (crossProbTableC1[x][y] + crossProbTableC2[x][y]) / 2.0;
833 for (x = 0; x < numClasses; ++x)
835 delete crossProbTableC1[x]; crossProbTableC1[x] = NULL;
836 delete crossProbTableC2[x]; crossProbTableC2[x] = NULL;
839 delete[] crossProbTableC1; crossProbTableC1 = NULL;
840 delete[] crossProbTableC2; crossProbTableC2 = NULL;
849 float totalSVs = 0.0;
865 return (
kkint32)(0.5f + totalSVs / (
float)count);
911 KKStr config1Name =
"";
912 KKStr config2Name =
"";
915 while (t && (!cancelFlag))
918 bool tokenFound =
true;
931 if ((varName.EqualIgnoreCase (
"config1")) && (
typeid (*e) ==
typeid (XmlElementTrainingConfiguration2)))
934 config1 =
dynamic_cast<XmlElementTrainingConfiguration2Ptr>(e)->TakeOwnership ();
935 config1Name = config1->ConfigRootName ();
939 config1 =
new TrainingConfiguration2 ();
940 config1 ->Load (config1Name,
false, log);
943 else if ((varName.EqualIgnoreCase (
"config2")) && (
typeid (*e) ==
typeid (XmlElementTrainingConfiguration2)))
946 config2 =
dynamic_cast<XmlElementTrainingConfiguration2Ptr>(e)->TakeOwnership ();
947 config2Name = config1->ConfigRootName ();
950 config2 =
new TrainingConfiguration2 ();
951 config2 ->Load (config2Name,
false, log);
954 else if ((varName.EqualIgnoreCase (
"trainer1")) && (
typeid (*e) ==
typeid (XmlElementTrainingProcess2)))
957 trainer1 =
dynamic_cast<XmlElementTrainingProcess2Ptr>(e)->TakeOwnership ();
960 else if ((varName.EqualIgnoreCase (
"trainer2")) && (
typeid (*e) ==
typeid (XmlElementTrainingProcess2)))
963 trainer2 =
dynamic_cast<XmlElementTrainingProcess2Ptr>(e)->TakeOwnership ();
974 errMsg <<
"ModelDual::ReadXML ***ERROR*** Unexpected Element: Section: " << t
->SectionName () <<
" VarName:" << t
->VarName ();
975 log.Level (-1) << endl << errMsg << endl << endl;
994 KKStr errMsg =
"ModelDual::ReadXML ***ERROR*** trainer1 not loaded!!!";
995 log.Level (-1) << endl << errMsg << endl << endl;
1002 KKStr errMsg =
"ModelDual::ReadXML ***ERROR*** trainer2 not loaded!!!";
1003 log.Level (-1) << endl << errMsg << endl << endl;
1020 errMsg <<
"ModelDual::ReadXML ***ERROR*** Base class 'Model' does not have 'param' defined.";
1022 log.Level (-1) << endl << errMsg << endl << endl;
1030 log.Level (-1) << endl << errMsg << endl << endl;
virtual void Load(const KKStr &_configFileName, bool _validateDirectories, RunLog &log)
KKStr(kkint32 size)
Creates a KKStr object that pre-allocates space for 'size' characters.
XmlTag(const KKStr &_name, TagTypes _tagType)
const KKStr & Name() const
Base class to all Learning Algorithms.
TrainingProcess2Ptr trainer2
KKStr & operator+=(const KKStr &right)
TrainingConfiguration2Ptr config2
FeatureVector * FeatureVectorPtr
KKStr ExtractToken2(const char *delStr="\n\t\r ")
Extract first Token from the string.
virtual ClassProbListPtr ProbabilitiesByClass(FeatureVectorPtr example, RunLog &log)
KKException(const KKStr &_exceptionStr, const KKException &_innerException)
virtual void WriteXML(const KKStr &varName, ostream &o) const
XmlTokenPtr ReadXMLModelToken(XmlTokenPtr t, RunLog &log)
Will process any tokens that belong to 'ModelParam' and return NULL ones that are not will be passed ...
void MergeIn(const ClassProbPtr cp)
Adds the Prediction in 'cp' into this list.
const KKStr & ConfigFileName2() const
FeatureVectorListPtr trainExamples
void ReconcileProbAndVotes(Classifier2Ptr classifier, MLClassPtr predClass, FeatureVectorPtr encodedExample, double &predClassProb, kkint32 &predClassVotes)
Represents a "Class" in the Machine Learning Sense.
void AddErrorMsg(const KKStr &errMsg, kkint32 lineNum)
virtual void ProbabilitiesByClassDual(FeatureVectorPtr example, KKStr &classifier1Desc, KKStr &classifier2Desc, ClassProbListPtr &classifier1Results, ClassProbListPtr &classifier2Results, RunLog &log)
Only applied to ModelDual classifier.
Classifier2Ptr classifier1
void WriteModelXMLFields(std::ostream &o) const
The "WriteXML" method in Derived classes call this method to include the parents classes fields in th...
FactoryFVProducerPtr factoryFVProducer
ModelParamDualPtr Param()
KKStr operator+(const char *right) const
virtual const KKStr & SectionName() const
unsigned __int32 kkuint32
void DeleteExistingClassifiers()
virtual void WriteXML(const KKStr &varName, std::ostream &o) const
virtual KKStr Description() const
KKException(const KKStr &_exceptionStr, const std::exception &_innerException)
virtual FeatureVectorPtr PrepExampleForPrediction(FeatureVectorPtr fv, bool &newExampleCreated)
Every prediction method in every class that is inherited from this class should call this method befo...
KKStr & operator=(KKStr &&src)
kkuint32 Len() const
Returns the number of characters in the string.
kkint32 NumOfSupportVectors() const
virtual kkint32 MemoryConsumedEstimated() const
KKStr operator+(const char *left, const KKStr &right)
const ClassProbPtr LookUp(MLClassPtr targetClass) const
void ClassifyAExample(FeatureVector &example, MLClassPtr &predClass1, MLClassPtr &predClass2, kkint32 &predClass1Votes, kkint32 &predClass2Votes, double &knownClassProb, double &predClass1Prob, double &predClass2Prob, kkint32 &numOfWinners, double &breakTie)
XmlElement * XmlElementPtr
void AddAtribute(const KKStr &attributeName, const KKStr &attributeValue)
virtual void RetrieveCrossProbTable(MLClassList &classes, double **crossProbTable, RunLog &log)
static TrainingProcess2Ptr CreateTrainingProcessFromTrainingExamples(TrainingConfiguration2Const *config, FeatureVectorListPtr trainingExamples, bool takeOwnershipOfTrainingExamples, bool featuresAlreadyNormalized, VolConstBool &cancelFlag, RunLog &log)
Will Construct an instance using provided list of examples rather than loading from training library...
static bool ConfigFileExists(const KKStr &_configFileName)
virtual MLClassPtr Predict(FeatureVectorPtr example, RunLog &log)
XmlTag const * XmlTagConstPtr
void WriteXML(const KKStr &varName, std::ostream &o) const
Manages the reading and writing of objects in a simple XML format. For a class to be supported by Xml...
virtual ModelDualPtr Duplicate() const
KKStr ModelTypeStr() const
void TrainingTimeEnd()
Derived classes call this method to stop the clock for 'trainingTime'.
virtual kkint32 MemoryConsumedEstimated() const
kkint32 MemoryConsumedEstimated() const
static KKStr Concat(const std::vector< std::string > &values)
Concatenates the list of 'std::string' strings.
ClassProbList * ClassProbListPtr
Classifier2(TrainingProcess2Ptr _trainer, RunLog &_log)
Classifier2Ptr classifier2
void AddIn(const ClassProbListPtr otherPredictions)
Adds the contents of 'otherPredictions' to this list.
virtual void Predict(FeatureVectorPtr example, MLClassPtr knownClass, MLClassPtr &predClass1, MLClassPtr &predClass2, kkint32 &predClass1Votes, kkint32 &predClass2Votes, double &probOfKnownClass, double &predClass1Prob, double &predClass2Prob, kkint32 &numOfWinners, bool &knownClassOneOfTheWinners, double &breakTie, RunLog &log)
virtual const KKStr & VarName() const
bool operator==(const KKStr &right) const
const KKStr & Name() const
Model(const KKStr &_name, const ModelParam &_param, FactoryFVProducerPtr _factoryFVProducer)
Construct a instance of 'Model' using the parameters specified in '_param'.
ModelParamDual * ModelParamDualPtr
KKStr operator+(const KKStr &right) const
virtual const KKStr & SectionName() const
Will implement the Dual Classifier Model.
static MLClassPtr CreateNewMLClass(const KKStr &_name, kkint32 _classId=-1)
Static method used to create a new instance of a MLClass object.
TrainingConfiguration2Ptr config1
virtual TrainingConfiguration2Ptr ManufacturTrainingConfiguration() const
Returns a 'TrainingConfiguration2' derived instance.
ModelDual(const ModelDual &_model)
virtual ~ModelDual()
Frees any memory allocated by, and owned by the ModelDual.
virtual void ReadXML(XmlStream &s, XmlTagConstPtr tag, VolConstBool &cancelFlag, RunLog &log)
To be implemented by derived classes; the parent classes fields will be updated by the derived class ...
void NormalizeToOne()
Will normalize the list of predictions such that the total probability will equal 1...
virtual kkint32 MemoryConsumedEstimated() const
void WriteXML(std::ostream &o)
Used for logging messages.
void EncodeProblem(const struct svm_paramater ¶m, struct svm_problem &prob_in, struct svm_problem &prob_out)
const KKStr & ConfigFileName() const
virtual void TrainModel(FeatureVectorListPtr _trainExamples, bool _alreadyNormalized, bool _takeOwnership, VolConstBool &_cancelFlag, RunLog &_log)
Performs operations such as FeatureEncoding, and Normalization. The actual training of models occurs ...
bool StartsWith(const KKStr &value) const
ClassProbListPtr ProbabilitiesByClass(FeatureVectorPtr example)
void TrainingTimeStart()
Derived classes call this method to start the clock for 'trainingTime'.
void ReadXMLModelPost(RunLog &log)
const KKStr & ConfigFileName1() const
virtual KKStr ModelParamTypeStr() const
virtual TokenTypes TokenType()=0
void RetrieveCrossProbTable(MLClassList &classes, double **crossProbTable)
virtual kkint32 NumOfSupportVectors() const
Model(const Model &_madel)
Copy Constructor.
virtual XmlTokenPtr GetNextToken(VolConstBool &cancelFlag, RunLog &log)
KKException(const KKStr &_exceptionStr)
Maintains a list of MLClass instances.
virtual void ProbabilitiesByClass(FeatureVectorPtr example, const MLClassList &_mlClasses, kkint32 *_votes, double *_probabilities, RunLog &log)
FeatureVectorList * FeatureVectorListPtr
virtual void ProbabilitiesByClass(FeatureVectorPtr _example, const MLClassList &_mlClasses, double *_probabilities, RunLog &_log)
Derives predicted probabilities by class.
bool FullHierarchyMustMatch() const
virtual const KKStr & VarName() const
#define XmlFactoryMacro(NameOfClass)
MLClassPtr ReconcilePredictions(MLClassPtr pred1, MLClassPtr pred2, RunLog &log)
TrainingProcess2Ptr trainer1
FactoryFVProducer * FactoryFVProducerPtr
KKStr ModelDescription() const
ModelDual(const KKStr &_name, const ModelParamDual &_param, FactoryFVProducerPtr _factoryFVProducer)
ModelDual(FactoryFVProducerPtr _factoryFVProducer)
Model(FactoryFVProducerPtr _factoryFVProducer)
Use this when you are planning on creating a empty model without parameters.
KKStr osGetRootName(const KKStr &fullFileName)
MLClassPtr ClassifyAExample(FeatureVector &example)
MLClassPtr OtherClass() const
volatile const bool VolConstBool
virtual void TrainModel(FeatureVectorListPtr _trainExamples, bool _alreadyNormalized, bool _takeOwnership, VolConstBool &_cancelFlag, RunLog &_log)
Performs operations such as FeatureEncoding, and Normalization. The actual training of models occurs ...