Path: blob/master/modules/ml/test/test_save_load.cpp
16354 views
/*M///////////////////////////////////////////////////////////////////////////////////////1//2// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.3//4// By downloading, copying, installing or using the software you agree to this license.5// If you do not agree to this license, do not download, install,6// copy or use the software.7//8//9// Intel License Agreement10// For Open Source Computer Vision Library11//12// Copyright (C) 2000, Intel Corporation, all rights reserved.13// Third party copyrights are property of their respective owners.14//15// Redistribution and use in source and binary forms, with or without modification,16// are permitted provided that the following conditions are met:17//18// * Redistribution's of source code must retain the above copyright notice,19// this list of conditions and the following disclaimer.20//21// * Redistribution's in binary form must reproduce the above copyright notice,22// this list of conditions and the following disclaimer in the documentation23// and/or other materials provided with the distribution.24//25// * The name of Intel Corporation may not be used to endorse or promote products26// derived from this software without specific prior written permission.27//28// This software is provided by the copyright holders and contributors "as is" and29// any express or implied warranties, including, but not limited to, the implied30// warranties of merchantability and fitness for a particular purpose are disclaimed.31// In no event shall the Intel Corporation or contributors be liable for any direct,32// indirect, incidental, special, exemplary, or consequential damages33// (including, but not limited to, procurement of substitute goods or services;34// loss of use, data, or profits; or business interruption) however caused35// and on any theory of liability, whether in contract, strict liability,36// or tort (including negligence or otherwise) arising in any way out of37// the use of this software, even if advised of the possibility of such damage.38//39//M*/4041#include "test_precomp.hpp"4243namespace opencv_test {4445CV_SLMLTest::CV_SLMLTest( const char* _modelName ) : CV_MLBaseTest( _modelName )46{47validationFN = "slvalidation.xml";48}4950int CV_SLMLTest::run_test_case( int testCaseIdx )51{52int code = cvtest::TS::OK;53code = prepare_test_case( testCaseIdx );5455if( code == cvtest::TS::OK )56{57data->setTrainTestSplit(data->getNTrainSamples(), true);58code = train( testCaseIdx );59if( code == cvtest::TS::OK )60{61get_test_error( testCaseIdx, &test_resps1 );62fname1 = tempfile(".json.gz");63save( (fname1 + "?base64").c_str() );64load( fname1.c_str() );65get_test_error( testCaseIdx, &test_resps2 );66fname2 = tempfile(".json.gz");67save( (fname2 + "?base64").c_str() );68}69else70ts->printf( cvtest::TS::LOG, "model can not be trained" );71}72return code;73}7475int CV_SLMLTest::validate_test_results( int testCaseIdx )76{77int code = cvtest::TS::OK;7879// 1. compare files80FILE *fs1 = fopen(fname1.c_str(), "rb"), *fs2 = fopen(fname2.c_str(), "rb");81size_t sz1 = 0, sz2 = 0;82if( !fs1 || !fs2 )83code = cvtest::TS::FAIL_MISSING_TEST_DATA;84if( code >= 0 )85{86fseek(fs1, 0, SEEK_END); fseek(fs2, 0, SEEK_END);87sz1 = ftell(fs1);88sz2 = ftell(fs2);89fseek(fs1, 0, SEEK_SET); fseek(fs2, 0, SEEK_SET);90}9192if( sz1 != sz2 )93code = cvtest::TS::FAIL_INVALID_OUTPUT;9495if( code >= 0 )96{97const int BUFSZ = 1024;98uchar buf1[BUFSZ], buf2[BUFSZ];99for( size_t pos = 0; pos < sz1; )100{101size_t r1 = fread(buf1, 1, BUFSZ, fs1);102size_t r2 = fread(buf2, 1, BUFSZ, fs2);103if( r1 != r2 || memcmp(buf1, buf2, r1) != 0 )104{105ts->printf( cvtest::TS::LOG,106"in test case %d first (%s) and second (%s) saved files differ in %d-th kb\n",107testCaseIdx, fname1.c_str(), fname2.c_str(),108(int)pos );109code = cvtest::TS::FAIL_INVALID_OUTPUT;110break;111}112pos += r1;113}114}115116if(fs1)117fclose(fs1);118if(fs2)119fclose(fs2);120121// delete temporary files122if( code >= 0 )123{124remove( fname1.c_str() );125remove( fname2.c_str() );126}127128if( code >= 0 )129{130// 2. compare responses131CV_Assert( test_resps1.size() == test_resps2.size() );132vector<float>::const_iterator it1 = test_resps1.begin(), it2 = test_resps2.begin();133for( ; it1 != test_resps1.end(); ++it1, ++it2 )134{135if( fabs(*it1 - *it2) > FLT_EPSILON )136{137ts->printf( cvtest::TS::LOG, "in test case %d responses predicted before saving and after loading is different", testCaseIdx );138code = cvtest::TS::FAIL_INVALID_OUTPUT;139break;140}141}142}143return code;144}145146namespace {147148TEST(ML_NaiveBayes, save_load) { CV_SLMLTest test( CV_NBAYES ); test.safe_run(); }149TEST(ML_KNearest, save_load) { CV_SLMLTest test( CV_KNEAREST ); test.safe_run(); }150TEST(ML_SVM, save_load) { CV_SLMLTest test( CV_SVM ); test.safe_run(); }151TEST(ML_ANN, save_load) { CV_SLMLTest test( CV_ANN ); test.safe_run(); }152TEST(ML_DTree, save_load) { CV_SLMLTest test( CV_DTREE ); test.safe_run(); }153TEST(ML_Boost, save_load) { CV_SLMLTest test( CV_BOOST ); test.safe_run(); }154TEST(ML_RTrees, save_load) { CV_SLMLTest test( CV_RTREES ); test.safe_run(); }155TEST(DISABLED_ML_ERTrees, save_load) { CV_SLMLTest test( CV_ERTREES ); test.safe_run(); }156TEST(MV_SVMSGD, save_load){ CV_SLMLTest test( CV_SVMSGD ); test.safe_run(); }157158class CV_LegacyTest : public cvtest::BaseTest159{160public:161CV_LegacyTest(const std::string &_modelName, const std::string &_suffixes = std::string())162: cvtest::BaseTest(), modelName(_modelName), suffixes(_suffixes)163{164}165virtual ~CV_LegacyTest() {}166protected:167void run(int)168{169unsigned int idx = 0;170for (;;)171{172if (idx >= suffixes.size())173break;174int found = (int)suffixes.find(';', idx);175string piece = suffixes.substr(idx, found - idx);176if (piece.empty())177break;178oneTest(piece);179idx += (unsigned int)piece.size() + 1;180}181}182void oneTest(const string & suffix)183{184using namespace cv::ml;185186int code = cvtest::TS::OK;187string filename = ts->get_data_path() + "legacy/" + modelName + suffix;188bool isTree = modelName == CV_BOOST || modelName == CV_DTREE || modelName == CV_RTREES;189Ptr<StatModel> model;190if (modelName == CV_BOOST)191model = Algorithm::load<Boost>(filename);192else if (modelName == CV_ANN)193model = Algorithm::load<ANN_MLP>(filename);194else if (modelName == CV_DTREE)195model = Algorithm::load<DTrees>(filename);196else if (modelName == CV_NBAYES)197model = Algorithm::load<NormalBayesClassifier>(filename);198else if (modelName == CV_SVM)199model = Algorithm::load<SVM>(filename);200else if (modelName == CV_RTREES)201model = Algorithm::load<RTrees>(filename);202else if (modelName == CV_SVMSGD)203model = Algorithm::load<SVMSGD>(filename);204if (!model)205{206code = cvtest::TS::FAIL_INVALID_TEST_DATA;207}208else209{210Mat input = Mat(isTree ? 10 : 1, model->getVarCount(), CV_32F);211ts->get_rng().fill(input, RNG::UNIFORM, 0, 40);212213if (isTree)214randomFillCategories(filename, input);215216Mat output;217model->predict(input, output, StatModel::RAW_OUTPUT | (isTree ? DTrees::PREDICT_SUM : 0));218// just check if no internal assertions or errors thrown219}220ts->set_failed_test_info(code);221}222void randomFillCategories(const string & filename, Mat & input)223{224Mat catMap;225Mat catCount;226std::vector<uchar> varTypes;227228FileStorage fs(filename, FileStorage::READ);229FileNode root = fs.getFirstTopLevelNode();230root["cat_map"] >> catMap;231root["cat_count"] >> catCount;232root["var_type"] >> varTypes;233234int offset = 0;235int countOffset = 0;236uint var = 0, varCount = (uint)varTypes.size();237for (; var < varCount; ++var)238{239if (varTypes[var] == ml::VAR_CATEGORICAL)240{241int size = catCount.at<int>(0, countOffset);242for (int row = 0; row < input.rows; ++row)243{244int randomChosenIndex = offset + ((uint)ts->get_rng()) % size;245int value = catMap.at<int>(0, randomChosenIndex);246input.at<float>(row, var) = (float)value;247}248offset += size;249++countOffset;250}251}252}253string modelName;254string suffixes;255};256257TEST(ML_ANN, legacy_load) { CV_LegacyTest test(CV_ANN, "_waveform.xml"); test.safe_run(); }258TEST(ML_Boost, legacy_load) { CV_LegacyTest test(CV_BOOST, "_adult.xml;_1.xml;_2.xml;_3.xml"); test.safe_run(); }259TEST(ML_DTree, legacy_load) { CV_LegacyTest test(CV_DTREE, "_abalone.xml;_mushroom.xml"); test.safe_run(); }260TEST(ML_NBayes, legacy_load) { CV_LegacyTest test(CV_NBAYES, "_waveform.xml"); test.safe_run(); }261TEST(ML_SVM, legacy_load) { CV_LegacyTest test(CV_SVM, "_poletelecomm.xml;_waveform.xml"); test.safe_run(); }262TEST(ML_RTrees, legacy_load) { CV_LegacyTest test(CV_RTREES, "_waveform.xml"); test.safe_run(); }263TEST(ML_SVMSGD, legacy_load) { CV_LegacyTest test(CV_SVMSGD, "_waveform.xml"); test.safe_run(); }264265/*TEST(ML_SVM, throw_exception_when_save_untrained_model)266{267Ptr<cv::ml::SVM> svm;268string filename = tempfile("svm.xml");269ASSERT_THROW(svm.save(filename.c_str()), Exception);270remove(filename.c_str());271}*/272273TEST(DISABLED_ML_SVM, linear_save_load)274{275Ptr<cv::ml::SVM> svm1, svm2, svm3;276277svm1 = Algorithm::load<SVM>("SVM45_X_38-1.xml");278svm2 = Algorithm::load<SVM>("SVM45_X_38-2.xml");279string tname = tempfile("a.json");280svm2->save(tname + "?base64");281svm3 = Algorithm::load<SVM>(tname);282283ASSERT_EQ(svm1->getVarCount(), svm2->getVarCount());284ASSERT_EQ(svm1->getVarCount(), svm3->getVarCount());285286int m = 10000, n = svm1->getVarCount();287Mat samples(m, n, CV_32F), r1, r2, r3;288randu(samples, 0., 1.);289290svm1->predict(samples, r1);291svm2->predict(samples, r2);292svm3->predict(samples, r3);293294double eps = 1e-4;295EXPECT_LE(cvtest::norm(r1, r2, NORM_INF), eps);296EXPECT_LE(cvtest::norm(r1, r3, NORM_INF), eps);297298remove(tname.c_str());299}300301}} // namespace302/* End of file. */303304305