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