forked from shogun-toolbox/shogun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CrossValidation.cpp
351 lines (288 loc) · 10.1 KB
/
CrossValidation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Heiko Strathmann, Soeren Sonnenburg, Giovanni De Toni,
* Sergey Lisitsyn, Saurabh Mahindre, Jacob Walker, Viktor Gal,
* Leon Kuchenbecker
*/
#include <shogun/base/Parameter.h>
#include <shogun/base/progress.h>
#include <shogun/evaluation/CrossValidation.h>
#include <shogun/evaluation/CrossValidationStorage.h>
#include <shogun/evaluation/Evaluation.h>
#include <shogun/evaluation/SplittingStrategy.h>
#include <shogun/lib/List.h>
#include <shogun/machine/Machine.h>
#include <shogun/mathematics/Statistics.h>
#include <shogun/util/converters.h>
using namespace shogun;
CCrossValidation::CCrossValidation() : CMachineEvaluation()
{
init();
}
CCrossValidation::CCrossValidation(
CMachine* machine, CFeatures* features, CLabels* labels,
CSplittingStrategy* splitting_strategy, CEvaluation* evaluation_criterion,
bool autolock)
: CMachineEvaluation(
machine, features, labels, splitting_strategy, evaluation_criterion,
autolock)
{
init();
}
CCrossValidation::CCrossValidation(
CMachine* machine, CLabels* labels, CSplittingStrategy* splitting_strategy,
CEvaluation* evaluation_criterion, bool autolock)
: CMachineEvaluation(
machine, labels, splitting_strategy, evaluation_criterion, autolock)
{
init();
}
CCrossValidation::~CCrossValidation()
{
}
void CCrossValidation::init()
{
m_num_runs = 1;
SG_ADD(&m_num_runs, "num_runs", "Number of repetitions");
}
CEvaluationResult* CCrossValidation::evaluate_impl()
{
/* if for some reason the do_unlock_frag is set, unlock */
if (m_do_unlock)
{
m_machine->data_unlock();
m_do_unlock = false;
}
/* set labels in any case (no locking needs this) */
m_machine->set_labels(m_labels);
if (m_autolock)
{
/* if machine supports locking try to do so */
if (m_machine->supports_locking())
{
/* only lock if machine is not yet locked */
if (!m_machine->is_data_locked())
{
m_machine->data_lock(m_labels, m_features);
m_do_unlock = true;
}
}
else
{
SG_WARNING(
"%s does not support locking. Autolocking is skipped. "
"Set autolock flag to false to get rid of warning.\n",
m_machine->get_name());
}
}
SGVector<float64_t> results(m_num_runs);
/* perform all the x-val runs */
SG_DEBUG("starting %d runs of cross-validation\n", m_num_runs)
for (auto i : SG_PROGRESS(range(m_num_runs)))
{
/* evtl. update xvalidation output class */
SG_DEBUG("Creating CrossValidationStorage.\n")
CrossValidationStorage* storage = new CrossValidationStorage();
SG_REF(storage)
storage->put("num_runs", utils::safe_convert<index_t>(m_num_runs));
storage->put(
"num_folds", utils::safe_convert<index_t>(
m_splitting_strategy->get_num_subsets()));
storage->put("labels", m_labels);
storage->post_init();
SG_DEBUG("Ending CrossValidationStorage initilization.\n")
SG_DEBUG("entering cross-validation run %d \n", i)
results[i] = evaluate_one_run(i, storage);
SG_DEBUG("result of cross-validation run %d is %f\n", i, results[i])
/* Emit the value */
observe(
i, "cross_validation_run", "One run of CrossValidation",
storage->as<CEvaluationResult>());
SG_UNREF(storage)
}
/* construct evaluation result */
CCrossValidationResult* result = new CCrossValidationResult();
result->set_mean(CStatistics::mean(results));
if (m_num_runs > 1)
result->set_std_dev(CStatistics::std_deviation(results));
else
result->set_std_dev(0);
/* unlock machine if it was locked in this method */
if (m_machine->is_data_locked() && m_do_unlock)
{
m_machine->data_unlock();
m_do_unlock = false;
}
SG_REF(result);
return result;
}
void CCrossValidation::set_num_runs(int32_t num_runs)
{
if (num_runs < 1)
SG_ERROR("%d is an illegal number of repetitions\n", num_runs)
m_num_runs = num_runs;
}
float64_t CCrossValidation::evaluate_one_run(
int64_t index, CrossValidationStorage* storage)
{
SG_DEBUG("entering %s::evaluate_one_run()\n", get_name())
index_t num_subsets = m_splitting_strategy->get_num_subsets();
SG_DEBUG("building index sets for %d-fold cross-validation\n", num_subsets)
/* build index sets */
m_splitting_strategy->build_subsets();
/* results array */
SGVector<float64_t> results(num_subsets);
/* different behavior whether data is locked or not */
if (m_machine->is_data_locked())
{
m_machine->set_store_model_features(true);
SG_DEBUG("starting locked evaluation\n", get_name())
/* do actual cross-validation */
for (auto i : SG_PROGRESS(range(num_subsets)))
{
COMPUTATION_CONTROLLERS
/* evtl. update xvalidation output class */
CrossValidationFoldStorage* fold = new CrossValidationFoldStorage();
SG_REF(fold)
fold->put("run_index", (index_t)index);
fold->put("fold_index", i);
/* index subset for training, will be freed below */
SGVector<index_t> inverse_subset_indices =
m_splitting_strategy->generate_subset_inverse(i);
/* train machine on training features */
m_machine->train_locked(inverse_subset_indices);
/* feature subset for testing */
SGVector<index_t> subset_indices =
m_splitting_strategy->generate_subset_indices(i);
/* evtl. update xvalidation output class */
fold->put("train_indices", inverse_subset_indices);
auto fold_machine = (CMachine*)m_machine->clone();
fold->put("trained_machine", fold_machine);
SG_UNREF(fold_machine)
/* produce output for desired indices */
CLabels* result_labels = m_machine->apply_locked(subset_indices);
SG_REF(result_labels);
/* set subset for testing labels */
m_labels->add_subset(subset_indices);
/* evaluate against own labels */
m_evaluation_criterion->set_indices(subset_indices);
results[i] =
m_evaluation_criterion->evaluate(result_labels, m_labels);
/* evtl. update xvalidation output class */
fold->put("test_indices", subset_indices);
fold->put("predicted_labels", result_labels);
CLabels* true_labels = (CLabels*)m_labels->clone();
SG_REF(true_labels)
fold->put("ground_truth_labels", true_labels);
fold->post_update_results();
fold->put("evaluation_result", results[i]);
/* remove subset to prevent side effects */
m_labels->remove_subset();
/* Save fold into storage */
storage->append_fold_result(fold);
/* clean up */
SG_UNREF(result_labels);
SG_UNREF(true_labels)
SG_UNREF(fold);
SG_DEBUG("done locked evaluation\n", get_name())
}
}
else
{
SG_DEBUG("starting unlocked evaluation\n", get_name())
/* tell machine to store model internally
* (otherwise changing subset of features will kaboom the classifier) */
m_machine->set_store_model_features(true);
/* do actual cross-validation */
// TODO parallel xvalidation needs some serious fixing, see #3743
//#pragma omp parallel for
for (index_t i = 0; i < num_subsets; ++i)
{
COMPUTATION_CONTROLLERS
CrossValidationFoldStorage* fold = new CrossValidationFoldStorage();
SG_REF(fold)
auto machine = (CMachine*)m_machine->clone();
// TODO while these are not used through const interfaces,
// we unfortunately have to clone, even though these could be shared
auto features = (CFeatures*)m_features->clone();
auto labels = (CLabels*)m_labels->clone();
auto evaluation_criterion =
(CEvaluation*)m_evaluation_criterion->clone();
/* evtl. update xvalidation output class */
fold->put("run_index", (index_t)index);
fold->put("fold_index", i);
/* set feature subset for training */
SGVector<index_t> inverse_subset_indices =
m_splitting_strategy->generate_subset_inverse(i);
features->add_subset(inverse_subset_indices);
/* set label subset for training */
labels->add_subset(inverse_subset_indices);
SG_DEBUG("training set %d:\n", i)
if (io->get_loglevel() == MSG_DEBUG)
{
SGVector<index_t>::display_vector(
inverse_subset_indices.vector, inverse_subset_indices.vlen,
"training indices");
}
/* train machine on training features and remove subset */
SG_DEBUG("starting training\n")
machine->set_labels(labels);
machine->train(features);
SG_DEBUG("finished training\n")
/* evtl. update xvalidation output class */
fold->put("train_indices", inverse_subset_indices);
auto fold_machine = (CMachine*)machine->clone();
fold->put("trained_machine", fold_machine);
SG_UNREF(fold_machine)
features->remove_subset();
labels->remove_subset();
/* set feature subset for testing (subset method that stores
* pointer) */
SGVector<index_t> subset_indices =
m_splitting_strategy->generate_subset_indices(i);
features->add_subset(subset_indices);
/* set label subset for testing */
labels->add_subset(subset_indices);
SG_DEBUG("test set %d:\n", i)
if (io->get_loglevel() == MSG_DEBUG)
{
SGVector<index_t>::display_vector(
subset_indices.vector, subset_indices.vlen, "test indices");
}
/* apply machine to test features and remove subset */
SG_DEBUG("starting evaluation\n")
SG_DEBUG("%p\n", features)
CLabels* result_labels = machine->apply(features);
SG_DEBUG("finished evaluation\n")
features->remove_subset();
SG_REF(result_labels);
/* evaluate */
results[i] = evaluation_criterion->evaluate(result_labels, labels);
SG_DEBUG("result on fold %d is %f\n", i, results[i])
/* evtl. update xvalidation output class */
fold->put("test_indices", subset_indices);
fold->put("predicted_labels", result_labels);
CLabels* true_labels = (CLabels*)labels->clone();
SG_REF(true_labels)
fold->put("ground_truth_labels", true_labels);
fold->post_update_results();
fold->put("evaluation_result", results[i]);
storage->append_fold_result(fold);
/* clean up, remove subsets */
labels->remove_subset();
SG_UNREF(machine);
SG_UNREF(features);
SG_UNREF(labels);
SG_UNREF(evaluation_criterion);
SG_UNREF(result_labels);
SG_UNREF(true_labels);
SG_UNREF(fold);
}
SG_DEBUG("done unlocked evaluation\n", get_name())
}
/* build arithmetic mean of results */
float64_t mean = CStatistics::mean(results);
SG_DEBUG("leaving %s::evaluate_one_run()\n", get_name())
return mean;
}