| 1 | // #include <math.h> |
| 2 | #include <cmath> |
| 3 | #include <stdio.h> |
| 4 | #include <stdlib.h> |
| 5 | #include <ctype.h> |
| 6 | #include <float.h> |
| 7 | #include <string.h> |
| 8 | #include <stdarg.h> |
| 9 | #include <limits.h> |
| 10 | #include <locale.h> |
| 11 | #include "svm.h" |
| 12 | //json |
| 13 | #include "json/json.h" |
| 14 | #include <iostream> |
| 15 | #include <fstream> |
| 16 | #include <string> |
| 17 | int libsvm_version = LIBSVM_VERSION; |
| 18 | typedef float Qfloat; |
| 19 | typedef signed char schar; |
| 20 | #ifndef min |
| 21 | template <class T> static inline T min(T x,T y) { return (x<y)?x:y; } |
| 22 | #endif |
| 23 | #ifndef max |
| 24 | template <class T> static inline T max(T x,T y) { return (x>y)?x:y; } |
| 25 | #endif |
| 26 | template <class T> static inline void swap(T& x, T& y) { T t=x; x=y; y=t; } |
| 27 | template <class S, class T> static inline void clone(T*& dst, S* src, int n) |
| 28 | { |
| 29 | dst = new T[n]; |
| 30 | // memcpy((void *)dst,(void *)src,sizeof(T)*n); |
| 31 | memcpy((void *)dst,(void *)src,sizeof(T)*n); |
| 32 | } |
| 33 | static inline double powi(double base, int times) |
| 34 | { |
| 35 | double tmp = base, ret = 1.0; |
| 36 | |
| 37 | for(int t=times; t>0; t/=2) |
| 38 | { |
| 39 | if(t%2==1) ret*=tmp; |
| 40 | tmp = tmp * tmp; |
| 41 | } |
| 42 | return ret; |
| 43 | } |
| 44 | #define INF HUGE_VAL |
| 45 | #define TAU 1e-12 |
| 46 | #define Malloc(type,n) (type *)malloc((n)*sizeof(type)) |
| 47 | |
| 48 | static void print_string_stdout(const char *s) |
| 49 | { |
| 50 | fputs(s,stdout); |
| 51 | fflush(stdout); |
| 52 | } |
| 53 | static void (*svm_print_string) (const char *) = &print_string_stdout; |
| 54 | #if 1 |
| 55 | static void info(const char *fmt,...) |
| 56 | { |
| 57 | char buf[BUFSIZ]; |
| 58 | va_list ap; |
| 59 | va_start(ap,fmt); |
| 60 | vsprintf(buf,fmt,ap); |
| 61 | va_end(ap); |
| 62 | (*svm_print_string)(buf); |
| 63 | } |
| 64 | #else |
| 65 | static void info(const char *fmt,...) {} |
| 66 | #endif |
| 67 | |
| 68 | // |
| 69 | // Kernel Cache |
| 70 | // |
| 71 | // l is the number of total data items |
| 72 | // size is the cache size limit in bytes |
| 73 | // |
| 74 | class Cache |
| 75 | { |
| 76 | public: |
| 77 | Cache(int l,long int size); |
| 78 | ~Cache(); |
| 79 | |
| 80 | // request data [0,len) |
| 81 | // return some position p where [p,len) need to be filled |
| 82 | // (p >= len if nothing needs to be filled) |
| 83 | int get_data(const int index, Qfloat **data, int len); |
| 84 | void swap_index(int i, int j); |
| 85 | private: |
| 86 | int l; |
| 87 | long int size; |
| 88 | struct head_t |
| 89 | { |
| 90 | head_t *prev, *next; // a circular list |
| 91 | Qfloat *data; |
| 92 | int len; // data[0,len) is cached in this entry |
| 93 | }; |
| 94 | |
| 95 | head_t *head; |
| 96 | head_t lru_head; |
| 97 | void lru_delete(head_t *h); |
| 98 | void lru_insert(head_t *h); |
| 99 | }; |
| 100 | |
| 101 | Cache::Cache(int l_,long int size_):l(l_),size(size_) |
| 102 | { |
| 103 | head = (head_t *)calloc(l,sizeof(head_t)); // initialized to 0 |
| 104 | size /= sizeof(Qfloat); |
| 105 | size -= l * sizeof(head_t) / sizeof(Qfloat); |
| 106 | size = max(size, 2 * (long int) l); // cache must be large enough for two columns |
| 107 | lru_head.next = lru_head.prev = &lru_head; |
| 108 | } |
| 109 | |
| 110 | Cache::~Cache() |
| 111 | { |
| 112 | for(head_t *h = lru_head.next; h != &lru_head; h=h->next) |
| 113 | free(h->data); |
| 114 | free(head); |
| 115 | } |
| 116 | |
| 117 | void Cache::lru_delete(head_t *h) |
| 118 | { |
| 119 | // delete from current location |
| 120 | h->prev->next = h->next; |
| 121 | h->next->prev = h->prev; |
| 122 | } |
| 123 | |
| 124 | void Cache::lru_insert(head_t *h) |
| 125 | { |
| 126 | // insert to last position |
| 127 | h->next = &lru_head; |
| 128 | h->prev = lru_head.prev; |
| 129 | h->prev->next = h; |
| 130 | h->next->prev = h; |
| 131 | } |
| 132 | |
| 133 | int Cache::get_data(const int index, Qfloat **data, int len) |
| 134 | { |
| 135 | head_t *h = &head[index]; |
| 136 | if(h->len) lru_delete(h); |
| 137 | int more = len - h->len; |
| 138 | |
| 139 | if(more > 0) |
| 140 | { |
| 141 | // free old space |
| 142 | while(size < more) |
| 143 | { |
| 144 | head_t *old = lru_head.next; |
| 145 | lru_delete(old); |
| 146 | free(old->data); |
| 147 | size += old->len; |
| 148 | old->data = 0; |
| 149 | old->len = 0; |
| 150 | } |
| 151 | |
| 152 | // allocate new space |
| 153 | h->data = (Qfloat *)realloc(h->data,sizeof(Qfloat)*len); |
| 154 | size -= more; |
| 155 | swap(h->len,len); |
| 156 | } |
| 157 | |
| 158 | lru_insert(h); |
| 159 | *data = h->data; |
| 160 | return len; |
| 161 | } |
| 162 | |
| 163 | void Cache::swap_index(int i, int j) |
| 164 | { |
| 165 | if(i==j) return; |
| 166 | |
| 167 | if(head[i].len) lru_delete(&head[i]); |
| 168 | if(head[j].len) lru_delete(&head[j]); |
| 169 | swap(head[i].data,head[j].data); |
| 170 | swap(head[i].len,head[j].len); |
| 171 | if(head[i].len) lru_insert(&head[i]); |
| 172 | if(head[j].len) lru_insert(&head[j]); |
| 173 | |
| 174 | if(i>j) swap(i,j); |
| 175 | for(head_t *h = lru_head.next; h!=&lru_head; h=h->next) |
| 176 | { |
| 177 | if(h->len > i) |
| 178 | { |
| 179 | if(h->len > j) |
| 180 | swap(h->data[i],h->data[j]); |
| 181 | else |
| 182 | { |
| 183 | // give up |
| 184 | lru_delete(h); |
| 185 | free(h->data); |
| 186 | size += h->len; |
| 187 | h->data = 0; |
| 188 | h->len = 0; |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | // |
| 195 | // Kernel evaluation |
| 196 | // |
| 197 | // the static method k_function is for doing single kernel evaluation |
| 198 | // the constructor of Kernel prepares to calculate the l*l kernel matrix |
| 199 | // the member function get_Q is for getting one column from the Q Matrix |
| 200 | // |
| 201 | class QMatrix { |
| 202 | public: |
| 203 | virtual Qfloat *get_Q(int column, int len) const = 0; |
| 204 | virtual double *get_QD() const = 0; |
| 205 | virtual void swap_index(int i, int j) const = 0; |
| 206 | virtual ~QMatrix() {} |
| 207 | }; |
| 208 | |
| 209 | class Kernel: public QMatrix { |
| 210 | public: |
| 211 | Kernel(int l, svm_node * const * x, const svm_parameter& param); |
| 212 | virtual ~Kernel(); |
| 213 | |
| 214 | static double k_function(const svm_node *x, const svm_node *y, |
| 215 | const svm_parameter& param); |
| 216 | virtual Qfloat *get_Q(int column, int len) const = 0; |
| 217 | virtual double *get_QD() const = 0; |
| 218 | virtual void swap_index(int i, int j) const // no so const... |
| 219 | { |
| 220 | swap(x[i],x[j]); |
| 221 | if(x_square) swap(x_square[i],x_square[j]); |
| 222 | } |
| 223 | protected: |
| 224 | |
| 225 | double (Kernel::*kernel_function)(int i, int j) const; |
| 226 | |
| 227 | private: |
| 228 | const svm_node **x; |
| 229 | double *x_square; |
| 230 | |
| 231 | // svm_parameter |
| 232 | const int kernel_type; |
| 233 | const int degree; |
| 234 | const double gamma; |
| 235 | const double coef0; |
| 236 | |
| 237 | static double dot(const svm_node *px, const svm_node *py); |
| 238 | double kernel_linear(int i, int j) const |
| 239 | { |
| 240 | return dot(x[i],x[j]); |
| 241 | } |
| 242 | double kernel_poly(int i, int j) const |
| 243 | { |
| 244 | return powi(gamma*dot(x[i],x[j])+coef0,degree); |
| 245 | } |
| 246 | double kernel_rbf(int i, int j) const |
| 247 | { |
| 248 | return exp(-gamma*(x_square[i]+x_square[j]-2*dot(x[i],x[j]))); |
| 249 | } |
| 250 | double kernel_sigmoid(int i, int j) const |
| 251 | { |
| 252 | return tanh(gamma*dot(x[i],x[j])+coef0); |
| 253 | } |
| 254 | double kernel_precomputed(int i, int j) const |
| 255 | { |
| 256 | return x[i][(int)(x[j][0].value)].value; |
| 257 | } |
| 258 | }; |
| 259 | |
| 260 | Kernel::Kernel(int l, svm_node * const * x_, const svm_parameter& param) |
| 261 | :kernel_type(param.kernel_type), degree(param.degree), |
| 262 | gamma(param.gamma), coef0(param.coef0) |
| 263 | { |
| 264 | switch(kernel_type) |
| 265 | { |
| 266 | case LINEAR: |
| 267 | kernel_function = &Kernel::kernel_linear; |
| 268 | break; |
| 269 | case POLY: |
| 270 | kernel_function = &Kernel::kernel_poly; |
| 271 | break; |
| 272 | case RBF: |
| 273 | kernel_function = &Kernel::kernel_rbf; |
| 274 | break; |
| 275 | case SIGMOID: |
| 276 | kernel_function = &Kernel::kernel_sigmoid; |
| 277 | break; |
| 278 | case PRECOMPUTED: |
| 279 | kernel_function = &Kernel::kernel_precomputed; |
| 280 | break; |
| 281 | } |
| 282 | |
| 283 | clone(x,x_,l); |
| 284 | |
| 285 | if(kernel_type == RBF) |
| 286 | { |
| 287 | x_square = new double[l]; |
| 288 | for(int i=0;i<l;i++) |
| 289 | x_square[i] = dot(x[i],x[i]); |
| 290 | } |
| 291 | else |
| 292 | x_square = 0; |
| 293 | } |
| 294 | |
| 295 | Kernel::~Kernel() |
| 296 | { |
| 297 | delete[] x; |
| 298 | delete[] x_square; |
| 299 | } |
| 300 | |
| 301 | double Kernel::dot(const svm_node *px, const svm_node *py) |
| 302 | { |
| 303 | double sum = 0; |
| 304 | while(px->index != -1 && py->index != -1) |
| 305 | { |
| 306 | if(px->index == py->index) |
| 307 | { |
| 308 | sum += px->value * py->value; |
| 309 | ++px; |
| 310 | ++py; |
| 311 | } |
| 312 | else |
| 313 | { |
| 314 | if(px->index > py->index) |
| 315 | ++py; |
| 316 | else |
| 317 | ++px; |
| 318 | } |
| 319 | } |
| 320 | return sum; |
| 321 | } |
| 322 | |
| 323 | double Kernel::k_function(const svm_node *x, const svm_node *y, |
| 324 | const svm_parameter& param) |
| 325 | { |
| 326 | switch(param.kernel_type) |
| 327 | { |
| 328 | case LINEAR: |
| 329 | return dot(x,y); |
| 330 | case POLY: |
| 331 | return powi(param.gamma*dot(x,y)+param.coef0,param.degree); |
| 332 | case RBF: |
| 333 | { |
| 334 | double sum = 0; |
| 335 | while(x->index != -1 && y->index !=-1) |
| 336 | { |
| 337 | if(x->index == y->index) |
| 338 | { |
| 339 | double d = x->value - y->value; |
| 340 | sum += d*d; |
| 341 | ++x; |
| 342 | ++y; |
| 343 | } |
| 344 | else |
| 345 | { |
| 346 | if(x->index > y->index) |
| 347 | { |
| 348 | sum += y->value * y->value; |
| 349 | ++y; |
| 350 | } |
| 351 | else |
| 352 | { |
| 353 | sum += x->value * x->value; |
| 354 | ++x; |
| 355 | } |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | while(x->index != -1) |
| 360 | { |
| 361 | sum += x->value * x->value; |
| 362 | ++x; |
| 363 | } |
| 364 | |
| 365 | while(y->index != -1) |
| 366 | { |
| 367 | sum += y->value * y->value; |
| 368 | ++y; |
| 369 | } |
| 370 | |
| 371 | return exp(-param.gamma*sum); |
| 372 | } |
| 373 | case SIGMOID: |
| 374 | return tanh(param.gamma*dot(x,y)+param.coef0); |
| 375 | case PRECOMPUTED: //x: test (validation), y: SV |
| 376 | return x[(int)(y->value)].value; |
| 377 | default: |
| 378 | return 0; // Unreachable |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | // An SMO algorithm in Fan et al., JMLR 6(2005), p. 1889--1918 |
| 383 | // Solves: |
| 384 | // |
| 385 | // min 0.5(\alpha^T Q \alpha) + p^T \alpha |
| 386 | // |
| 387 | // y^T \alpha = \delta |
| 388 | // y_i = +1 or -1 |
| 389 | // 0 <= alpha_i <= Cp for y_i = 1 |
| 390 | // 0 <= alpha_i <= Cn for y_i = -1 |
| 391 | // |
| 392 | // Given: |
| 393 | // |
| 394 | // Q, p, y, Cp, Cn, and an initial feasible point \alpha |
| 395 | // l is the size of vectors and matrices |
| 396 | // eps is the stopping tolerance |
| 397 | // |
| 398 | // solution will be put in \alpha, objective value will be put in obj |
| 399 | // |
| 400 | class Solver { |
| 401 | public: |
| 402 | Solver() {}; |
| 403 | virtual ~Solver() {}; |
| 404 | |
| 405 | struct SolutionInfo { |
| 406 | double obj; |
| 407 | double rho; |
| 408 | double upper_bound_p; |
| 409 | double upper_bound_n; |
| 410 | double r; // for Solver_NU |
| 411 | }; |
| 412 | |
| 413 | void Solve(int l, const QMatrix& Q, const double *p_, const schar *y_, |
| 414 | double *alpha_, double Cp, double Cn, double eps, |
| 415 | SolutionInfo* si, int shrinking, bool verbose=false); |
| 416 | protected: |
| 417 | int active_size; |
| 418 | schar *y; |
| 419 | double *G; // gradient of objective function |
| 420 | enum { LOWER_BOUND, UPPER_BOUND, FREE }; |
| 421 | char *alpha_status; // LOWER_BOUND, UPPER_BOUND, FREE |
| 422 | double *alpha; |
| 423 | const QMatrix *Q; |
| 424 | const double *QD; |
| 425 | double eps; |
| 426 | double Cp,Cn; |
| 427 | double *p; |
| 428 | int *active_set; |
| 429 | double *G_bar; // gradient, if we treat free variables as 0 |
| 430 | int l; |
| 431 | bool unshrink; // XXX |
| 432 | |
| 433 | double get_C(int i) |
| 434 | { |
| 435 | return (y[i] > 0)? Cp : Cn; |
| 436 | } |
| 437 | void update_alpha_status(int i) |
| 438 | { |
| 439 | if(alpha[i] >= get_C(i)) |
| 440 | alpha_status[i] = UPPER_BOUND; |
| 441 | else if(alpha[i] <= 0) |
| 442 | alpha_status[i] = LOWER_BOUND; |
| 443 | else alpha_status[i] = FREE; |
| 444 | } |
| 445 | bool is_upper_bound(int i) { return alpha_status[i] == UPPER_BOUND; } |
| 446 | bool is_lower_bound(int i) { return alpha_status[i] == LOWER_BOUND; } |
| 447 | bool is_free(int i) { return alpha_status[i] == FREE; } |
| 448 | void swap_index(int i, int j); |
| 449 | void reconstruct_gradient(); |
| 450 | virtual int select_working_set(int &i, int &j); |
| 451 | virtual double calculate_rho(); |
| 452 | virtual void do_shrinking(); |
| 453 | private: |
| 454 | bool be_shrunk(int i, double Gmax1, double Gmax2); |
| 455 | }; |
| 456 | |
| 457 | void Solver::swap_index(int i, int j) |
| 458 | { |
| 459 | Q->swap_index(i,j); |
| 460 | swap(y[i],y[j]); |
| 461 | swap(G[i],G[j]); |
| 462 | swap(alpha_status[i],alpha_status[j]); |
| 463 | swap(alpha[i],alpha[j]); |
| 464 | swap(p[i],p[j]); |
| 465 | swap(active_set[i],active_set[j]); |
| 466 | swap(G_bar[i],G_bar[j]); |
| 467 | } |
| 468 | |
| 469 | void Solver::reconstruct_gradient() |
| 470 | { |
| 471 | // reconstruct inactive elements of G from G_bar and free variables |
| 472 | |
| 473 | if(active_size == l) return; |
| 474 | |
| 475 | int i,j; |
| 476 | int nr_free = 0; |
| 477 | |
| 478 | for(j=active_size;j<l;j++) |
| 479 | G[j] = G_bar[j] + p[j]; |
| 480 | |
| 481 | for(j=0;j<active_size;j++) |
| 482 | if(is_free(j)) |
| 483 | nr_free++; |
| 484 | |
| 485 | if(2*nr_free < active_size) |
| 486 | info("\nWARNING: using -h 0 may be faster\n"); |
| 487 | |
| 488 | if (nr_free*l > 2*active_size*(l-active_size)) |
| 489 | { |
| 490 | for(i=active_size;i<l;i++) |
| 491 | { |
| 492 | const Qfloat *Q_i = Q->get_Q(i,active_size); |
| 493 | for(j=0;j<active_size;j++) |
| 494 | if(is_free(j)) |
| 495 | G[i] += alpha[j] * Q_i[j]; |
| 496 | } |
| 497 | } |
| 498 | else |
| 499 | { |
| 500 | for(i=0;i<active_size;i++) |
| 501 | if(is_free(i)) |
| 502 | { |
| 503 | const Qfloat *Q_i = Q->get_Q(i,l); |
| 504 | double alpha_i = alpha[i]; |
| 505 | for(j=active_size;j<l;j++) |
| 506 | G[j] += alpha_i * Q_i[j]; |
| 507 | } |
| 508 | } |
| 509 | } |
| 510 | |
| 511 | void Solver::Solve(int l, const QMatrix& Q, const double *p_, const schar *y_, |
| 512 | double *alpha_, double Cp, double Cn, double eps, |
| 513 | SolutionInfo* si, int shrinking, |
| 514 | bool verbose)//pk |
| 515 | { |
| 516 | this->l = l; |
| 517 | this->Q = &Q; |
| 518 | QD=Q.get_QD(); |
| 519 | clone(p, p_,l); |
| 520 | clone(y, y_,l); |
| 521 | clone(alpha,alpha_,l); |
| 522 | this->Cp = Cp; |
| 523 | this->Cn = Cn; |
| 524 | this->eps = eps; |
| 525 | unshrink = false; |
| 526 | |
| 527 | // initialize alpha_status |
| 528 | { |
| 529 | alpha_status = new char[l]; |
| 530 | for(int i=0;i<l;i++) |
| 531 | update_alpha_status(i); |
| 532 | } |
| 533 | |
| 534 | // initialize active set (for shrinking) |
| 535 | { |
| 536 | active_set = new int[l]; |
| 537 | for(int i=0;i<l;i++) |
| 538 | active_set[i] = i; |
| 539 | active_size = l; |
| 540 | } |
| 541 | |
| 542 | // initialize gradient |
| 543 | { |
| 544 | G = new double[l]; |
| 545 | G_bar = new double[l]; |
| 546 | int i; |
| 547 | for(i=0;i<l;i++) |
| 548 | { |
| 549 | G[i] = p[i]; |
| 550 | G_bar[i] = 0; |
| 551 | } |
| 552 | for(i=0;i<l;i++) |
| 553 | if(!is_lower_bound(i)) |
| 554 | { |
| 555 | const Qfloat *Q_i = Q.get_Q(i,l); |
| 556 | double alpha_i = alpha[i]; |
| 557 | int j; |
| 558 | for(j=0;j<l;j++) |
| 559 | G[j] += alpha_i*Q_i[j]; |
| 560 | if(is_upper_bound(i)) |
| 561 | for(j=0;j<l;j++) |
| 562 | G_bar[j] += get_C(i) * Q_i[j]; |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | // optimization step |
| 567 | |
| 568 | int iter = 0; |
| 569 | int max_iter = max(10000000, l>INT_MAX/100 ? INT_MAX : 100*l); |
| 570 | int counter = min(l,1000)+1; |
| 571 | |
| 572 | while(iter < max_iter) |
| 573 | { |
| 574 | // show progress and do shrinking |
| 575 | |
| 576 | if(--counter == 0) |
| 577 | { |
| 578 | counter = min(l,1000); |
| 579 | if(shrinking) do_shrinking(); |
| 580 | if(verbose)//pk |
| 581 | info("."); |
| 582 | } |
| 583 | |
| 584 | int i,j; |
| 585 | if(select_working_set(i,j)!=0) |
| 586 | { |
| 587 | // reconstruct the whole gradient |
| 588 | reconstruct_gradient(); |
| 589 | // reset active set size and check |
| 590 | active_size = l; |
| 591 | if(verbose)//pk |
| 592 | info("*"); |
| 593 | if(select_working_set(i,j)!=0) |
| 594 | break; |
| 595 | else |
| 596 | counter = 1; // do shrinking next iteration |
| 597 | } |
| 598 | |
| 599 | ++iter; |
| 600 | |
| 601 | // update alpha[i] and alpha[j], handle bounds carefully |
| 602 | |
| 603 | const Qfloat *Q_i = Q.get_Q(i,active_size); |
| 604 | const Qfloat *Q_j = Q.get_Q(j,active_size); |
| 605 | |
| 606 | double C_i = get_C(i); |
| 607 | double C_j = get_C(j); |
| 608 | |
| 609 | double old_alpha_i = alpha[i]; |
| 610 | double old_alpha_j = alpha[j]; |
| 611 | |
| 612 | if(y[i]!=y[j]) |
| 613 | { |
| 614 | double quad_coef = QD[i]+QD[j]+2*Q_i[j]; |
| 615 | if (quad_coef <= 0) |
| 616 | quad_coef = TAU; |
| 617 | double delta = (-G[i]-G[j])/quad_coef; |
| 618 | double diff = alpha[i] - alpha[j]; |
| 619 | alpha[i] += delta; |
| 620 | alpha[j] += delta; |
| 621 | |
| 622 | if(diff > 0) |
| 623 | { |
| 624 | if(alpha[j] < 0) |
| 625 | { |
| 626 | alpha[j] = 0; |
| 627 | alpha[i] = diff; |
| 628 | } |
| 629 | } |
| 630 | else |
| 631 | { |
| 632 | if(alpha[i] < 0) |
| 633 | { |
| 634 | alpha[i] = 0; |
| 635 | alpha[j] = -diff; |
| 636 | } |
| 637 | } |
| 638 | if(diff > C_i - C_j) |
| 639 | { |
| 640 | if(alpha[i] > C_i) |
| 641 | { |
| 642 | alpha[i] = C_i; |
| 643 | alpha[j] = C_i - diff; |
| 644 | } |
| 645 | } |
| 646 | else |
| 647 | { |
| 648 | if(alpha[j] > C_j) |
| 649 | { |
| 650 | alpha[j] = C_j; |
| 651 | alpha[i] = C_j + diff; |
| 652 | } |
| 653 | } |
| 654 | } |
| 655 | else |
| 656 | { |
| 657 | double quad_coef = QD[i]+QD[j]-2*Q_i[j]; |
| 658 | if (quad_coef <= 0) |
| 659 | quad_coef = TAU; |
| 660 | double delta = (G[i]-G[j])/quad_coef; |
| 661 | double sum = alpha[i] + alpha[j]; |
| 662 | alpha[i] -= delta; |
| 663 | alpha[j] += delta; |
| 664 | |
| 665 | if(sum > C_i) |
| 666 | { |
| 667 | if(alpha[i] > C_i) |
| 668 | { |
| 669 | alpha[i] = C_i; |
| 670 | alpha[j] = sum - C_i; |
| 671 | } |
| 672 | } |
| 673 | else |
| 674 | { |
| 675 | if(alpha[j] < 0) |
| 676 | { |
| 677 | alpha[j] = 0; |
| 678 | alpha[i] = sum; |
| 679 | } |
| 680 | } |
| 681 | if(sum > C_j) |
| 682 | { |
| 683 | if(alpha[j] > C_j) |
| 684 | { |
| 685 | alpha[j] = C_j; |
| 686 | alpha[i] = sum - C_j; |
| 687 | } |
| 688 | } |
| 689 | else |
| 690 | { |
| 691 | if(alpha[i] < 0) |
| 692 | { |
| 693 | alpha[i] = 0; |
| 694 | alpha[j] = sum; |
| 695 | } |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | // update G |
| 700 | |
| 701 | double delta_alpha_i = alpha[i] - old_alpha_i; |
| 702 | double delta_alpha_j = alpha[j] - old_alpha_j; |
| 703 | |
| 704 | for(int k=0;k<active_size;k++) |
| 705 | { |
| 706 | G[k] += Q_i[k]*delta_alpha_i + Q_j[k]*delta_alpha_j; |
| 707 | } |
| 708 | |
| 709 | // update alpha_status and G_bar |
| 710 | |
| 711 | { |
| 712 | bool ui = is_upper_bound(i); |
| 713 | bool uj = is_upper_bound(j); |
| 714 | update_alpha_status(i); |
| 715 | update_alpha_status(j); |
| 716 | int k; |
| 717 | if(ui != is_upper_bound(i)) |
| 718 | { |
| 719 | Q_i = Q.get_Q(i,l); |
| 720 | if(ui) |
| 721 | for(k=0;k<l;k++) |
| 722 | G_bar[k] -= C_i * Q_i[k]; |
| 723 | else |
| 724 | for(k=0;k<l;k++) |
| 725 | G_bar[k] += C_i * Q_i[k]; |
| 726 | } |
| 727 | |
| 728 | if(uj != is_upper_bound(j)) |
| 729 | { |
| 730 | Q_j = Q.get_Q(j,l); |
| 731 | if(uj) |
| 732 | for(k=0;k<l;k++) |
| 733 | G_bar[k] -= C_j * Q_j[k]; |
| 734 | else |
| 735 | for(k=0;k<l;k++) |
| 736 | G_bar[k] += C_j * Q_j[k]; |
| 737 | } |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | if(iter >= max_iter) |
| 742 | { |
| 743 | if(active_size < l) |
| 744 | { |
| 745 | // reconstruct the whole gradient to calculate objective value |
| 746 | reconstruct_gradient(); |
| 747 | active_size = l; |
| 748 | if(verbose)//pk |
| 749 | info("*"); |
| 750 | } |
| 751 | info("\nWARNING: reaching max number of iterations"); |
| 752 | } |
| 753 | |
| 754 | // calculate rho |
| 755 | |
| 756 | si->rho = calculate_rho(); |
| 757 | |
| 758 | // calculate objective value |
| 759 | { |
| 760 | double v = 0; |
| 761 | int i; |
| 762 | for(i=0;i<l;i++) |
| 763 | v += alpha[i] * (G[i] + p[i]); |
| 764 | |
| 765 | si->obj = v/2; |
| 766 | } |
| 767 | |
| 768 | // put back the solution |
| 769 | { |
| 770 | for(int i=0;i<l;i++) |
| 771 | alpha_[active_set[i]] = alpha[i]; |
| 772 | } |
| 773 | |
| 774 | // juggle everything back |
| 775 | /*{ |
| 776 | for(int i=0;i<l;i++) |
| 777 | while(active_set[i] != i) |
| 778 | swap_index(i,active_set[i]); |
| 779 | // or Q.swap_index(i,active_set[i]); |
| 780 | }*/ |
| 781 | |
| 782 | si->upper_bound_p = Cp; |
| 783 | si->upper_bound_n = Cn; |
| 784 | |
| 785 | if(verbose)//pk |
| 786 | info("\noptimization finished, #iter = %d\n",iter); |
| 787 | |
| 788 | delete[] p; |
| 789 | delete[] y; |
| 790 | delete[] alpha; |
| 791 | delete[] alpha_status; |
| 792 | delete[] active_set; |
| 793 | delete[] G; |
| 794 | delete[] G_bar; |
| 795 | } |
| 796 | |
| 797 | // return 1 if already optimal, return 0 otherwise |
| 798 | int Solver::select_working_set(int &out_i, int &out_j) |
| 799 | { |
| 800 | // return i,j such that |
| 801 | // i: maximizes -y_i * grad(f)_i, i in I_up(\alpha) |
| 802 | // j: minimizes the decrease of obj value |
| 803 | // (if quadratic coefficeint <= 0, replace it with tau) |
| 804 | // -y_j*grad(f)_j < -y_i*grad(f)_i, j in I_low(\alpha) |
| 805 | |
| 806 | double Gmax = -INF; |
| 807 | double Gmax2 = -INF; |
| 808 | int Gmax_idx = -1; |
| 809 | int Gmin_idx = -1; |
| 810 | double obj_diff_min = INF; |
| 811 | |
| 812 | for(int t=0;t<active_size;t++) |
| 813 | if(y[t]==+1) |
| 814 | { |
| 815 | if(!is_upper_bound(t)) |
| 816 | if(-G[t] >= Gmax) |
| 817 | { |
| 818 | Gmax = -G[t]; |
| 819 | Gmax_idx = t; |
| 820 | } |
| 821 | } |
| 822 | else |
| 823 | { |
| 824 | if(!is_lower_bound(t)) |
| 825 | if(G[t] >= Gmax) |
| 826 | { |
| 827 | Gmax = G[t]; |
| 828 | Gmax_idx = t; |
| 829 | } |
| 830 | } |
| 831 | |
| 832 | int i = Gmax_idx; |
| 833 | const Qfloat *Q_i = NULL; |
| 834 | if(i != -1) // NULL Q_i not accessed: Gmax=-INF if i=-1 |
| 835 | Q_i = Q->get_Q(i,active_size); |
| 836 | |
| 837 | for(int j=0;j<active_size;j++) |
| 838 | { |
| 839 | if(y[j]==+1) |
| 840 | { |
| 841 | if (!is_lower_bound(j)) |
| 842 | { |
| 843 | double grad_diff=Gmax+G[j]; |
| 844 | if (G[j] >= Gmax2) |
| 845 | Gmax2 = G[j]; |
| 846 | if (grad_diff > 0) |
| 847 | { |
| 848 | double obj_diff; |
| 849 | double quad_coef = QD[i]+QD[j]-2.0*y[i]*Q_i[j]; |
| 850 | if (quad_coef > 0) |
| 851 | obj_diff = -(grad_diff*grad_diff)/quad_coef; |
| 852 | else |
| 853 | obj_diff = -(grad_diff*grad_diff)/TAU; |
| 854 | |
| 855 | if (obj_diff <= obj_diff_min) |
| 856 | { |
| 857 | Gmin_idx=j; |
| 858 | obj_diff_min = obj_diff; |
| 859 | } |
| 860 | } |
| 861 | } |
| 862 | } |
| 863 | else |
| 864 | { |
| 865 | if (!is_upper_bound(j)) |
| 866 | { |
| 867 | double grad_diff= Gmax-G[j]; |
| 868 | if (-G[j] >= Gmax2) |
| 869 | Gmax2 = -G[j]; |
| 870 | if (grad_diff > 0) |
| 871 | { |
| 872 | double obj_diff; |
| 873 | double quad_coef = QD[i]+QD[j]+2.0*y[i]*Q_i[j]; |
| 874 | if (quad_coef > 0) |
| 875 | obj_diff = -(grad_diff*grad_diff)/quad_coef; |
| 876 | else |
| 877 | obj_diff = -(grad_diff*grad_diff)/TAU; |
| 878 | |
| 879 | if (obj_diff <= obj_diff_min) |
| 880 | { |
| 881 | Gmin_idx=j; |
| 882 | obj_diff_min = obj_diff; |
| 883 | } |
| 884 | } |
| 885 | } |
| 886 | } |
| 887 | } |
| 888 | |
| 889 | if(Gmax+Gmax2 < eps) |
| 890 | return 1; |
| 891 | |
| 892 | out_i = Gmax_idx; |
| 893 | out_j = Gmin_idx; |
| 894 | return 0; |
| 895 | } |
| 896 | |
| 897 | bool Solver::be_shrunk(int i, double Gmax1, double Gmax2) |
| 898 | { |
| 899 | if(is_upper_bound(i)) |
| 900 | { |
| 901 | if(y[i]==+1) |
| 902 | return(-G[i] > Gmax1); |
| 903 | else |
| 904 | return(-G[i] > Gmax2); |
| 905 | } |
| 906 | else if(is_lower_bound(i)) |
| 907 | { |
| 908 | if(y[i]==+1) |
| 909 | return(G[i] > Gmax2); |
| 910 | else |
| 911 | return(G[i] > Gmax1); |
| 912 | } |
| 913 | else |
| 914 | return(false); |
| 915 | } |
| 916 | |
| 917 | void Solver::do_shrinking() |
| 918 | { |
| 919 | int i; |
| 920 | double Gmax1 = -INF; // max { -y_i * grad(f)_i | i in I_up(\alpha) } |
| 921 | double Gmax2 = -INF; // max { y_i * grad(f)_i | i in I_low(\alpha) } |
| 922 | |
| 923 | // find maximal violating pair first |
| 924 | for(i=0;i<active_size;i++) |
| 925 | { |
| 926 | if(y[i]==+1) |
| 927 | { |
| 928 | if(!is_upper_bound(i)) |
| 929 | { |
| 930 | if(-G[i] >= Gmax1) |
| 931 | Gmax1 = -G[i]; |
| 932 | } |
| 933 | if(!is_lower_bound(i)) |
| 934 | { |
| 935 | if(G[i] >= Gmax2) |
| 936 | Gmax2 = G[i]; |
| 937 | } |
| 938 | } |
| 939 | else |
| 940 | { |
| 941 | if(!is_upper_bound(i)) |
| 942 | { |
| 943 | if(-G[i] >= Gmax2) |
| 944 | Gmax2 = -G[i]; |
| 945 | } |
| 946 | if(!is_lower_bound(i)) |
| 947 | { |
| 948 | if(G[i] >= Gmax1) |
| 949 | Gmax1 = G[i]; |
| 950 | } |
| 951 | } |
| 952 | } |
| 953 | |
| 954 | if(unshrink == false && Gmax1 + Gmax2 <= eps*10) |
| 955 | { |
| 956 | unshrink = true; |
| 957 | reconstruct_gradient(); |
| 958 | active_size = l; |
| 959 | info("*"); |
| 960 | } |
| 961 | |
| 962 | for(i=0;i<active_size;i++) |
| 963 | if (be_shrunk(i, Gmax1, Gmax2)) |
| 964 | { |
| 965 | active_size--; |
| 966 | while (active_size > i) |
| 967 | { |
| 968 | if (!be_shrunk(active_size, Gmax1, Gmax2)) |
| 969 | { |
| 970 | swap_index(i,active_size); |
| 971 | break; |
| 972 | } |
| 973 | active_size--; |
| 974 | } |
| 975 | } |
| 976 | } |
| 977 | |
| 978 | double Solver::calculate_rho() |
| 979 | { |
| 980 | double r; |
| 981 | int nr_free = 0; |
| 982 | double ub = INF, lb = -INF, sum_free = 0; |
| 983 | for(int i=0;i<active_size;i++) |
| 984 | { |
| 985 | double yG = y[i]*G[i]; |
| 986 | |
| 987 | if(is_upper_bound(i)) |
| 988 | { |
| 989 | if(y[i]==-1) |
| 990 | ub = min(ub,yG); |
| 991 | else |
| 992 | lb = max(lb,yG); |
| 993 | } |
| 994 | else if(is_lower_bound(i)) |
| 995 | { |
| 996 | if(y[i]==+1) |
| 997 | ub = min(ub,yG); |
| 998 | else |
| 999 | lb = max(lb,yG); |
| 1000 | } |
| 1001 | else |
| 1002 | { |
| 1003 | ++nr_free; |
| 1004 | sum_free += yG; |
| 1005 | } |
| 1006 | } |
| 1007 | |
| 1008 | if(nr_free>0) |
| 1009 | r = sum_free/nr_free; |
| 1010 | else |
| 1011 | r = (ub+lb)/2; |
| 1012 | |
| 1013 | return r; |
| 1014 | } |
| 1015 | |
| 1016 | // |
| 1017 | // Solver for nu-svm classification and regression |
| 1018 | // |
| 1019 | // additional constraint: e^T \alpha = constant |
| 1020 | // |
| 1021 | class Solver_NU : public Solver |
| 1022 | { |
| 1023 | public: |
| 1024 | Solver_NU() {} |
| 1025 | void Solve(int l, const QMatrix& Q, const double *p, const schar *y, |
| 1026 | double *alpha, double Cp, double Cn, double eps, |
| 1027 | SolutionInfo* si, int shrinking, bool verbose=false) |
| 1028 | { |
| 1029 | this->si = si; |
| 1030 | Solver::Solve(l,Q,p,y,alpha,Cp,Cn,eps,si,shrinking,verbose); |
| 1031 | } |
| 1032 | private: |
| 1033 | SolutionInfo *si; |
| 1034 | int select_working_set(int &i, int &j); |
| 1035 | double calculate_rho(); |
| 1036 | bool be_shrunk(int i, double Gmax1, double Gmax2, double Gmax3, double Gmax4); |
| 1037 | void do_shrinking(); |
| 1038 | }; |
| 1039 | |
| 1040 | // return 1 if already optimal, return 0 otherwise |
| 1041 | int Solver_NU::select_working_set(int &out_i, int &out_j) |
| 1042 | { |
| 1043 | // return i,j such that y_i = y_j and |
| 1044 | // i: maximizes -y_i * grad(f)_i, i in I_up(\alpha) |
| 1045 | // j: minimizes the decrease of obj value |
| 1046 | // (if quadratic coefficeint <= 0, replace it with tau) |
| 1047 | // -y_j*grad(f)_j < -y_i*grad(f)_i, j in I_low(\alpha) |
| 1048 | |
| 1049 | double Gmaxp = -INF; |
| 1050 | double Gmaxp2 = -INF; |
| 1051 | int Gmaxp_idx = -1; |
| 1052 | |
| 1053 | double Gmaxn = -INF; |
| 1054 | double Gmaxn2 = -INF; |
| 1055 | int Gmaxn_idx = -1; |
| 1056 | |
| 1057 | int Gmin_idx = -1; |
| 1058 | double obj_diff_min = INF; |
| 1059 | |
| 1060 | for(int t=0;t<active_size;t++) |
| 1061 | if(y[t]==+1) |
| 1062 | { |
| 1063 | if(!is_upper_bound(t)) |
| 1064 | if(-G[t] >= Gmaxp) |
| 1065 | { |
| 1066 | Gmaxp = -G[t]; |
| 1067 | Gmaxp_idx = t; |
| 1068 | } |
| 1069 | } |
| 1070 | else |
| 1071 | { |
| 1072 | if(!is_lower_bound(t)) |
| 1073 | if(G[t] >= Gmaxn) |
| 1074 | { |
| 1075 | Gmaxn = G[t]; |
| 1076 | Gmaxn_idx = t; |
| 1077 | } |
| 1078 | } |
| 1079 | |
| 1080 | int ip = Gmaxp_idx; |
| 1081 | int in = Gmaxn_idx; |
| 1082 | const Qfloat *Q_ip = NULL; |
| 1083 | const Qfloat *Q_in = NULL; |
| 1084 | if(ip != -1) // NULL Q_ip not accessed: Gmaxp=-INF if ip=-1 |
| 1085 | Q_ip = Q->get_Q(ip,active_size); |
| 1086 | if(in != -1) |
| 1087 | Q_in = Q->get_Q(in,active_size); |
| 1088 | |
| 1089 | for(int j=0;j<active_size;j++) |
| 1090 | { |
| 1091 | if(y[j]==+1) |
| 1092 | { |
| 1093 | if (!is_lower_bound(j)) |
| 1094 | { |
| 1095 | double grad_diff=Gmaxp+G[j]; |
| 1096 | if (G[j] >= Gmaxp2) |
| 1097 | Gmaxp2 = G[j]; |
| 1098 | if (grad_diff > 0) |
| 1099 | { |
| 1100 | double obj_diff; |
| 1101 | double quad_coef = QD[ip]+QD[j]-2*Q_ip[j]; |
| 1102 | if (quad_coef > 0) |
| 1103 | obj_diff = -(grad_diff*grad_diff)/quad_coef; |
| 1104 | else |
| 1105 | obj_diff = -(grad_diff*grad_diff)/TAU; |
| 1106 | |
| 1107 | if (obj_diff <= obj_diff_min) |
| 1108 | { |
| 1109 | Gmin_idx=j; |
| 1110 | obj_diff_min = obj_diff; |
| 1111 | } |
| 1112 | } |
| 1113 | } |
| 1114 | } |
| 1115 | else |
| 1116 | { |
| 1117 | if (!is_upper_bound(j)) |
| 1118 | { |
| 1119 | double grad_diff=Gmaxn-G[j]; |
| 1120 | if (-G[j] >= Gmaxn2) |
| 1121 | Gmaxn2 = -G[j]; |
| 1122 | if (grad_diff > 0) |
| 1123 | { |
| 1124 | double obj_diff; |
| 1125 | double quad_coef = QD[in]+QD[j]-2*Q_in[j]; |
| 1126 | if (quad_coef > 0) |
| 1127 | obj_diff = -(grad_diff*grad_diff)/quad_coef; |
| 1128 | else |
| 1129 | obj_diff = -(grad_diff*grad_diff)/TAU; |
| 1130 | |
| 1131 | if (obj_diff <= obj_diff_min) |
| 1132 | { |
| 1133 | Gmin_idx=j; |
| 1134 | obj_diff_min = obj_diff; |
| 1135 | } |
| 1136 | } |
| 1137 | } |
| 1138 | } |
| 1139 | } |
| 1140 | |
| 1141 | if(max(Gmaxp+Gmaxp2,Gmaxn+Gmaxn2) < eps) |
| 1142 | return 1; |
| 1143 | |
| 1144 | if (y[Gmin_idx] == +1) |
| 1145 | out_i = Gmaxp_idx; |
| 1146 | else |
| 1147 | out_i = Gmaxn_idx; |
| 1148 | out_j = Gmin_idx; |
| 1149 | |
| 1150 | return 0; |
| 1151 | } |
| 1152 | |
| 1153 | bool Solver_NU::be_shrunk(int i, double Gmax1, double Gmax2, double Gmax3, double Gmax4) |
| 1154 | { |
| 1155 | if(is_upper_bound(i)) |
| 1156 | { |
| 1157 | if(y[i]==+1) |
| 1158 | return(-G[i] > Gmax1); |
| 1159 | else |
| 1160 | return(-G[i] > Gmax4); |
| 1161 | } |
| 1162 | else if(is_lower_bound(i)) |
| 1163 | { |
| 1164 | if(y[i]==+1) |
| 1165 | return(G[i] > Gmax2); |
| 1166 | else |
| 1167 | return(G[i] > Gmax3); |
| 1168 | } |
| 1169 | else |
| 1170 | return(false); |
| 1171 | } |
| 1172 | |
| 1173 | void Solver_NU::do_shrinking() |
| 1174 | { |
| 1175 | double Gmax1 = -INF; // max { -y_i * grad(f)_i | y_i = +1, i in I_up(\alpha) } |
| 1176 | double Gmax2 = -INF; // max { y_i * grad(f)_i | y_i = +1, i in I_low(\alpha) } |
| 1177 | double Gmax3 = -INF; // max { -y_i * grad(f)_i | y_i = -1, i in I_up(\alpha) } |
| 1178 | double Gmax4 = -INF; // max { y_i * grad(f)_i | y_i = -1, i in I_low(\alpha) } |
| 1179 | |
| 1180 | // find maximal violating pair first |
| 1181 | int i; |
| 1182 | for(i=0;i<active_size;i++) |
| 1183 | { |
| 1184 | if(!is_upper_bound(i)) |
| 1185 | { |
| 1186 | if(y[i]==+1) |
| 1187 | { |
| 1188 | if(-G[i] > Gmax1) Gmax1 = -G[i]; |
| 1189 | } |
| 1190 | else if(-G[i] > Gmax4) Gmax4 = -G[i]; |
| 1191 | } |
| 1192 | if(!is_lower_bound(i)) |
| 1193 | { |
| 1194 | if(y[i]==+1) |
| 1195 | { |
| 1196 | if(G[i] > Gmax2) Gmax2 = G[i]; |
| 1197 | } |
| 1198 | else if(G[i] > Gmax3) Gmax3 = G[i]; |
| 1199 | } |
| 1200 | } |
| 1201 | |
| 1202 | if(unshrink == false && max(Gmax1+Gmax2,Gmax3+Gmax4) <= eps*10) |
| 1203 | { |
| 1204 | unshrink = true; |
| 1205 | reconstruct_gradient(); |
| 1206 | active_size = l; |
| 1207 | } |
| 1208 | |
| 1209 | for(i=0;i<active_size;i++) |
| 1210 | if (be_shrunk(i, Gmax1, Gmax2, Gmax3, Gmax4)) |
| 1211 | { |
| 1212 | active_size--; |
| 1213 | while (active_size > i) |
| 1214 | { |
| 1215 | if (!be_shrunk(active_size, Gmax1, Gmax2, Gmax3, Gmax4)) |
| 1216 | { |
| 1217 | swap_index(i,active_size); |
| 1218 | break; |
| 1219 | } |
| 1220 | active_size--; |
| 1221 | } |
| 1222 | } |
| 1223 | } |
| 1224 | |
| 1225 | double Solver_NU::calculate_rho() |
| 1226 | { |
| 1227 | int nr_free1 = 0,nr_free2 = 0; |
| 1228 | double ub1 = INF, ub2 = INF; |
| 1229 | double lb1 = -INF, lb2 = -INF; |
| 1230 | double sum_free1 = 0, sum_free2 = 0; |
| 1231 | |
| 1232 | for(int i=0;i<active_size;i++) |
| 1233 | { |
| 1234 | if(y[i]==+1) |
| 1235 | { |
| 1236 | if(is_upper_bound(i)) |
| 1237 | lb1 = max(lb1,G[i]); |
| 1238 | else if(is_lower_bound(i)) |
| 1239 | ub1 = min(ub1,G[i]); |
| 1240 | else |
| 1241 | { |
| 1242 | ++nr_free1; |
| 1243 | sum_free1 += G[i]; |
| 1244 | } |
| 1245 | } |
| 1246 | else |
| 1247 | { |
| 1248 | if(is_upper_bound(i)) |
| 1249 | lb2 = max(lb2,G[i]); |
| 1250 | else if(is_lower_bound(i)) |
| 1251 | ub2 = min(ub2,G[i]); |
| 1252 | else |
| 1253 | { |
| 1254 | ++nr_free2; |
| 1255 | sum_free2 += G[i]; |
| 1256 | } |
| 1257 | } |
| 1258 | } |
| 1259 | |
| 1260 | double r1,r2; |
| 1261 | if(nr_free1 > 0) |
| 1262 | r1 = sum_free1/nr_free1; |
| 1263 | else |
| 1264 | r1 = (ub1+lb1)/2; |
| 1265 | |
| 1266 | if(nr_free2 > 0) |
| 1267 | r2 = sum_free2/nr_free2; |
| 1268 | else |
| 1269 | r2 = (ub2+lb2)/2; |
| 1270 | |
| 1271 | si->r = (r1+r2)/2; |
| 1272 | return (r1-r2)/2; |
| 1273 | } |
| 1274 | |
| 1275 | // |
| 1276 | // Q matrices for various formulations |
| 1277 | // |
| 1278 | class SVC_Q: public Kernel |
| 1279 | { |
| 1280 | public: |
| 1281 | SVC_Q(const svm_problem& prob, const svm_parameter& param, const schar *y_) |
| 1282 | :Kernel(prob.l, prob.x, param) |
| 1283 | { |
| 1284 | clone(y,y_,prob.l); |
| 1285 | cache = new Cache(prob.l,(long int)(param.cache_size*(1<<20))); |
| 1286 | QD = new double[prob.l]; |
| 1287 | for(int i=0;i<prob.l;i++) |
| 1288 | QD[i] = (this->*kernel_function)(i,i); |
| 1289 | } |
| 1290 | |
| 1291 | Qfloat *get_Q(int i, int len) const |
| 1292 | { |
| 1293 | Qfloat *data; |
| 1294 | int start, j; |
| 1295 | if((start = cache->get_data(i,&data,len)) < len) |
| 1296 | { |
| 1297 | #if JIPLIB_PROCESS_IN_PARALLEL == 1 |
| 1298 | #pragma omp parallel for private(j) schedule(guided) |
| 1299 | #else |
| 1300 | #endif |
| 1301 | for(j=start;j<len;j++) |
| 1302 | data[j] = (Qfloat)(y[i]*y[j]*(this->*kernel_function)(i,j)); |
| 1303 | } |
| 1304 | return data; |
| 1305 | } |
| 1306 | |
| 1307 | double *get_QD() const |
| 1308 | { |
| 1309 | return QD; |
| 1310 | } |
| 1311 | |
| 1312 | void swap_index(int i, int j) const |
| 1313 | { |
| 1314 | cache->swap_index(i,j); |
| 1315 | Kernel::swap_index(i,j); |
| 1316 | swap(y[i],y[j]); |
| 1317 | swap(QD[i],QD[j]); |
| 1318 | } |
| 1319 | |
| 1320 | ~SVC_Q() |
| 1321 | { |
| 1322 | delete[] y; |
| 1323 | delete cache; |
| 1324 | delete[] QD; |
| 1325 | } |
| 1326 | private: |
| 1327 | schar *y; |
| 1328 | Cache *cache; |
| 1329 | double *QD; |
| 1330 | }; |
| 1331 | |
| 1332 | class ONE_CLASS_Q: public Kernel |
| 1333 | { |
| 1334 | public: |
| 1335 | ONE_CLASS_Q(const svm_problem& prob, const svm_parameter& param) |
| 1336 | :Kernel(prob.l, prob.x, param) |
| 1337 | { |
| 1338 | cache = new Cache(prob.l,(long int)(param.cache_size*(1<<20))); |
| 1339 | QD = new double[prob.l]; |
| 1340 | for(int i=0;i<prob.l;i++) |
| 1341 | QD[i] = (this->*kernel_function)(i,i); |
| 1342 | } |
| 1343 | |
| 1344 | Qfloat *get_Q(int i, int len) const |
| 1345 | { |
| 1346 | Qfloat *data; |
| 1347 | int start, j; |
| 1348 | if((start = cache->get_data(i,&data,len)) < len) |
| 1349 | { |
| 1350 | for(j=start;j<len;j++) |
| 1351 | data[j] = (Qfloat)(this->*kernel_function)(i,j); |
| 1352 | } |
| 1353 | return data; |
| 1354 | } |
| 1355 | |
| 1356 | double *get_QD() const |
| 1357 | { |
| 1358 | return QD; |
| 1359 | } |
| 1360 | |
| 1361 | void swap_index(int i, int j) const |
| 1362 | { |
| 1363 | cache->swap_index(i,j); |
| 1364 | Kernel::swap_index(i,j); |
| 1365 | swap(QD[i],QD[j]); |
| 1366 | } |
| 1367 | |
| 1368 | ~ONE_CLASS_Q() |
| 1369 | { |
| 1370 | delete cache; |
| 1371 | delete[] QD; |
| 1372 | } |
| 1373 | private: |
| 1374 | Cache *cache; |
| 1375 | double *QD; |
| 1376 | }; |
| 1377 | |
| 1378 | class SVR_Q: public Kernel |
| 1379 | { |
| 1380 | public: |
| 1381 | SVR_Q(const svm_problem& prob, const svm_parameter& param) |
| 1382 | :Kernel(prob.l, prob.x, param) |
| 1383 | { |
| 1384 | l = prob.l; |
| 1385 | cache = new Cache(l,(long int)(param.cache_size*(1<<20))); |
| 1386 | QD = new double[2*l]; |
| 1387 | sign = new schar[2*l]; |
| 1388 | index = new int[2*l]; |
| 1389 | for(int k=0;k<l;k++) |
| 1390 | { |
| 1391 | sign[k] = 1; |
| 1392 | sign[k+l] = -1; |
| 1393 | index[k] = k; |
| 1394 | index[k+l] = k; |
| 1395 | QD[k] = (this->*kernel_function)(k,k); |
| 1396 | QD[k+l] = QD[k]; |
| 1397 | } |
| 1398 | buffer[0] = new Qfloat[2*l]; |
| 1399 | buffer[1] = new Qfloat[2*l]; |
| 1400 | next_buffer = 0; |
| 1401 | } |
| 1402 | |
| 1403 | void swap_index(int i, int j) const |
| 1404 | { |
| 1405 | swap(sign[i],sign[j]); |
| 1406 | swap(index[i],index[j]); |
| 1407 | swap(QD[i],QD[j]); |
| 1408 | } |
| 1409 | |
| 1410 | Qfloat *get_Q(int i, int len) const |
| 1411 | { |
| 1412 | Qfloat *data; |
| 1413 | int j, real_i = index[i]; |
| 1414 | if(cache->get_data(real_i,&data,l) < l) |
| 1415 | { |
| 1416 | #if JIPLIB_PROCESS_IN_PARALLEL == 1 |
| 1417 | #pragma omp parallel for private(j) schedule(guided) |
| 1418 | #else |
| 1419 | #endif |
| 1420 | for(j=0;j<l;j++) |
| 1421 | data[j] = (Qfloat)(this->*kernel_function)(real_i,j); |
| 1422 | } |
| 1423 | |
| 1424 | // reorder and copy |
| 1425 | Qfloat *buf = buffer[next_buffer]; |
| 1426 | next_buffer = 1 - next_buffer; |
| 1427 | schar si = sign[i]; |
| 1428 | for(j=0;j<len;j++) |
| 1429 | buf[j] = (Qfloat) si * (Qfloat) sign[j] * data[index[j]]; |
| 1430 | return buf; |
| 1431 | } |
| 1432 | |
| 1433 | double *get_QD() const |
| 1434 | { |
| 1435 | return QD; |
| 1436 | } |
| 1437 | |
| 1438 | ~SVR_Q() |
| 1439 | { |
| 1440 | delete cache; |
| 1441 | delete[] sign; |
| 1442 | delete[] index; |
| 1443 | delete[] buffer[0]; |
| 1444 | delete[] buffer[1]; |
| 1445 | delete[] QD; |
| 1446 | } |
| 1447 | private: |
| 1448 | int l; |
| 1449 | Cache *cache; |
| 1450 | schar *sign; |
| 1451 | int *index; |
| 1452 | mutable int next_buffer; |
| 1453 | Qfloat *buffer[2]; |
| 1454 | double *QD; |
| 1455 | }; |
| 1456 | |
| 1457 | // |
| 1458 | // construct and solve various formulations |
| 1459 | // |
| 1460 | static void solve_c_svc( |
| 1461 | const svm_problem *prob, const svm_parameter* param, |
| 1462 | double *alpha, Solver::SolutionInfo* si, double Cp, double Cn) |
| 1463 | { |
| 1464 | int l = prob->l; |
| 1465 | double *minus_ones = new double[l]; |
| 1466 | schar *y = new schar[l]; |
| 1467 | |
| 1468 | int i; |
| 1469 | |
| 1470 | for(i=0;i<l;i++) |
| 1471 | { |
| 1472 | alpha[i] = 0; |
| 1473 | minus_ones[i] = -1; |
| 1474 | if(prob->y[i] > 0) y[i] = +1; else y[i] = -1; |
| 1475 | } |
| 1476 | |
| 1477 | Solver s; |
| 1478 | s.Solve(l, SVC_Q(*prob,*param,y), minus_ones, y, |
| 1479 | alpha, Cp, Cn, param->eps, si, param->shrinking, param->verbose); |
| 1480 | |
| 1481 | double sum_alpha=0; |
| 1482 | for(i=0;i<l;i++) |
| 1483 | sum_alpha += alpha[i]; |
| 1484 | |
| 1485 | if (Cp==Cn) |
| 1486 | if(param->verbose)//pk |
| 1487 | info("nu = %f\n", sum_alpha/(Cp*prob->l)); |
| 1488 | |
| 1489 | for(i=0;i<l;i++) |
| 1490 | alpha[i] *= y[i]; |
| 1491 | |
| 1492 | delete[] minus_ones; |
| 1493 | delete[] y; |
| 1494 | } |
| 1495 | |
| 1496 | static void solve_nu_svc( |
| 1497 | const svm_problem *prob, const svm_parameter *param, |
| 1498 | double *alpha, Solver::SolutionInfo* si) |
| 1499 | { |
| 1500 | int i; |
| 1501 | int l = prob->l; |
| 1502 | double nu = param->nu; |
| 1503 | |
| 1504 | schar *y = new schar[l]; |
| 1505 | |
| 1506 | for(i=0;i<l;i++) |
| 1507 | if(prob->y[i]>0) |
| 1508 | y[i] = +1; |
| 1509 | else |
| 1510 | y[i] = -1; |
| 1511 | |
| 1512 | double sum_pos = nu*l/2; |
| 1513 | double sum_neg = nu*l/2; |
| 1514 | |
| 1515 | for(i=0;i<l;i++) |
| 1516 | if(y[i] == +1) |
| 1517 | { |
| 1518 | alpha[i] = min(1.0,sum_pos); |
| 1519 | sum_pos -= alpha[i]; |
| 1520 | } |
| 1521 | else |
| 1522 | { |
| 1523 | alpha[i] = min(1.0,sum_neg); |
| 1524 | sum_neg -= alpha[i]; |
| 1525 | } |
| 1526 | |
| 1527 | double *zeros = new double[l]; |
| 1528 | |
| 1529 | for(i=0;i<l;i++) |
| 1530 | zeros[i] = 0; |
| 1531 | |
| 1532 | Solver_NU s; |
| 1533 | s.Solve(l, SVC_Q(*prob,*param,y), zeros, y, |
| 1534 | alpha, 1.0, 1.0, param->eps, si, param->shrinking, param->verbose); |
| 1535 | double r = si->r; |
| 1536 | |
| 1537 | if(param->verbose)//pk |
| 1538 | info("C = %f\n",1/r); |
| 1539 | |
| 1540 | for(i=0;i<l;i++) |
| 1541 | alpha[i] *= y[i]/r; |
| 1542 | |
| 1543 | si->rho /= r; |
| 1544 | si->obj /= (r*r); |
| 1545 | si->upper_bound_p = 1/r; |
| 1546 | si->upper_bound_n = 1/r; |
| 1547 | |
| 1548 | delete[] y; |
| 1549 | delete[] zeros; |
| 1550 | } |
| 1551 | |
| 1552 | static void solve_one_class( |
| 1553 | const svm_problem *prob, const svm_parameter *param, |
| 1554 | double *alpha, Solver::SolutionInfo* si) |
| 1555 | { |
| 1556 | int l = prob->l; |
| 1557 | double *zeros = new double[l]; |
| 1558 | schar *ones = new schar[l]; |
| 1559 | int i; |
| 1560 | |
| 1561 | int n = (int)(param->nu*prob->l); // # of alpha's at upper bound |
| 1562 | |
| 1563 | for(i=0;i<n;i++) |
| 1564 | alpha[i] = 1; |
| 1565 | if(n<prob->l) |
| 1566 | alpha[n] = param->nu * prob->l - n; |
| 1567 | for(i=n+1;i<l;i++) |
| 1568 | alpha[i] = 0; |
| 1569 | |
| 1570 | for(i=0;i<l;i++) |
| 1571 | { |
| 1572 | zeros[i] = 0; |
| 1573 | ones[i] = 1; |
| 1574 | } |
| 1575 | |
| 1576 | Solver s; |
| 1577 | s.Solve(l, ONE_CLASS_Q(*prob,*param), zeros, ones, |
| 1578 | alpha, 1.0, 1.0, param->eps, si, param->shrinking, param->verbose ); |
| 1579 | |
| 1580 | delete[] zeros; |
| 1581 | delete[] ones; |
| 1582 | } |
| 1583 | |
| 1584 | static void solve_epsilon_svr( |
| 1585 | const svm_problem *prob, const svm_parameter *param, |
| 1586 | double *alpha, Solver::SolutionInfo* si) |
| 1587 | { |
| 1588 | int l = prob->l; |
| 1589 | double *alpha2 = new double[2*l]; |
| 1590 | double *linear_term = new double[2*l]; |
| 1591 | schar *y = new schar[2*l]; |
| 1592 | int i; |
| 1593 | |
| 1594 | for(i=0;i<l;i++) |
| 1595 | { |
| 1596 | alpha2[i] = 0; |
| 1597 | linear_term[i] = param->p - prob->y[i]; |
| 1598 | y[i] = 1; |
| 1599 | |
| 1600 | alpha2[i+l] = 0; |
| 1601 | linear_term[i+l] = param->p + prob->y[i]; |
| 1602 | y[i+l] = -1; |
| 1603 | } |
| 1604 | |
| 1605 | Solver s; |
| 1606 | s.Solve(2*l, SVR_Q(*prob,*param), linear_term, y, |
| 1607 | alpha2, param->C, param->C, param->eps, si, param->shrinking, param->verbose); |
| 1608 | |
| 1609 | double sum_alpha = 0; |
| 1610 | for(i=0;i<l;i++) |
| 1611 | { |
| 1612 | alpha[i] = alpha2[i] - alpha2[i+l]; |
| 1613 | sum_alpha += fabs(alpha[i]); |
| 1614 | } |
| 1615 | if(param->verbose)//pk |
| 1616 | info("nu = %f\n",sum_alpha/(param->C*l)); |
| 1617 | |
| 1618 | delete[] alpha2; |
| 1619 | delete[] linear_term; |
| 1620 | delete[] y; |
| 1621 | } |
| 1622 | |
| 1623 | static void solve_nu_svr( |
| 1624 | const svm_problem *prob, const svm_parameter *param, |
| 1625 | double *alpha, Solver::SolutionInfo* si) |
| 1626 | { |
| 1627 | int l = prob->l; |
| 1628 | double C = param->C; |
| 1629 | double *alpha2 = new double[2*l]; |
| 1630 | double *linear_term = new double[2*l]; |
| 1631 | schar *y = new schar[2*l]; |
| 1632 | int i; |
| 1633 | |
| 1634 | double sum = C * param->nu * l / 2; |
| 1635 | for(i=0;i<l;i++) |
| 1636 | { |
| 1637 | alpha2[i] = alpha2[i+l] = min(sum,C); |
| 1638 | sum -= alpha2[i]; |
| 1639 | |
| 1640 | linear_term[i] = - prob->y[i]; |
| 1641 | y[i] = 1; |
| 1642 | |
| 1643 | linear_term[i+l] = prob->y[i]; |
| 1644 | y[i+l] = -1; |
| 1645 | } |
| 1646 | |
| 1647 | Solver_NU s; |
| 1648 | s.Solve(2*l, SVR_Q(*prob,*param), linear_term, y, |
| 1649 | alpha2, C, C, param->eps, si, param->shrinking, param->verbose); |
| 1650 | |
| 1651 | if(param->verbose)//pk |
| 1652 | info("epsilon = %f\n",-si->r); |
| 1653 | |
| 1654 | for(i=0;i<l;i++) |
| 1655 | alpha[i] = alpha2[i] - alpha2[i+l]; |
| 1656 | |
| 1657 | delete[] alpha2; |
| 1658 | delete[] linear_term; |
| 1659 | delete[] y; |
| 1660 | } |
| 1661 | |
| 1662 | // |
| 1663 | // decision_function |
| 1664 | // |
| 1665 | struct decision_function |
| 1666 | { |
| 1667 | double *alpha; |
| 1668 | double rho; |
| 1669 | }; |
| 1670 | |
| 1671 | static decision_function svm_train_one( |
| 1672 | const svm_problem *prob, const svm_parameter *param, |
| 1673 | double Cp, double Cn) |
| 1674 | { |
| 1675 | double *alpha = Malloc(double,prob->l); |
| 1676 | Solver::SolutionInfo si; |
| 1677 | switch(param->svm_type) |
| 1678 | { |
| 1679 | case C_SVC: |
| 1680 | solve_c_svc(prob,param,alpha,&si,Cp,Cn); |
| 1681 | break; |
| 1682 | case NU_SVC: |
| 1683 | solve_nu_svc(prob,param,alpha,&si); |
| 1684 | break; |
| 1685 | case ONE_CLASS: |
| 1686 | solve_one_class(prob,param,alpha,&si); |
| 1687 | break; |
| 1688 | case EPSILON_SVR: |
| 1689 | solve_epsilon_svr(prob,param,alpha,&si); |
| 1690 | break; |
| 1691 | case NU_SVR: |
| 1692 | solve_nu_svr(prob,param,alpha,&si); |
| 1693 | break; |
| 1694 | } |
| 1695 | |
| 1696 | if(param->verbose)//pk |
| 1697 | info("obj = %f, rho = %f\n",si.obj,si.rho); |
| 1698 | |
| 1699 | // output SVs |
| 1700 | |
| 1701 | int nSV = 0; |
| 1702 | int nBSV = 0; |
| 1703 | for(int i=0;i<prob->l;i++) |
| 1704 | { |
| 1705 | if(fabs(alpha[i]) > 0) |
| 1706 | { |
| 1707 | ++nSV; |
| 1708 | if(prob->y[i] > 0) |
| 1709 | { |
| 1710 | if(fabs(alpha[i]) >= si.upper_bound_p) |
| 1711 | ++nBSV; |
| 1712 | } |
| 1713 | else |
| 1714 | { |
| 1715 | if(fabs(alpha[i]) >= si.upper_bound_n) |
| 1716 | ++nBSV; |
| 1717 | } |
| 1718 | } |
| 1719 | } |
| 1720 | |
| 1721 | if(param->verbose)//pk |
| 1722 | info("nSV = %d, nBSV = %d\n",nSV,nBSV); |
| 1723 | |
| 1724 | decision_function f; |
| 1725 | f.alpha = alpha; |
| 1726 | f.rho = si.rho; |
| 1727 | return f; |
| 1728 | } |
| 1729 | |
| 1730 | // Platt's binary SVM Probablistic Output: an improvement from Lin et al. |
| 1731 | static void sigmoid_train( |
| 1732 | int l, const double *dec_values, const double *labels, |
| 1733 | double& A, double& B) |
| 1734 | { |
| 1735 | double prior1=0, prior0 = 0; |
| 1736 | int i; |
| 1737 | |
| 1738 | for (i=0;i<l;i++) |
| 1739 | if (labels[i] > 0) prior1+=1; |
| 1740 | else prior0+=1; |
| 1741 | |
| 1742 | int max_iter=100; // Maximal number of iterations |
| 1743 | double min_step=1e-10; // Minimal step taken in line search |
| 1744 | double sigma=1e-12; // For numerically strict PD of Hessian |
| 1745 | double eps=1e-5; |
| 1746 | double hiTarget=(prior1+1.0)/(prior1+2.0); |
| 1747 | double loTarget=1/(prior0+2.0); |
| 1748 | double *t=Malloc(double,l); |
| 1749 | double fApB,p,q,h11,h22,h21,g1,g2,det,dA,dB,gd,stepsize; |
| 1750 | double newA,newB,newf,d1,d2; |
| 1751 | int iter; |
| 1752 | |
| 1753 | // Initial Point and Initial Fun Value |
| 1754 | A=0.0; B=log((prior0+1.0)/(prior1+1.0)); |
| 1755 | double fval = 0.0; |
| 1756 | |
| 1757 | for (i=0;i<l;i++) |
| 1758 | { |
| 1759 | if (labels[i]>0) t[i]=hiTarget; |
| 1760 | else t[i]=loTarget; |
| 1761 | fApB = dec_values[i]*A+B; |
| 1762 | if (fApB>=0) |
| 1763 | fval += t[i]*fApB + log(1+exp(-fApB)); |
| 1764 | else |
| 1765 | fval += (t[i] - 1)*fApB +log(1+exp(fApB)); |
| 1766 | } |
| 1767 | for (iter=0;iter<max_iter;iter++) |
| 1768 | { |
| 1769 | // Update Gradient and Hessian (use H' = H + sigma I) |
| 1770 | h11=sigma; // numerically ensures strict PD |
| 1771 | h22=sigma; |
| 1772 | h21=0.0;g1=0.0;g2=0.0; |
| 1773 | for (i=0;i<l;i++) |
| 1774 | { |
| 1775 | fApB = dec_values[i]*A+B; |
| 1776 | if (fApB >= 0) |
| 1777 | { |
| 1778 | p=exp(-fApB)/(1.0+exp(-fApB)); |
| 1779 | q=1.0/(1.0+exp(-fApB)); |
| 1780 | } |
| 1781 | else |
| 1782 | { |
| 1783 | p=1.0/(1.0+exp(fApB)); |
| 1784 | q=exp(fApB)/(1.0+exp(fApB)); |
| 1785 | } |
| 1786 | d2=p*q; |
| 1787 | h11+=dec_values[i]*dec_values[i]*d2; |
| 1788 | h22+=d2; |
| 1789 | h21+=dec_values[i]*d2; |
| 1790 | d1=t[i]-p; |
| 1791 | g1+=dec_values[i]*d1; |
| 1792 | g2+=d1; |
| 1793 | } |
| 1794 | |
| 1795 | // Stopping Criteria |
| 1796 | if (fabs(g1)<eps && fabs(g2)<eps) |
| 1797 | break; |
| 1798 | |
| 1799 | // Finding Newton direction: -inv(H') * g |
| 1800 | det=h11*h22-h21*h21; |
| 1801 | dA=-(h22*g1 - h21 * g2) / det; |
| 1802 | dB=-(-h21*g1+ h11 * g2) / det; |
| 1803 | gd=g1*dA+g2*dB; |
| 1804 | |
| 1805 | |
| 1806 | stepsize = 1; // Line Search |
| 1807 | while (stepsize >= min_step) |
| 1808 | { |
| 1809 | newA = A + stepsize * dA; |
| 1810 | newB = B + stepsize * dB; |
| 1811 | |
| 1812 | // New function value |
| 1813 | newf = 0.0; |
| 1814 | for (i=0;i<l;i++) |
| 1815 | { |
| 1816 | fApB = dec_values[i]*newA+newB; |
| 1817 | if (fApB >= 0) |
| 1818 | newf += t[i]*fApB + log(1+exp(-fApB)); |
| 1819 | else |
| 1820 | newf += (t[i] - 1)*fApB +log(1+exp(fApB)); |
| 1821 | } |
| 1822 | // Check sufficient decrease |
| 1823 | if (newf<fval+0.0001*stepsize*gd) |
| 1824 | { |
| 1825 | A=newA;B=newB;fval=newf; |
| 1826 | break; |
| 1827 | } |
| 1828 | else |
| 1829 | stepsize = stepsize / 2.0; |
| 1830 | } |
| 1831 | |
| 1832 | if (stepsize < min_step) |
| 1833 | { |
| 1834 | info("Line search fails in two-class probability estimates\n"); |
| 1835 | break; |
| 1836 | } |
| 1837 | } |
| 1838 | |
| 1839 | if (iter>=max_iter) |
| 1840 | info("Reaching maximal iterations in two-class probability estimates\n"); |
| 1841 | free(t); |
| 1842 | } |
| 1843 | |
| 1844 | static double sigmoid_predict(double decision_value, double A, double B) |
| 1845 | { |
| 1846 | double fApB = decision_value*A+B; |
| 1847 | // 1-p used later; avoid catastrophic cancellation |
| 1848 | if (fApB >= 0) |
| 1849 | return exp(-fApB)/(1.0+exp(-fApB)); |
| 1850 | else |
| 1851 | return 1.0/(1+exp(fApB)) ; |
| 1852 | } |
| 1853 | |
| 1854 | // Method 2 from the multiclass_prob paper by Wu, Lin, and Weng |
| 1855 | static void multiclass_probability(int k, double **r, double *p) |
| 1856 | { |
| 1857 | int t,j; |
| 1858 | int iter = 0, max_iter=max(100,k); |
| 1859 | double **Q=Malloc(double *,k); |
| 1860 | double *Qp=Malloc(double,k); |
| 1861 | double pQp, eps=0.005/k; |
| 1862 | |
| 1863 | for (t=0;t<k;t++) |
| 1864 | { |
| 1865 | p[t]=1.0/k; // Valid if k = 1 |
| 1866 | Q[t]=Malloc(double,k); |
| 1867 | Q[t][t]=0; |
| 1868 | for (j=0;j<t;j++) |
| 1869 | { |
| 1870 | Q[t][t]+=r[j][t]*r[j][t]; |
| 1871 | Q[t][j]=Q[j][t]; |
| 1872 | } |
| 1873 | for (j=t+1;j<k;j++) |
| 1874 | { |
| 1875 | Q[t][t]+=r[j][t]*r[j][t]; |
| 1876 | Q[t][j]=-r[j][t]*r[t][j]; |
| 1877 | } |
| 1878 | } |
| 1879 | for (iter=0;iter<max_iter;iter++) |
| 1880 | { |
| 1881 | // stopping condition, recalculate QP,pQP for numerical accuracy |
| 1882 | pQp=0; |
| 1883 | for (t=0;t<k;t++) |
| 1884 | { |
| 1885 | Qp[t]=0; |
| 1886 | for (j=0;j<k;j++) |
| 1887 | Qp[t]+=Q[t][j]*p[j]; |
| 1888 | pQp+=p[t]*Qp[t]; |
| 1889 | } |
| 1890 | double max_error=0; |
| 1891 | for (t=0;t<k;t++) |
| 1892 | { |
| 1893 | double error=fabs(Qp[t]-pQp); |
| 1894 | if (error>max_error) |
| 1895 | max_error=error; |
| 1896 | } |
| 1897 | if (max_error<eps) break; |
| 1898 | |
| 1899 | for (t=0;t<k;t++) |
| 1900 | { |
| 1901 | double diff=(-Qp[t]+pQp)/Q[t][t]; |
| 1902 | p[t]+=diff; |
| 1903 | pQp=(pQp+diff*(diff*Q[t][t]+2*Qp[t]))/(1+diff)/(1+diff); |
| 1904 | for (j=0;j<k;j++) |
| 1905 | { |
| 1906 | Qp[j]=(Qp[j]+diff*Q[t][j])/(1+diff); |
| 1907 | p[j]/=(1+diff); |
| 1908 | } |
| 1909 | } |
| 1910 | } |
| 1911 | if (iter>=max_iter) |
| 1912 | info("Exceeds max_iter in multiclass_prob\n"); |
| 1913 | for(t=0;t<k;t++) free(Q[t]); |
| 1914 | free(Q); |
| 1915 | free(Qp); |
| 1916 | } |
| 1917 | |
| 1918 | // Cross-validation decision values for probability estimates |
| 1919 | static void svm_binary_svc_probability( |
| 1920 | const svm_problem *prob, const svm_parameter *param, |
| 1921 | double Cp, double Cn, double& probA, double& probB) |
| 1922 | { |
| 1923 | int i; |
| 1924 | int nr_fold = 5; |
| 1925 | int *perm = Malloc(int,prob->l); |
| 1926 | double *dec_values = Malloc(double,prob->l); |
| 1927 | |
| 1928 | // random shuffle |
| 1929 | for(i=0;i<prob->l;i++) perm[i]=i; |
| 1930 | for(i=0;i<prob->l;i++) |
| 1931 | { |
| 1932 | int j = i+rand()%(prob->l-i); |
| 1933 | swap(perm[i],perm[j]); |
| 1934 | } |
| 1935 | for(i=0;i<nr_fold;i++) |
| 1936 | { |
| 1937 | int begin = i*prob->l/nr_fold; |
| 1938 | int end = (i+1)*prob->l/nr_fold; |
| 1939 | int j,k; |
| 1940 | struct svm_problem subprob; |
| 1941 | |
| 1942 | subprob.l = prob->l-(end-begin); |
| 1943 | subprob.x = Malloc(struct svm_node*,subprob.l); |
| 1944 | subprob.y = Malloc(double,subprob.l); |
| 1945 | |
| 1946 | k=0; |
| 1947 | for(j=0;j<begin;j++) |
| 1948 | { |
| 1949 | subprob.x[k] = prob->x[perm[j]]; |
| 1950 | subprob.y[k] = prob->y[perm[j]]; |
| 1951 | ++k; |
| 1952 | } |
| 1953 | for(j=end;j<prob->l;j++) |
| 1954 | { |
| 1955 | subprob.x[k] = prob->x[perm[j]]; |
| 1956 | subprob.y[k] = prob->y[perm[j]]; |
| 1957 | ++k; |
| 1958 | } |
| 1959 | int p_count=0,n_count=0; |
| 1960 | for(j=0;j<k;j++) |
| 1961 | if(subprob.y[j]>0) |
| 1962 | p_count++; |
| 1963 | else |
| 1964 | n_count++; |
| 1965 | |
| 1966 | if(p_count==0 && n_count==0) |
| 1967 | for(j=begin;j<end;j++) |
| 1968 | dec_values[perm[j]] = 0; |
| 1969 | else if(p_count > 0 && n_count == 0) |
| 1970 | for(j=begin;j<end;j++) |
| 1971 | dec_values[perm[j]] = 1; |
| 1972 | else if(p_count == 0 && n_count > 0) |
| 1973 | for(j=begin;j<end;j++) |
| 1974 | dec_values[perm[j]] = -1; |
| 1975 | else |
| 1976 | { |
| 1977 | svm_parameter subparam = *param; |
| 1978 | subparam.probability=0; |
| 1979 | subparam.C=1.0; |
| 1980 | subparam.nr_weight=2; |
| 1981 | subparam.weight_label = Malloc(int,2); |
| 1982 | subparam.weight = Malloc(double,2); |
| 1983 | subparam.weight_label[0]=+1; |
| 1984 | subparam.weight_label[1]=-1; |
| 1985 | subparam.weight[0]=Cp; |
| 1986 | subparam.weight[1]=Cn; |
| 1987 | struct svm_model *submodel = svm_train(&subprob,&subparam); |
| 1988 | for(j=begin;j<end;j++) |
| 1989 | { |
| 1990 | svm_predict_values(submodel,prob->x[perm[j]],&(dec_values[perm[j]])); |
| 1991 | // ensure +1 -1 order; reason not using CV subroutine |
| 1992 | dec_values[perm[j]] *= submodel->label[0]; |
| 1993 | } |
| 1994 | svm_free_and_destroy_model(&submodel); |
| 1995 | svm_destroy_param(&subparam); |
| 1996 | } |
| 1997 | free(subprob.x); |
| 1998 | free(subprob.y); |
| 1999 | } |
| 2000 | sigmoid_train(prob->l,dec_values,prob->y,probA,probB); |
| 2001 | free(dec_values); |
| 2002 | free(perm); |
| 2003 | } |
| 2004 | |
| 2005 | // Return parameter of a Laplace distribution |
| 2006 | static double svm_svr_probability( |
| 2007 | const svm_problem *prob, const svm_parameter *param) |
| 2008 | { |
| 2009 | int i; |
| 2010 | int nr_fold = 5; |
| 2011 | double *ymv = Malloc(double,prob->l); |
| 2012 | double mae = 0; |
| 2013 | |
| 2014 | svm_parameter newparam = *param; |
| 2015 | newparam.probability = 0; |
| 2016 | svm_cross_validation(prob,&newparam,nr_fold,ymv); |
| 2017 | for(i=0;i<prob->l;i++) |
| 2018 | { |
| 2019 | ymv[i]=prob->y[i]-ymv[i]; |
| 2020 | mae += fabs(ymv[i]); |
| 2021 | } |
| 2022 | mae /= prob->l; |
| 2023 | double std=sqrt(2*mae*mae); |
| 2024 | int count=0; |
| 2025 | mae=0; |
| 2026 | for(i=0;i<prob->l;i++) |
| 2027 | if (fabs(ymv[i]) > 5*std) |
| 2028 | count=count+1; |
| 2029 | else |
| 2030 | mae+=fabs(ymv[i]); |
| 2031 | mae /= (prob->l-count); |
| 2032 | info("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma= %g\n",mae); |
| 2033 | free(ymv); |
| 2034 | return mae; |
| 2035 | } |
| 2036 | |
| 2037 | |
| 2038 | // label: label name, start: begin of each class, count: #data of classes, perm: indices to the original data |
| 2039 | // perm, length l, must be allocated before calling this subroutine |
| 2040 | static void svm_group_classes(const svm_problem *prob, int *nr_class_ret, int **label_ret, int **start_ret, int **count_ret, int *perm) |
| 2041 | { |
| 2042 | int l = prob->l; |
| 2043 | int max_nr_class = 16; |
| 2044 | int nr_class = 0; |
| 2045 | int *label = Malloc(int,max_nr_class); |
| 2046 | int *count = Malloc(int,max_nr_class); |
| 2047 | int *data_label = Malloc(int,l); |
| 2048 | int i; |
| 2049 | |
| 2050 | for(i=0;i<l;i++) |
| 2051 | { |
| 2052 | int this_label = (int)prob->y[i]; |
| 2053 | int j; |
| 2054 | for(j=0;j<nr_class;j++) |
| 2055 | { |
| 2056 | if(this_label == label[j]) |
| 2057 | { |
| 2058 | ++count[j]; |
| 2059 | break; |
| 2060 | } |
| 2061 | } |
| 2062 | data_label[i] = j; |
| 2063 | if(j == nr_class) |
| 2064 | { |
| 2065 | if(nr_class == max_nr_class) |
| 2066 | { |
| 2067 | max_nr_class *= 2; |
| 2068 | label = (int *)realloc(label,max_nr_class*sizeof(int)); |
| 2069 | count = (int *)realloc(count,max_nr_class*sizeof(int)); |
| 2070 | } |
| 2071 | label[nr_class] = this_label; |
| 2072 | count[nr_class] = 1; |
| 2073 | ++nr_class; |
| 2074 | } |
| 2075 | } |
| 2076 | |
| 2077 | int *start = Malloc(int,nr_class); |
| 2078 | start[0] = 0; |
| 2079 | for(i=1;i<nr_class;i++) |
| 2080 | start[i] = start[i-1]+count[i-1]; |
| 2081 | for(i=0;i<l;i++) |
| 2082 | { |
| 2083 | perm[start[data_label[i]]] = i; |
| 2084 | ++start[data_label[i]]; |
| 2085 | } |
| 2086 | start[0] = 0; |
| 2087 | for(i=1;i<nr_class;i++) |
| 2088 | start[i] = start[i-1]+count[i-1]; |
| 2089 | |
| 2090 | *nr_class_ret = nr_class; |
| 2091 | *label_ret = label; |
| 2092 | *start_ret = start; |
| 2093 | *count_ret = count; |
| 2094 | free(data_label); |
| 2095 | } |
| 2096 | |
| 2097 | // |
| 2098 | // Interface functions |
| 2099 | // |
| 2100 | svm_model *svm_train(const svm_problem *prob, const svm_parameter *param) |
| 2101 | { |
| 2102 | svm_model *model = Malloc(svm_model,1); |
| 2103 | model->param = *param; |
| 2104 | model->free_sv = 0; // XXX |
| 2105 | |
| 2106 | if(param->svm_type == ONE_CLASS || |
| 2107 | param->svm_type == EPSILON_SVR || |
| 2108 | param->svm_type == NU_SVR) |
| 2109 | { |
| 2110 | // regression or one-class-svm |
| 2111 | model->nr_class = 2; |
| 2112 | model->label = NULL; |
| 2113 | model->nSV = NULL; |
| 2114 | model->probA = NULL; model->probB = NULL; |
| 2115 | model->sv_coef = Malloc(double *,1); |
| 2116 | |
| 2117 | if(param->probability && |
| 2118 | (param->svm_type == EPSILON_SVR || |
| 2119 | param->svm_type == NU_SVR)) |
| 2120 | { |
| 2121 | model->probA = Malloc(double,1); |
| 2122 | model->probA[0] = svm_svr_probability(prob,param); |
| 2123 | } |
| 2124 | |
| 2125 | decision_function f = svm_train_one(prob,param,0,0); |
| 2126 | model->rho = Malloc(double,1); |
| 2127 | model->rho[0] = f.rho; |
| 2128 | |
| 2129 | int nSV = 0; |
| 2130 | int i; |
| 2131 | for(i=0;i<prob->l;i++) |
| 2132 | if(fabs(f.alpha[i]) > 0) ++nSV; |
| 2133 | model->l = nSV; |
| 2134 | model->SV = Malloc(svm_node *,nSV); |
| 2135 | model->sv_coef[0] = Malloc(double,nSV); |
| 2136 | int j = 0; |
| 2137 | for(i=0;i<prob->l;i++) |
| 2138 | if(fabs(f.alpha[i]) > 0) |
| 2139 | { |
| 2140 | model->SV[j] = prob->x[i]; |
| 2141 | model->sv_coef[0][j] = f.alpha[i]; |
| 2142 | ++j; |
| 2143 | } |
| 2144 | |
| 2145 | free(f.alpha); |
| 2146 | } |
| 2147 | else |
| 2148 | { |
| 2149 | // classification |
| 2150 | int l = prob->l; |
| 2151 | int nr_class; |
| 2152 | int *label = NULL; |
| 2153 | int *start = NULL; |
| 2154 | int *count = NULL; |
| 2155 | int *perm = Malloc(int,l); |
| 2156 | |
| 2157 | // group training data of the same class |
| 2158 | svm_group_classes(prob,&nr_class,&label,&start,&count,perm); |
| 2159 | if(nr_class == 1) |
| 2160 | info("WARNING: training data in only one class. See README for details.\n"); |
| 2161 | |
| 2162 | svm_node **x = Malloc(svm_node *,l); |
| 2163 | int i; |
| 2164 | for(i=0;i<l;i++) |
| 2165 | x[i] = prob->x[perm[i]]; |
| 2166 | |
| 2167 | // calculate weighted C |
| 2168 | |
| 2169 | double *weighted_C = Malloc(double, nr_class); |
| 2170 | for(i=0;i<nr_class;i++) |
| 2171 | weighted_C[i] = param->C; |
| 2172 | for(i=0;i<param->nr_weight;i++) |
| 2173 | { |
| 2174 | int j; |
| 2175 | for(j=0;j<nr_class;j++) |
| 2176 | if(param->weight_label[i] == label[j]) |
| 2177 | break; |
| 2178 | if(j == nr_class) |
| 2179 | fprintf(stderr,"WARNING: class label %d specified in weight is not found\n", param->weight_label[i]); |
| 2180 | else |
| 2181 | weighted_C[j] *= param->weight[i]; |
| 2182 | } |
| 2183 | |
| 2184 | // train k*(k-1)/2 models |
| 2185 | |
| 2186 | bool *nonzero = Malloc(bool,l); |
| 2187 | for(i=0;i<l;i++) |
| 2188 | nonzero[i] = false; |
| 2189 | decision_function *f = Malloc(decision_function,nr_class*(nr_class-1)/2); |
| 2190 | |
| 2191 | double *probA=NULL,*probB=NULL; |
| 2192 | if (param->probability) |
| 2193 | { |
| 2194 | probA=Malloc(double,nr_class*(nr_class-1)/2); |
| 2195 | probB=Malloc(double,nr_class*(nr_class-1)/2); |
| 2196 | } |
| 2197 | |
| 2198 | int p = 0; |
| 2199 | for(i=0;i<nr_class;i++) |
| 2200 | for(int j=i+1;j<nr_class;j++) |
| 2201 | { |
| 2202 | svm_problem sub_prob; |
| 2203 | int si = start[i], sj = start[j]; |
| 2204 | int ci = count[i], cj = count[j]; |
| 2205 | sub_prob.l = ci+cj; |
| 2206 | sub_prob.x = Malloc(svm_node *,sub_prob.l); |
| 2207 | sub_prob.y = Malloc(double,sub_prob.l); |
| 2208 | int k; |
| 2209 | for(k=0;k<ci;k++) |
| 2210 | { |
| 2211 | sub_prob.x[k] = x[si+k]; |
| 2212 | sub_prob.y[k] = +1; |
| 2213 | } |
| 2214 | for(k=0;k<cj;k++) |
| 2215 | { |
| 2216 | sub_prob.x[ci+k] = x[sj+k]; |
| 2217 | sub_prob.y[ci+k] = -1; |
| 2218 | } |
| 2219 | |
| 2220 | if(param->probability) |
| 2221 | svm_binary_svc_probability(&sub_prob,param,weighted_C[i],weighted_C[j],probA[p],probB[p]); |
| 2222 | |
| 2223 | f[p] = svm_train_one(&sub_prob,param,weighted_C[i],weighted_C[j]); |
| 2224 | for(k=0;k<ci;k++) |
| 2225 | if(!nonzero[si+k] && fabs(f[p].alpha[k]) > 0) |
| 2226 | nonzero[si+k] = true; |
| 2227 | for(k=0;k<cj;k++) |
| 2228 | if(!nonzero[sj+k] && fabs(f[p].alpha[ci+k]) > 0) |
| 2229 | nonzero[sj+k] = true; |
| 2230 | free(sub_prob.x); |
| 2231 | free(sub_prob.y); |
| 2232 | ++p; |
| 2233 | } |
| 2234 | |
| 2235 | // build output |
| 2236 | |
| 2237 | model->nr_class = nr_class; |
| 2238 | |
| 2239 | model->label = Malloc(int,nr_class); |
| 2240 | for(i=0;i<nr_class;i++) |
| 2241 | model->label[i] = label[i]; |
| 2242 | |
| 2243 | model->rho = Malloc(double,nr_class*(nr_class-1)/2); |
| 2244 | for(i=0;i<nr_class*(nr_class-1)/2;i++) |
| 2245 | model->rho[i] = f[i].rho; |
| 2246 | |
| 2247 | if(param->probability) |
| 2248 | { |
| 2249 | model->probA = Malloc(double,nr_class*(nr_class-1)/2); |
| 2250 | model->probB = Malloc(double,nr_class*(nr_class-1)/2); |
| 2251 | for(i=0;i<nr_class*(nr_class-1)/2;i++) |
| 2252 | { |
| 2253 | model->probA[i] = probA[i]; |
| 2254 | model->probB[i] = probB[i]; |
| 2255 | } |
| 2256 | } |
| 2257 | else |
| 2258 | { |
| 2259 | model->probA=NULL; |
| 2260 | model->probB=NULL; |
| 2261 | } |
| 2262 | |
| 2263 | int total_sv = 0; |
| 2264 | int *nz_count = Malloc(int,nr_class); |
| 2265 | model->nSV = Malloc(int,nr_class); |
| 2266 | for(i=0;i<nr_class;i++) |
| 2267 | { |
| 2268 | int nSV = 0; |
| 2269 | for(int j=0;j<count[i];j++) |
| 2270 | if(nonzero[start[i]+j]) |
| 2271 | { |
| 2272 | ++nSV; |
| 2273 | ++total_sv; |
| 2274 | } |
| 2275 | model->nSV[i] = nSV; |
| 2276 | nz_count[i] = nSV; |
| 2277 | } |
| 2278 | |
| 2279 | if(param->verbose)//pk |
| 2280 | info("Total nSV = %d\n",total_sv); |
| 2281 | |
| 2282 | model->l = total_sv; |
| 2283 | model->SV = Malloc(svm_node *,total_sv); |
| 2284 | p = 0; |
| 2285 | for(i=0;i<l;i++) |
| 2286 | if(nonzero[i]) model->SV[p++] = x[i]; |
| 2287 | |
| 2288 | int *nz_start = Malloc(int,nr_class); |
| 2289 | nz_start[0] = 0; |
| 2290 | for(i=1;i<nr_class;i++) |
| 2291 | nz_start[i] = nz_start[i-1]+nz_count[i-1]; |
| 2292 | |
| 2293 | model->sv_coef = Malloc(double *,nr_class-1); |
| 2294 | for(i=0;i<nr_class-1;i++) |
| 2295 | model->sv_coef[i] = Malloc(double,total_sv); |
| 2296 | |
| 2297 | p = 0; |
| 2298 | for(i=0;i<nr_class;i++) |
| 2299 | for(int j=i+1;j<nr_class;j++) |
| 2300 | { |
| 2301 | // classifier (i,j): coefficients with |
| 2302 | // i are in sv_coef[j-1][nz_start[i]...], |
| 2303 | // j are in sv_coef[i][nz_start[j]...] |
| 2304 | |
| 2305 | int si = start[i]; |
| 2306 | int sj = start[j]; |
| 2307 | int ci = count[i]; |
| 2308 | int cj = count[j]; |
| 2309 | |
| 2310 | int q = nz_start[i]; |
| 2311 | int k; |
| 2312 | for(k=0;k<ci;k++) |
| 2313 | if(nonzero[si+k]) |
| 2314 | model->sv_coef[j-1][q++] = f[p].alpha[k]; |
| 2315 | q = nz_start[j]; |
| 2316 | for(k=0;k<cj;k++) |
| 2317 | if(nonzero[sj+k]) |
| 2318 | model->sv_coef[i][q++] = f[p].alpha[ci+k]; |
| 2319 | ++p; |
| 2320 | } |
| 2321 | |
| 2322 | free(label); |
| 2323 | free(probA); |
| 2324 | free(probB); |
| 2325 | free(count); |
| 2326 | free(perm); |
| 2327 | free(start); |
| 2328 | free(x); |
| 2329 | free(weighted_C); |
| 2330 | free(nonzero); |
| 2331 | for(i=0;i<nr_class*(nr_class-1)/2;i++) |
| 2332 | free(f[i].alpha); |
| 2333 | free(f); |
| 2334 | free(nz_count); |
| 2335 | free(nz_start); |
| 2336 | } |
| 2337 | return model; |
| 2338 | } |
| 2339 | |
| 2340 | // Stratified cross validation |
| 2341 | void svm_cross_validation(const svm_problem *prob, const svm_parameter *param, int nr_fold, double *target) |
| 2342 | { |
| 2343 | int i; |
| 2344 | int *fold_start = Malloc(int,nr_fold+1); |
| 2345 | int l = prob->l; |
| 2346 | int *perm = Malloc(int,l); |
| 2347 | int nr_class; |
| 2348 | |
| 2349 | // stratified cv may not give leave-one-out rate |
| 2350 | // Each class to l folds -> some folds may have zero elements |
| 2351 | if((param->svm_type == C_SVC || |
| 2352 | param->svm_type == NU_SVC) && nr_fold < l) |
| 2353 | { |
| 2354 | int *start = NULL; |
| 2355 | int *label = NULL; |
| 2356 | int *count = NULL; |
| 2357 | svm_group_classes(prob,&nr_class,&label,&start,&count,perm); |
| 2358 | |
| 2359 | // random shuffle and then data grouped by fold using the array perm |
| 2360 | int *fold_count = Malloc(int,nr_fold); |
| 2361 | int c; |
| 2362 | int *index = Malloc(int,l); |
| 2363 | for(i=0;i<l;i++) |
| 2364 | index[i]=perm[i]; |
| 2365 | for (c=0; c<nr_class; c++) |
| 2366 | for(i=0;i<count[c];i++) |
| 2367 | { |
| 2368 | int j = i+rand()%(count[c]-i); |
| 2369 | swap(index[start[c]+j],index[start[c]+i]); |
| 2370 | } |
| 2371 | for(i=0;i<nr_fold;i++) |
| 2372 | { |
| 2373 | fold_count[i] = 0; |
| 2374 | for (c=0; c<nr_class;c++) |
| 2375 | fold_count[i]+=(i+1)*count[c]/nr_fold-i*count[c]/nr_fold; |
| 2376 | } |
| 2377 | fold_start[0]=0; |
| 2378 | for (i=1;i<=nr_fold;i++) |
| 2379 | fold_start[i] = fold_start[i-1]+fold_count[i-1]; |
| 2380 | for (c=0; c<nr_class;c++) |
| 2381 | for(i=0;i<nr_fold;i++) |
| 2382 | { |
| 2383 | int begin = start[c]+i*count[c]/nr_fold; |
| 2384 | int end = start[c]+(i+1)*count[c]/nr_fold; |
| 2385 | for(int j=begin;j<end;j++) |
| 2386 | { |
| 2387 | perm[fold_start[i]] = index[j]; |
| 2388 | fold_start[i]++; |
| 2389 | } |
| 2390 | } |
| 2391 | fold_start[0]=0; |
| 2392 | for (i=1;i<=nr_fold;i++) |
| 2393 | fold_start[i] = fold_start[i-1]+fold_count[i-1]; |
| 2394 | free(start); |
| 2395 | free(label); |
| 2396 | free(count); |
| 2397 | free(index); |
| 2398 | free(fold_count); |
| 2399 | } |
| 2400 | else |
| 2401 | { |
| 2402 | for(i=0;i<l;i++) perm[i]=i; |
| 2403 | for(i=0;i<l;i++) |
| 2404 | { |
| 2405 | int j = i+rand()%(l-i); |
| 2406 | swap(perm[i],perm[j]); |
| 2407 | } |
| 2408 | for(i=0;i<=nr_fold;i++) |
| 2409 | fold_start[i]=i*l/nr_fold; |
| 2410 | } |
| 2411 | |
| 2412 | for(i=0;i<nr_fold;i++) |
| 2413 | { |
| 2414 | int begin = fold_start[i]; |
| 2415 | int end = fold_start[i+1]; |
| 2416 | int j,k; |
| 2417 | struct svm_problem subprob; |
| 2418 | |
| 2419 | subprob.l = l-(end-begin); |
| 2420 | subprob.x = Malloc(struct svm_node*,subprob.l); |
| 2421 | subprob.y = Malloc(double,subprob.l); |
| 2422 | |
| 2423 | k=0; |
| 2424 | for(j=0;j<begin;j++) |
| 2425 | { |
| 2426 | subprob.x[k] = prob->x[perm[j]]; |
| 2427 | subprob.y[k] = prob->y[perm[j]]; |
| 2428 | ++k; |
| 2429 | } |
| 2430 | for(j=end;j<l;j++) |
| 2431 | { |
| 2432 | subprob.x[k] = prob->x[perm[j]]; |
| 2433 | subprob.y[k] = prob->y[perm[j]]; |
| 2434 | ++k; |
| 2435 | } |
| 2436 | struct svm_model *submodel = svm_train(&subprob,param); |
| 2437 | if(param->probability && |
| 2438 | (param->svm_type == C_SVC || param->svm_type == NU_SVC)) |
| 2439 | { |
| 2440 | double *prob_estimates=Malloc(double,svm_get_nr_class(submodel)); |
| 2441 | for(j=begin;j<end;j++) |
| 2442 | target[perm[j]] = svm_predict_probability(submodel,prob->x[perm[j]],prob_estimates); |
| 2443 | free(prob_estimates); |
| 2444 | } |
| 2445 | else |
| 2446 | for(j=begin;j<end;j++) |
| 2447 | target[perm[j]] = svm_predict(submodel,prob->x[perm[j]]); |
| 2448 | svm_free_and_destroy_model(&submodel); |
| 2449 | free(subprob.x); |
| 2450 | free(subprob.y); |
| 2451 | } |
| 2452 | free(fold_start); |
| 2453 | free(perm); |
| 2454 | } |
| 2455 | |
| 2456 | |
| 2457 | int svm_get_svm_type(const svm_model *model) |
| 2458 | { |
| 2459 | return model->param.svm_type; |
| 2460 | } |
| 2461 | |
| 2462 | int svm_get_nr_class(const svm_model *model) |
| 2463 | { |
| 2464 | return model->nr_class; |
| 2465 | } |
| 2466 | |
| 2467 | void svm_get_labels(const svm_model *model, int* label) |
| 2468 | { |
| 2469 | if (model->label != NULL) |
| 2470 | for(int i=0;i<model->nr_class;i++) |
| 2471 | label[i] = model->label[i]; |
| 2472 | } |
| 2473 | |
| 2474 | double svm_get_svr_probability(const svm_model *model) |
| 2475 | { |
| 2476 | if ((model->param.svm_type == EPSILON_SVR || model->param.svm_type == NU_SVR) && |
| 2477 | model->probA!=NULL) |
| 2478 | return model->probA[0]; |
| 2479 | else |
| 2480 | { |
| 2481 | fprintf(stderr,"Model doesn't contain information for SVR probability inference\n"); |
| 2482 | return 0; |
| 2483 | } |
| 2484 | } |
| 2485 | |
| 2486 | double svm_predict_values(const svm_model *model, const svm_node *x, double* dec_values) |
| 2487 | { |
| 2488 | int i; |
| 2489 | if(model->param.svm_type == ONE_CLASS || |
| 2490 | model->param.svm_type == EPSILON_SVR || |
| 2491 | model->param.svm_type == NU_SVR) |
| 2492 | { |
| 2493 | double *sv_coef = model->sv_coef[0]; |
| 2494 | double sum = 0; |
| 2495 | #if JIPLIB_PROCESS_IN_PARALLEL == 1 |
| 2496 | #pragma omp parallel for private(i) reduction(+:sum) schedule(guided) |
| 2497 | #else |
| 2498 | #endif |
| 2499 | for(i=0;i<model->l;i++) |
| 2500 | sum += sv_coef[i] * Kernel::k_function(x,model->SV[i],model->param); |
| 2501 | sum -= model->rho[0]; |
| 2502 | *dec_values = sum; |
| 2503 | |
| 2504 | if(model->param.svm_type == ONE_CLASS) |
| 2505 | return (sum>0)?1:-1; |
| 2506 | else |
| 2507 | return sum; |
| 2508 | } |
| 2509 | else |
| 2510 | { |
| 2511 | int nr_class = model->nr_class; |
| 2512 | int l = model->l; |
| 2513 | |
| 2514 | double *kvalue = Malloc(double,l); |
| 2515 | #if JIPLIB_PROCESS_IN_PARALLEL == 1 |
| 2516 | #pragma omp parallel for private(i) schedule(guided) |
| 2517 | #else |
| 2518 | #endif |
| 2519 | for(i=0;i<l;i++) |
| 2520 | kvalue[i] = Kernel::k_function(x,model->SV[i],model->param); |
| 2521 | |
| 2522 | int *start = Malloc(int,nr_class); |
| 2523 | start[0] = 0; |
| 2524 | for(i=1;i<nr_class;i++) |
| 2525 | start[i] = start[i-1]+model->nSV[i-1]; |
| 2526 | |
| 2527 | int *vote = Malloc(int,nr_class); |
| 2528 | for(i=0;i<nr_class;i++) |
| 2529 | vote[i] = 0; |
| 2530 | |
| 2531 | int p=0; |
| 2532 | for(i=0;i<nr_class;i++) |
| 2533 | for(int j=i+1;j<nr_class;j++) |
| 2534 | { |
| 2535 | double sum = 0; |
| 2536 | int si = start[i]; |
| 2537 | int sj = start[j]; |
| 2538 | int ci = model->nSV[i]; |
| 2539 | int cj = model->nSV[j]; |
| 2540 | |
| 2541 | int k; |
| 2542 | double *coef1 = model->sv_coef[j-1]; |
| 2543 | double *coef2 = model->sv_coef[i]; |
| 2544 | for(k=0;k<ci;k++) |
| 2545 | sum += coef1[si+k] * kvalue[si+k]; |
| 2546 | for(k=0;k<cj;k++) |
| 2547 | sum += coef2[sj+k] * kvalue[sj+k]; |
| 2548 | sum -= model->rho[p]; |
| 2549 | dec_values[p] = sum; |
| 2550 | |
| 2551 | if(dec_values[p] > 0) |
| 2552 | ++vote[i]; |
| 2553 | else |
| 2554 | ++vote[j]; |
| 2555 | p++; |
| 2556 | } |
| 2557 | |
| 2558 | int vote_max_idx = 0; |
| 2559 | for(i=1;i<nr_class;i++) |
| 2560 | if(vote[i] > vote[vote_max_idx]) |
| 2561 | vote_max_idx = i; |
| 2562 | |
| 2563 | free(kvalue); |
| 2564 | free(start); |
| 2565 | free(vote); |
| 2566 | return model->label[vote_max_idx]; |
| 2567 | } |
| 2568 | } |
| 2569 | |
| 2570 | double svm_predict(const svm_model *model, const svm_node *x) |
| 2571 | { |
| 2572 | int nr_class = model->nr_class; |
| 2573 | double *dec_values; |
| 2574 | if(model->param.svm_type == ONE_CLASS || |
| 2575 | model->param.svm_type == EPSILON_SVR || |
| 2576 | model->param.svm_type == NU_SVR) |
| 2577 | dec_values = Malloc(double, 1); |
| 2578 | else |
| 2579 | dec_values = Malloc(double, nr_class*(nr_class-1)/2); |
| 2580 | double pred_result = svm_predict_values(model, x, dec_values); |
| 2581 | free(dec_values); |
| 2582 | return pred_result; |
| 2583 | } |
| 2584 | |
| 2585 | double svm_predict_probability( |
| 2586 | const svm_model *model, const svm_node *x, double *prob_estimates) |
| 2587 | { |
| 2588 | if ((model->param.svm_type == C_SVC || model->param.svm_type == NU_SVC) && |
| 2589 | model->probA!=NULL && model->probB!=NULL) |
| 2590 | { |
| 2591 | int i; |
| 2592 | int nr_class = model->nr_class; |
| 2593 | double *dec_values = Malloc(double, nr_class*(nr_class-1)/2); |
| 2594 | svm_predict_values(model, x, dec_values); |
| 2595 | |
| 2596 | double min_prob=1e-7; |
| 2597 | double **pairwise_prob=Malloc(double *,nr_class); |
| 2598 | for(i=0;i<nr_class;i++) |
| 2599 | pairwise_prob[i]=Malloc(double,nr_class); |
| 2600 | int k=0; |
| 2601 | for(i=0;i<nr_class;i++) |
| 2602 | for(int j=i+1;j<nr_class;j++) |
| 2603 | { |
| 2604 | pairwise_prob[i][j]=min(max(sigmoid_predict(dec_values[k],model->probA[k],model->probB[k]),min_prob),1-min_prob); |
| 2605 | pairwise_prob[j][i]=1-pairwise_prob[i][j]; |
| 2606 | k++; |
| 2607 | } |
| 2608 | multiclass_probability(nr_class,pairwise_prob,prob_estimates); |
| 2609 | |
| 2610 | int prob_max_idx = 0; |
| 2611 | for(i=1;i<nr_class;i++) |
| 2612 | if(prob_estimates[i] > prob_estimates[prob_max_idx]) |
| 2613 | prob_max_idx = i; |
| 2614 | for(i=0;i<nr_class;i++) |
| 2615 | free(pairwise_prob[i]); |
| 2616 | free(dec_values); |
| 2617 | free(pairwise_prob); |
| 2618 | return model->label[prob_max_idx]; |
| 2619 | } |
| 2620 | else |
| 2621 | return svm_predict(model, x); |
| 2622 | } |
| 2623 | |
| 2624 | static const char *svm_type_table[] = |
| 2625 | { |
| 2626 | "c_svc","nu_svc","one_class","epsilon_svr","nu_svr",NULL |
| 2627 | }; |
| 2628 | |
| 2629 | static const char *kernel_type_table[]= |
| 2630 | { |
| 2631 | "linear","polynomial","rbf","sigmoid","precomputed",NULL |
| 2632 | }; |
| 2633 | |
| 2634 | int svm_save_model(const std::string &model_file_name, const struct svm_model *model, const std::vector<double> &offset, const std::vector<double> &scale, const std::map<std::string,short> &classValueMap, const std::vector<std::string> &nameVector, const std::vector<std::string> &bandNames)//pk 11/04/2018{ |
| 2635 | { |
| 2636 | int result=1; |
| 2637 | std::ofstream fileStream(model_file_name); |
| 2638 | if(fileStream) |
| 2639 | result=svm_serialize_model(fileStream, model, offset, scale, classValueMap, nameVector, bandNames); |
| 2640 | fileStream.close(); |
| 2641 | return result; |
| 2642 | } |
| 2643 | |
| 2644 | int svm_serialize_model(std::ostream &outputStream, const struct svm_model *model, const std::vector<double> &offset, const std::vector<double> &scale, const std::map<std::string,short> &classValueMap, const std::vector<std::string> &nameVector, const std::vector<std::string> &bandNames)//pk 11/04/2018{ |
| 2645 | { |
| 2646 | Json::Value model_json; |
| 2647 | const svm_parameter& param = model->param; |
| 2648 | |
| 2649 | model_json["svm_type"]=svm_type_table[param.svm_type]; |
| 2650 | model_json["kernel_type"]=kernel_type_table[param.kernel_type]; |
| 2651 | |
| 2652 | |
| 2653 | if(param.kernel_type == POLY) |
| 2654 | model_json["degree"]=param.degree; |
| 2655 | |
| 2656 | if(param.kernel_type == POLY || param.kernel_type == RBF || param.kernel_type == SIGMOID) |
| 2657 | model_json["gamma"]=param.gamma; |
| 2658 | |
| 2659 | if(param.kernel_type == POLY || param.kernel_type == SIGMOID) |
| 2660 | model_json["coef0"]=param.coef0; |
| 2661 | |
| 2662 | int nr_class = model->nr_class; |
| 2663 | int l = model->l; |
| 2664 | model_json["nr_class"]=nr_class; |
| 2665 | model_json["total_sv"]=l; |
| 2666 | { |
| 2667 | Json::Value rho_json; |
| 2668 | for(int i=0;i<nr_class*(nr_class-1)/2;i++) |
| 2669 | rho_json.append(model->rho[i]); |
| 2670 | model_json["rho"]=rho_json; |
| 2671 | } |
| 2672 | if(model->label) |
| 2673 | { |
| 2674 | Json::Value label_json; |
| 2675 | for(int i=0;i<nr_class;++i) |
| 2676 | label_json.append(model->label[i]); |
| 2677 | model_json["label"]=label_json; |
| 2678 | } |
| 2679 | |
| 2680 | if(model->probA) // regression has probA only |
| 2681 | { |
| 2682 | Json::Value probA_json; |
| 2683 | for(int i=0;i<nr_class*(nr_class-1)/2;i++) |
| 2684 | probA_json.append(model->probA[i]); |
| 2685 | model_json["probA"]=probA_json; |
| 2686 | } |
| 2687 | if(model->probB) |
| 2688 | { |
| 2689 | Json::Value probB_json; |
| 2690 | for(int i=0;i<nr_class*(nr_class-1)/2;i++) |
| 2691 | probB_json.append(model->probB[i]); |
| 2692 | model_json["probB"]=probB_json; |
| 2693 | } |
| 2694 | if(offset.size()){ |
| 2695 | Json::Value offset_json; |
| 2696 | for(int i=0;i<offset.size();i++) |
| 2697 | offset_json.append(offset[i]); |
| 2698 | model_json["offset"]=offset_json; |
| 2699 | } |
| 2700 | if(scale.size()){ |
| 2701 | Json::Value scale_json; |
| 2702 | for(int i=0;i<scale.size();i++) |
| 2703 | scale_json.append(scale[i]); |
| 2704 | model_json["scale"]=scale_json; |
| 2705 | } |
| 2706 | //classValueMap |
| 2707 | if(classValueMap.size()){ |
| 2708 | Json::Value classValueMap_json; |
| 2709 | std::map<std::string,short>::const_iterator mapit=classValueMap.begin(); |
| 2710 | while(mapit!=classValueMap.end()){ |
| 2711 | classValueMap_json[mapit->first]=mapit->second; |
| 2712 | ++mapit; |
| 2713 | } |
| 2714 | model_json["classValueMap"]=classValueMap_json; |
| 2715 | } |
| 2716 | //nameVector |
| 2717 | if(nameVector.size()){ |
| 2718 | Json::Value nameVector_json; |
| 2719 | for(int index=0;index<nameVector.size();++index) |
| 2720 | nameVector_json.append(nameVector[index]); |
| 2721 | model_json["nameVector"]=nameVector_json; |
| 2722 | } |
| 2723 | //bandNames |
| 2724 | if(bandNames.size()){ |
| 2725 | Json::Value bandNames_json; |
| 2726 | for(int index=0;index<bandNames.size();++index) |
| 2727 | bandNames_json.append(bandNames[index]); |
| 2728 | model_json["bandNames"]=bandNames_json; |
| 2729 | } |
| 2730 | if(model->nSV) |
| 2731 | { |
| 2732 | Json::Value nSV_json; |
| 2733 | for(int i=0;i<nr_class;i++) |
| 2734 | nSV_json.append(model->nSV[i]); |
| 2735 | model_json["nr_sv"]=nSV_json; |
| 2736 | } |
| 2737 | |
| 2738 | const double * const *sv_coef = model->sv_coef; |
| 2739 | const svm_node * const *SV = model->SV; |
| 2740 | |
| 2741 | Json::Value SV_coefs; |
| 2742 | Json::Value SV_nodes; |
| 2743 | for(int i=0;i<model->l;i++) |
| 2744 | { |
| 2745 | Json::Value SV_coef; |
| 2746 | Json::Value SV_node; |
| 2747 | for(int j=0;j<nr_class-1;j++) |
| 2748 | SV_coef.append(sv_coef[j][i]); |
| 2749 | SV_coefs.append(SV_coef); |
| 2750 | |
| 2751 | const svm_node *p = SV[i]; |
| 2752 | |
| 2753 | if(param.kernel_type == PRECOMPUTED){ |
| 2754 | SV_node.append((int)(p->value)); |
| 2755 | // SV_node["0"]=(int)(p->value); |
| 2756 | } |
| 2757 | else{ |
| 2758 | int ndim=0; |
| 2759 | while(p->index != -1) |
| 2760 | { |
| 2761 | SV_node.append(p->value); |
| 2762 | p++; |
| 2763 | ++ndim; |
| 2764 | } |
| 2765 | } |
| 2766 | SV_nodes.append(SV_node); |
| 2767 | } |
| 2768 | model_json["SV_coef"]=SV_coefs; |
| 2769 | model_json["SV_node"]=SV_nodes; |
| 2770 | |
| 2771 | Json::StreamWriterBuilder builder; |
| 2772 | outputStream << Json::writeString(builder, model_json) << std::endl; |
| 2773 | return 0; |
| 2774 | } |
| 2775 | |
| 2776 | int svm_save_model_old(const char *model_file_name, const svm_model *model) |
| 2777 | { |
| 2778 | FILE *fp = fopen(model_file_name,"w"); |
| 2779 | if(fp==NULL) return -1; |
| 2780 | |
| 2781 | char *old_locale = strdup(setlocale(LC_ALL, NULL)); |
| 2782 | setlocale(LC_ALL, "C"); |
| 2783 | |
| 2784 | const svm_parameter& param = model->param; |
| 2785 | |
| 2786 | fprintf(fp,"svm_type %s\n", svm_type_table[param.svm_type]); |
| 2787 | fprintf(fp,"kernel_type %s\n", kernel_type_table[param.kernel_type]); |
| 2788 | |
| 2789 | if(param.kernel_type == POLY) |
| 2790 | fprintf(fp,"degree %d\n", param.degree); |
| 2791 | |
| 2792 | if(param.kernel_type == POLY || param.kernel_type == RBF || param.kernel_type == SIGMOID) |
| 2793 | fprintf(fp,"gamma %g\n", param.gamma); |
| 2794 | |
| 2795 | if(param.kernel_type == POLY || param.kernel_type == SIGMOID) |
| 2796 | fprintf(fp,"coef0 %g\n", param.coef0); |
| 2797 | |
| 2798 | int nr_class = model->nr_class; |
| 2799 | int l = model->l; |
| 2800 | fprintf(fp, "nr_class %d\n", nr_class); |
| 2801 | fprintf(fp, "total_sv %d\n",l); |
| 2802 | |
| 2803 | { |
| 2804 | fprintf(fp, "rho"); |
| 2805 | for(int i=0;i<nr_class*(nr_class-1)/2;i++) |
| 2806 | fprintf(fp," %g",model->rho[i]); |
| 2807 | fprintf(fp, "\n"); |
| 2808 | } |
| 2809 | |
| 2810 | if(model->label) |
| 2811 | { |
| 2812 | fprintf(fp, "label"); |
| 2813 | for(int i=0;i<nr_class;i++) |
| 2814 | fprintf(fp," %d",model->label[i]); |
| 2815 | fprintf(fp, "\n"); |
| 2816 | } |
| 2817 | |
| 2818 | if(model->probA) // regression has probA only |
| 2819 | { |
| 2820 | fprintf(fp, "probA"); |
| 2821 | for(int i=0;i<nr_class*(nr_class-1)/2;i++) |
| 2822 | fprintf(fp," %g",model->probA[i]); |
| 2823 | fprintf(fp, "\n"); |
| 2824 | } |
| 2825 | if(model->probB) |
| 2826 | { |
| 2827 | fprintf(fp, "probB"); |
| 2828 | for(int i=0;i<nr_class*(nr_class-1)/2;i++) |
| 2829 | fprintf(fp," %g",model->probB[i]); |
| 2830 | fprintf(fp, "\n"); |
| 2831 | } |
| 2832 | if(model->nSV) |
| 2833 | { |
| 2834 | fprintf(fp, "nr_sv"); |
| 2835 | for(int i=0;i<nr_class;i++) |
| 2836 | fprintf(fp," %d",model->nSV[i]); |
| 2837 | fprintf(fp, "\n"); |
| 2838 | } |
| 2839 | |
| 2840 | fprintf(fp, "SV\n"); |
| 2841 | const double * const *sv_coef = model->sv_coef; |
| 2842 | const svm_node * const *SV = model->SV; |
| 2843 | |
| 2844 | for(int i=0;i<l;i++) |
| 2845 | { |
| 2846 | for(int j=0;j<nr_class-1;j++) |
| 2847 | fprintf(fp, "%.16g ",sv_coef[j][i]); |
| 2848 | |
| 2849 | const svm_node *p = SV[i]; |
| 2850 | |
| 2851 | if(param.kernel_type == PRECOMPUTED) |
| 2852 | fprintf(fp,"0:%d ",(int)(p->value)); |
| 2853 | else |
| 2854 | while(p->index != -1) |
| 2855 | { |
| 2856 | fprintf(fp,"%d:%.8g ",p->index,p->value); |
| 2857 | p++; |
| 2858 | } |
| 2859 | fprintf(fp, "\n"); |
| 2860 | } |
| 2861 | |
| 2862 | setlocale(LC_ALL, old_locale); |
| 2863 | free(old_locale); |
| 2864 | |
| 2865 | if (ferror(fp) != 0 || fclose(fp) != 0) return -1; |
| 2866 | else return 0; |
| 2867 | } |
| 2868 | |
| 2869 | static char *line = NULL; |
| 2870 | static int max_line_len; |
| 2871 | |
| 2872 | static char* readline(FILE *input) |
| 2873 | { |
| 2874 | int len; |
| 2875 | |
| 2876 | if(fgets(line,max_line_len,input) == NULL) |
| 2877 | return NULL; |
| 2878 | |
| 2879 | while(strrchr(line,'\n') == NULL) |
| 2880 | { |
| 2881 | max_line_len *= 2; |
| 2882 | line = (char *) realloc(line,max_line_len); |
| 2883 | len = (int) strlen(line); |
| 2884 | if(fgets(line+len,max_line_len-len,input) == NULL) |
| 2885 | break; |
| 2886 | } |
| 2887 | return line; |
| 2888 | } |
| 2889 | |
| 2890 | // svm_model *svm_load_model(const char *model_file_name) |
| 2891 | svm_model *svm_load_model(const std::string &model_file_name, std::vector<double> &offset, std::vector<double> &scale, std::map<std::string,short> &classValueMap, std::vector<std::string> &nameVector, std::vector<std::string> &bandNames)//pk 2/10/2017 |
| 2892 | { |
| 2893 | std::ifstream jsonfile(model_file_name); |
| 2894 | Json::Value root; |
| 2895 | jsonfile >> root; |
| 2896 | |
| 2897 | // read parameters |
| 2898 | |
| 2899 | svm_model *model = Malloc(svm_model,1); |
| 2900 | svm_parameter& param = model->param; |
| 2901 | model->rho = NULL; |
| 2902 | model->probA = NULL; |
| 2903 | model->probB = NULL; |
| 2904 | model->label = NULL; |
| 2905 | model->nSV = NULL; |
| 2906 | |
| 2907 | int i=0; |
| 2908 | int n=0; |
| 2909 | int m=0; |
| 2910 | int l=0; |
| 2911 | for(i=0;svm_type_table[i];i++){ |
| 2912 | if(strcmp(svm_type_table[i],root["svm_type"].asString().c_str())==0){ |
| 2913 | param.svm_type=i; |
| 2914 | break; |
| 2915 | } |
| 2916 | } |
| 2917 | if(svm_type_table[i] == NULL) |
| 2918 | { |
| 2919 | fprintf(stderr,"unknown svm type.\n"); |
| 2920 | |
| 2921 | free(model->rho); |
| 2922 | free(model->label); |
| 2923 | free(model->nSV); |
| 2924 | free(model); |
| 2925 | return NULL; |
| 2926 | } |
| 2927 | for(i=0;kernel_type_table[i];i++) |
| 2928 | { |
| 2929 | if(strcmp(kernel_type_table[i],root["kernel_type"].asString().c_str())==0) |
| 2930 | { |
| 2931 | param.kernel_type=i; |
| 2932 | break; |
| 2933 | } |
| 2934 | } |
| 2935 | if(kernel_type_table[i] == NULL) |
| 2936 | { |
| 2937 | fprintf(stderr,"unknown kernel function.\n"); |
| 2938 | |
| 2939 | free(model->rho); |
| 2940 | free(model->label); |
| 2941 | free(model->nSV); |
| 2942 | free(model); |
| 2943 | return NULL; |
| 2944 | } |
| 2945 | if(param.kernel_type==POLY){ |
| 2946 | param.degree=root["degree"].asInt(); |
| 2947 | } |
| 2948 | if(param.kernel_type == POLY || param.kernel_type == RBF || param.kernel_type == SIGMOID){ |
| 2949 | param.gamma=root["gamma"].asDouble(); |
| 2950 | } |
| 2951 | if(param.kernel_type == POLY || param.kernel_type == SIGMOID){ |
| 2952 | param.coef0=root["coef0"].asDouble(); |
| 2953 | } |
| 2954 | model->nr_class=root["nr_class"].asInt(); |
| 2955 | model->l=root["total_sv"].asInt(); |
| 2956 | n = model->nr_class * (model->nr_class-1)/2; |
| 2957 | model->rho = Malloc(double,n); |
| 2958 | for(i=0;i<n;i++) |
| 2959 | model->rho[i]=root["rho"][i].asDouble(); |
| 2960 | n = model->nr_class; |
| 2961 | model->label = Malloc(int,n); |
| 2962 | for(i=0;i<n;i++) |
| 2963 | model->label[i]=root["label"][i].asInt(); |
| 2964 | n = model->nr_class * (model->nr_class-1)/2; |
| 2965 | model->probA = Malloc(double,n); |
| 2966 | for(i=0;i<n;i++) |
| 2967 | model->probA[i]=root["probA"][i].asDouble(); |
| 2968 | n = model->nr_class * (model->nr_class-1)/2; |
| 2969 | model->probB = Malloc(double,n); |
| 2970 | for(i=0;i<n;i++) |
| 2971 | model->probB[i]=root["probB"][i].asDouble(); |
| 2972 | offset.resize(root["offset"].size()); |
| 2973 | for(i=0;i<offset.size();++i) |
| 2974 | offset[i]=root["offset"][i].asDouble(); |
| 2975 | scale.resize(root["scale"].size()); |
| 2976 | for(i=0;i<scale.size();++i) |
| 2977 | scale[i]=root["scale"][i].asDouble(); |
| 2978 | n = model->nr_class; |
| 2979 | nameVector.resize(root["nameVector"].size()); |
| 2980 | for(i=0;i<n;i++){ |
| 2981 | nameVector[i]=root["nameVector"][i].asString(); |
| 2982 | classValueMap[nameVector[i]]=root["classValueMap"][nameVector[i]].asInt(); |
| 2983 | } |
| 2984 | if(root["bandNames"].size()){ |
| 2985 | bandNames.resize(root["bandNames"].size()); |
| 2986 | for(i=0;i<bandNames.size();++i) |
| 2987 | bandNames[i]=root["bandNames"][i].asString(); |
| 2988 | } |
| 2989 | else |
| 2990 | bandNames=std::vector<std::string>(); |
| 2991 | n = model->nr_class; |
| 2992 | model->nSV = Malloc(int,n); |
| 2993 | for(i=0;i<model->nr_class;++i) |
| 2994 | model->nSV[i]=root["nr_sv"][i].asInt(); |
| 2995 | m = model->nr_class - 1; |
| 2996 | l = model->l; |
| 2997 | model->sv_coef = Malloc(double *,m); |
| 2998 | for(i=0;i<m;i++) |
| 2999 | model->sv_coef[i] = Malloc(double,l); |
| 3000 | |
| 3001 | // read sv_coef and SV |
| 3002 | |
| 3003 | m = model->nr_class - 1; |
| 3004 | l = model->l; |
| 3005 | model->sv_coef = Malloc(double *,m); |
| 3006 | for(i=0;i<m;i++) |
| 3007 | model->sv_coef[i] = Malloc(double,l); |
| 3008 | model->SV = Malloc(svm_node*,l); |
| 3009 | svm_node *x_space = NULL; |
| 3010 | if(l>0) x_space = Malloc(svm_node,l*(offset.size()+1)); |
| 3011 | |
| 3012 | int j=0; |
| 3013 | for(i=0;i<model->l;++i)//number of SV |
| 3014 | { |
| 3015 | model->SV[i] = &x_space[j]; |
| 3016 | model->sv_coef[0][i] = root["SV_coef"][i][0].asDouble(); |
| 3017 | for(int k=1;k<m;k++){ |
| 3018 | model->sv_coef[k][i] = root["SV_coef"][i][k].asDouble(); |
| 3019 | } |
| 3020 | if(param.kernel_type == PRECOMPUTED){ |
| 3021 | x_space[j].index=0; |
| 3022 | // x_space[j].value=root["SV_node"][i]["0"].asDouble(); |
| 3023 | x_space[j].value=root["SV_node"][i][0].asDouble(); |
| 3024 | ++j; |
| 3025 | } |
| 3026 | else{ |
| 3027 | for(int index=0;index<offset.size();++index){ |
| 3028 | x_space[j].index=index+1; |
| 3029 | x_space[j].value=root["SV_node"][i][index].asDouble(); |
| 3030 | ++j; |
| 3031 | } |
| 3032 | } |
| 3033 | x_space[j].index = -1; |
| 3034 | ++j; |
| 3035 | } |
| 3036 | model->free_sv = 1; // XXX |
| 3037 | return model; |
| 3038 | } |
| 3039 | |
| 3040 | void svm_free_model_content(svm_model* model_ptr) |
| 3041 | { |
| 3042 | if(model_ptr->free_sv && model_ptr->l > 0 && model_ptr->SV != NULL) |
| 3043 | free((void *)(model_ptr->SV[0])); |
| 3044 | if(model_ptr->sv_coef) |
| 3045 | { |
| 3046 | for(int i=0;i<model_ptr->nr_class-1;i++) |
| 3047 | free(model_ptr->sv_coef[i]); |
| 3048 | } |
| 3049 | |
| 3050 | free(model_ptr->SV); |
| 3051 | model_ptr->SV = NULL; |
| 3052 | |
| 3053 | free(model_ptr->sv_coef); |
| 3054 | model_ptr->sv_coef = NULL; |
| 3055 | |
| 3056 | free(model_ptr->rho); |
| 3057 | model_ptr->rho = NULL; |
| 3058 | |
| 3059 | free(model_ptr->label); |
| 3060 | model_ptr->label= NULL; |
| 3061 | |
| 3062 | free(model_ptr->probA); |
| 3063 | model_ptr->probA = NULL; |
| 3064 | |
| 3065 | free(model_ptr->probB); |
| 3066 | model_ptr->probB= NULL; |
| 3067 | |
| 3068 | free(model_ptr->nSV); |
| 3069 | model_ptr->nSV = NULL; |
| 3070 | } |
| 3071 | |
| 3072 | void svm_free_and_destroy_model(svm_model** model_ptr_ptr) |
| 3073 | { |
| 3074 | if(model_ptr_ptr != NULL && *model_ptr_ptr != NULL) |
| 3075 | { |
| 3076 | svm_free_model_content(*model_ptr_ptr); |
| 3077 | free(*model_ptr_ptr); |
| 3078 | *model_ptr_ptr = NULL; |
| 3079 | } |
| 3080 | } |
| 3081 | |
| 3082 | void svm_destroy_param(svm_parameter* param) |
| 3083 | { |
| 3084 | free(param->weight_label); |
| 3085 | free(param->weight); |
| 3086 | } |
| 3087 | |
| 3088 | const char *svm_check_parameter(const svm_problem *prob, const svm_parameter *param) |
| 3089 | { |
| 3090 | // svm_type |
| 3091 | |
| 3092 | int svm_type = param->svm_type; |
| 3093 | if(svm_type != C_SVC && |
| 3094 | svm_type != NU_SVC && |
| 3095 | svm_type != ONE_CLASS && |
| 3096 | svm_type != EPSILON_SVR && |
| 3097 | svm_type != NU_SVR) |
| 3098 | return "unknown svm type"; |
| 3099 | |
| 3100 | // kernel_type, degree |
| 3101 | |
| 3102 | int kernel_type = param->kernel_type; |
| 3103 | if(kernel_type != LINEAR && |
| 3104 | kernel_type != POLY && |
| 3105 | kernel_type != RBF && |
| 3106 | kernel_type != SIGMOID && |
| 3107 | kernel_type != PRECOMPUTED) |
| 3108 | return "unknown kernel type"; |
| 3109 | |
| 3110 | if(param->gamma < 0) |
| 3111 | return "gamma < 0"; |
| 3112 | |
| 3113 | if(param->degree < 0) |
| 3114 | return "degree of polynomial kernel < 0"; |
| 3115 | |
| 3116 | // cache_size,eps,C,nu,p,shrinking |
| 3117 | |
| 3118 | if(param->cache_size <= 0) |
| 3119 | return "cache_size <= 0"; |
| 3120 | |
| 3121 | if(param->eps <= 0) |
| 3122 | return "eps <= 0"; |
| 3123 | |
| 3124 | if(svm_type == C_SVC || |
| 3125 | svm_type == EPSILON_SVR || |
| 3126 | svm_type == NU_SVR) |
| 3127 | if(param->C <= 0) |
| 3128 | return "C <= 0"; |
| 3129 | |
| 3130 | if(svm_type == NU_SVC || |
| 3131 | svm_type == ONE_CLASS || |
| 3132 | svm_type == NU_SVR) |
| 3133 | if(param->nu <= 0 || param->nu > 1) |
| 3134 | return "nu <= 0 or nu > 1"; |
| 3135 | |
| 3136 | if(svm_type == EPSILON_SVR) |
| 3137 | if(param->p < 0) |
| 3138 | return "p < 0"; |
| 3139 | |
| 3140 | if(param->shrinking != 0 && |
| 3141 | param->shrinking != 1) |
| 3142 | return "shrinking != 0 and shrinking != 1"; |
| 3143 | |
| 3144 | if(param->probability != 0 && |
| 3145 | param->probability != 1) |
| 3146 | return "probability != 0 and probability != 1"; |
| 3147 | |
| 3148 | if(param->probability == 1 && |
| 3149 | svm_type == ONE_CLASS) |
| 3150 | return "one-class SVM probability output not supported yet"; |
| 3151 | |
| 3152 | |
| 3153 | // check whether nu-svc is feasible |
| 3154 | |
| 3155 | if(svm_type == NU_SVC) |
| 3156 | { |
| 3157 | int l = prob->l; |
| 3158 | int max_nr_class = 16; |
| 3159 | int nr_class = 0; |
| 3160 | int *label = Malloc(int,max_nr_class); |
| 3161 | int *count = Malloc(int,max_nr_class); |
| 3162 | |
| 3163 | int i; |
| 3164 | for(i=0;i<l;i++) |
| 3165 | { |
| 3166 | int this_label = (int)prob->y[i]; |
| 3167 | int j; |
| 3168 | for(j=0;j<nr_class;j++) |
| 3169 | if(this_label == label[j]) |
| 3170 | { |
| 3171 | ++count[j]; |
| 3172 | break; |
| 3173 | } |
| 3174 | if(j == nr_class) |
| 3175 | { |
| 3176 | if(nr_class == max_nr_class) |
| 3177 | { |
| 3178 | max_nr_class *= 2; |
| 3179 | label = (int *)realloc(label,max_nr_class*sizeof(int)); |
| 3180 | count = (int *)realloc(count,max_nr_class*sizeof(int)); |
| 3181 | } |
| 3182 | label[nr_class] = this_label; |
| 3183 | count[nr_class] = 1; |
| 3184 | ++nr_class; |
| 3185 | } |
| 3186 | } |
| 3187 | |
| 3188 | for(i=0;i<nr_class;i++) |
| 3189 | { |
| 3190 | int n1 = count[i]; |
| 3191 | for(int j=i+1;j<nr_class;j++) |
| 3192 | { |
| 3193 | int n2 = count[j]; |
| 3194 | if(param->nu*(n1+n2)/2 > min(n1,n2)) |
| 3195 | { |
| 3196 | free(label); |
| 3197 | free(count); |
| 3198 | return "specified nu is infeasible"; |
| 3199 | } |
| 3200 | } |
| 3201 | } |
| 3202 | free(label); |
| 3203 | free(count); |
| 3204 | } |
| 3205 | |
| 3206 | return NULL; |
| 3207 | } |
| 3208 | |
| 3209 | int svm_check_probability_model(const svm_model *model) |
| 3210 | { |
| 3211 | return ((model->param.svm_type == C_SVC || model->param.svm_type == NU_SVC) && |
| 3212 | model->probA!=NULL && model->probB!=NULL) || |
| 3213 | ((model->param.svm_type == EPSILON_SVR || model->param.svm_type == NU_SVR) && |
| 3214 | model->probA!=NULL); |
| 3215 | } |
| 3216 | |
| 3217 | void svm_set_print_string_function(void (*print_func)(const char *)) |
| 3218 | { |
| 3219 | if(print_func == NULL) |
| 3220 | svm_print_string = &print_string_stdout; |
| 3221 | else |
| 3222 | svm_print_string = print_func; |
| 3223 | } |