-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
MKLMulticlass.cpp
461 lines (355 loc) · 9.74 KB
/
MKLMulticlass.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2009 Alexander Binder
* Copyright (C) 2009 Fraunhofer Institute FIRST and Max-Planck-Society
*
* Update to patch 0.10.0 - thanks to Eric aka Yoo (thereisnoknife@gmail.com)
*
*/
#include <shogun/multiclass/MulticlassOneVsRestStrategy.h>
#include <shogun/classifier/mkl/MKLMulticlass.h>
#include <shogun/io/SGIO.h>
#include <shogun/labels/MulticlassLabels.h>
#include <vector>
#include <shogun/lib/Signal.h>
using namespace shogun;
CMKLMulticlass::CMKLMulticlass()
: CMulticlassSVM(new CMulticlassOneVsRestStrategy())
{
svm=NULL;
lpw=NULL;
mkl_eps=0.01;
max_num_mkl_iters=999;
pnorm=1;
}
CMKLMulticlass::CMKLMulticlass(float64_t C, CKernel* k, CLabels* lab)
: CMulticlassSVM(new CMulticlassOneVsRestStrategy(), C, k, lab)
{
svm=NULL;
lpw=NULL;
mkl_eps=0.01;
max_num_mkl_iters=999;
pnorm=1;
}
CMKLMulticlass::~CMKLMulticlass()
{
SG_UNREF(svm);
svm=NULL;
delete lpw;
lpw=NULL;
}
CMKLMulticlass::CMKLMulticlass( const CMKLMulticlass & cm)
: CMulticlassSVM(new CMulticlassOneVsRestStrategy())
{
svm=NULL;
lpw=NULL;
SG_ERROR(
" CMKLMulticlass::CMKLMulticlass(const CMKLMulticlass & cm): must "
"not be called, glpk structure is currently not copyable");
}
CMKLMulticlass CMKLMulticlass::operator=( const CMKLMulticlass & cm)
{
SG_ERROR(
" CMKLMulticlass CMKLMulticlass::operator=(...): must "
"not be called, glpk structure is currently not copyable");
return (*this);
}
void CMKLMulticlass::initsvm()
{
if (!m_labels)
{
SG_ERROR("CMKLMulticlass::initsvm(): the set labels is NULL\n")
}
SG_UNREF(svm);
svm=new CGMNPSVM;
SG_REF(svm);
svm->set_C(get_C());
svm->set_epsilon(get_epsilon());
if (m_labels->get_num_labels()<=0)
{
SG_ERROR("CMKLMulticlass::initsvm(): the number of labels is "
"nonpositive, do not know how to handle this!\n");
}
svm->set_labels(m_labels);
}
void CMKLMulticlass::initlpsolver()
{
if (!m_kernel)
{
SG_ERROR("CMKLMulticlass::initlpsolver(): the set kernel is NULL\n")
}
if (m_kernel->get_kernel_type()!=K_COMBINED)
{
SG_ERROR("CMKLMulticlass::initlpsolver(): given kernel is not of type"
" K_COMBINED %d required by Multiclass Mkl \n",
m_kernel->get_kernel_type());
}
int numker=dynamic_cast<CCombinedKernel *>(m_kernel)->get_num_subkernels();
ASSERT(numker>0)
/*
if (lpw)
{
delete lpw;
}
*/
//lpw=new MKLMulticlassGLPK;
if(pnorm>1)
{
lpw=new MKLMulticlassGradient;
lpw->set_mkl_norm(pnorm);
}
else
{
lpw=new MKLMulticlassGLPK;
}
lpw->setup(numker);
}
bool CMKLMulticlass::evaluatefinishcriterion(const int32_t
numberofsilpiterations)
{
if ( (max_num_mkl_iters>0) && (numberofsilpiterations>=max_num_mkl_iters) )
return true;
if (weightshistory.size()>1)
{
std::vector<float64_t> wold,wnew;
wold=weightshistory[ weightshistory.size()-2 ];
wnew=weightshistory.back();
float64_t delta=0;
ASSERT (wold.size()==wnew.size())
if((pnorm<=1)&&(!normweightssquared.empty()))
{
//check dual gap part for mkl
delta=oldalphaterm-curalphaterm;
int32_t maxind=0;
float64_t maxval=normweightssquared[maxind];
for (size_t i=0;i< wnew.size();++i)
{
delta+=-0.5*oldnormweightssquared[i]*wold[i];
if(normweightssquared[i]>maxval)
{
maxind=i;
maxval=normweightssquared[i];
}
}
delta+=0.5*normweightssquared[maxind];
//delta=fabs(delta);
SG_SINFO("L1 Norm chosen, MKL part of duality gap %f \n",delta)
if( (delta < mkl_eps) && (numberofsilpiterations>=1) )
{
return true;
}
}
else
{
delta=0;
float64_t deltaold=oldalphaterm,deltanew=curalphaterm;
for (size_t i=0;i< wnew.size();++i)
{
delta+=(wold[i]-wnew[i])*(wold[i]-wnew[i]);
deltaold+= -0.5*oldnormweightssquared[i]*wold[i];
deltanew+= -0.5*normweightssquared[i]*wnew[i];
}
if(deltanew>0)
{
delta=1-deltanew/deltaold;
}
else
{
SG_SWARNING("CMKLMulticlass::evaluatefinishcriterion(...): deltanew<=0.Switching back to weight norsm difference as criterion.\n")
delta=sqrt(delta);
}
SG_SINFO("weight delta %f \n",delta)
if( (delta < mkl_eps) && (numberofsilpiterations>=1) )
{
return true;
}
}
}
return false;
}
void CMKLMulticlass::addingweightsstep( const std::vector<float64_t> &
curweights)
{
if (weightshistory.size()>2)
{
weightshistory.erase(weightshistory.begin());
}
//float64_t* weights(NULL);
//weights=new float64_t[curweights.size()];
SGVector<float64_t> weights(curweights.size());
std::copy(curweights.begin(),curweights.end(),weights.vector);
m_kernel->set_subkernel_weights(weights);
//delete[] weights;
//weights=NULL;
initsvm();
svm->set_kernel(m_kernel);
svm->train();
float64_t sumofsignfreealphas=getsumofsignfreealphas();
curalphaterm=sumofsignfreealphas;
int32_t numkernels=
dynamic_cast<CCombinedKernel *>(m_kernel)->get_num_subkernels();
normweightssquared.resize(numkernels);
for (int32_t ind=0; ind < numkernels; ++ind )
{
normweightssquared[ind]=getsquarenormofprimalcoefficients( ind );
}
lpw->addconstraint(normweightssquared,sumofsignfreealphas);
}
float64_t CMKLMulticlass::getsumofsignfreealphas()
{
std::vector<int> trainlabels2(m_labels->get_num_labels());
SGVector<int32_t> lab=((CMulticlassLabels*) m_labels)->get_int_labels();
std::copy(lab.vector,lab.vector+lab.vlen, trainlabels2.begin());
ASSERT (trainlabels2.size()>0)
float64_t sum=0;
for (int32_t nc=0; nc< ((CMulticlassLabels*) m_labels)->get_num_classes();++nc)
{
CSVM * sm=svm->get_svm(nc);
float64_t bia=sm->get_bias();
sum+= 0.5*bia*bia;
SG_UNREF(sm);
}
index_t basealphas_y = 0, basealphas_x = 0;
float64_t* basealphas = svm->get_basealphas_ptr(&basealphas_y,
&basealphas_x);
for (size_t lb=0; lb< trainlabels2.size();++lb)
{
for (int32_t nc=0; nc< ((CMulticlassLabels*) m_labels)->get_num_classes();++nc)
{
CSVM * sm=svm->get_svm(nc);
if ((int)nc!=trainlabels2[lb])
{
CSVM * sm2=svm->get_svm(trainlabels2[lb]);
float64_t bia1=sm2->get_bias();
float64_t bia2=sm->get_bias();
SG_UNREF(sm2);
sum+= -basealphas[lb*basealphas_y + nc]*(bia1-bia2-1);
}
SG_UNREF(sm);
}
}
return sum;
}
float64_t CMKLMulticlass::getsquarenormofprimalcoefficients(
const int32_t ind)
{
CKernel * ker=dynamic_cast<CCombinedKernel *>(m_kernel)->get_kernel(ind);
float64_t tmp=0;
for (int32_t classindex=0; classindex< ((CMulticlassLabels*) m_labels)->get_num_classes();
++classindex)
{
CSVM * sm=svm->get_svm(classindex);
for (int32_t i=0; i < sm->get_num_support_vectors(); ++i)
{
float64_t alphai=sm->get_alpha(i);
int32_t svindi= sm->get_support_vector(i);
for (int32_t k=0; k < sm->get_num_support_vectors(); ++k)
{
float64_t alphak=sm->get_alpha(k);
int32_t svindk=sm->get_support_vector(k);
tmp+=alphai*ker->kernel(svindi,svindk)
*alphak;
}
}
SG_UNREF(sm);
}
SG_UNREF(ker);
ker=NULL;
return tmp;
}
bool CMKLMulticlass::train_machine(CFeatures* data)
{
ASSERT(m_kernel)
ASSERT(m_labels && m_labels->get_num_labels())
ASSERT(m_labels->get_label_type() == LT_MULTICLASS)
int numcl=((CMulticlassLabels*) m_labels)->get_num_classes();
if (data)
{
if (m_labels->get_num_labels() != data->get_num_vectors())
{
SG_ERROR("%s::train_machine(): Number of training vectors (%d) does"
" not match number of labels (%d)\n", get_name(),
data->get_num_vectors(), m_labels->get_num_labels());
}
m_kernel->init(data, data);
}
initlpsolver();
weightshistory.clear();
int32_t numkernels=
dynamic_cast<CCombinedKernel *>(m_kernel)->get_num_subkernels();
::std::vector<float64_t> curweights(numkernels,1.0/numkernels);
weightshistory.push_back(curweights);
addingweightsstep(curweights);
oldalphaterm=curalphaterm;
oldnormweightssquared=normweightssquared;
int32_t numberofsilpiterations=0;
bool final=false;
while (!(cancel_computation()) && !final)
{
//curweights.clear();
lpw->computeweights(curweights);
weightshistory.push_back(curweights);
addingweightsstep(curweights);
//new weights new biasterm
final=evaluatefinishcriterion(numberofsilpiterations);
oldalphaterm=curalphaterm;
oldnormweightssquared=normweightssquared;
++numberofsilpiterations;
} // while(false==final)
//set alphas, bias, support vecs
ASSERT(numcl>=1)
create_multiclass_svm(numcl);
for (int32_t i=0; i<numcl; i++)
{
CSVM* osvm=svm->get_svm(i);
CSVM* nsvm=new CSVM(osvm->get_num_support_vectors());
for (int32_t k=0; k<osvm->get_num_support_vectors() ; k++)
{
nsvm->set_alpha(k, osvm->get_alpha(k) );
nsvm->set_support_vector(k,osvm->get_support_vector(k) );
}
nsvm->set_bias(osvm->get_bias() );
set_svm(i, nsvm);
SG_UNREF(osvm);
osvm=NULL;
}
SG_UNREF(svm);
svm=NULL;
if (lpw)
{
delete lpw;
}
lpw=NULL;
return true;
}
float64_t* CMKLMulticlass::getsubkernelweights(int32_t & numweights)
{
if ( weightshistory.empty() )
{
numweights=0;
return NULL;
}
std::vector<float64_t> subkerw=weightshistory.back();
numweights=weightshistory.back().size();
float64_t* res=new float64_t[numweights];
std::copy(weightshistory.back().begin(), weightshistory.back().end(),res);
return res;
}
void CMKLMulticlass::set_mkl_epsilon(float64_t eps )
{
mkl_eps=eps;
}
void CMKLMulticlass::set_max_num_mkliters(int32_t maxnum)
{
max_num_mkl_iters=maxnum;
}
void CMKLMulticlass::set_mkl_norm(float64_t norm)
{
pnorm=norm;
if(pnorm<1 )
SG_ERROR("CMKLMulticlass::set_mkl_norm(float64_t norm) : parameter pnorm<1")
}