6 int libsvm_version = LIBSVM_VERSION;
8 typedef signed char schar;
10 template <
class T>
static inline T min(T x,T y) {
return (x<y)?x:y; }
13 template <
class T>
static inline T max(T x,T y) {
return (x>y)?x:y; }
15 template <
class T>
static inline void swap(T& x, T& y) { T t=x; x=y; y=t; }
16 template <
class S,
class T>
static inline void clone(T*& dst, S* src,
int n)
19 memcpy((
void *)dst,(
void *)src,
sizeof(T)*n);
21 static inline double powi(
double base,
int times)
23 double tmp = base, ret = 1.0;
25 for(
int t=times; t>0; t/=2)
34 #define Malloc(type,n) (type *)malloc((n)*sizeof(type))
36 static void print_string_stdout(
const char *s)
41 static void (*svm_print_string) (
const char *) = &print_string_stdout;
43 static void info(
const char *fmt,...)
50 (*svm_print_string)(buf);
53 static void info(
const char *fmt,...) {}
65 Cache(
int l,
long int size);
71 int get_data(
const int index, Qfloat **data,
int len);
72 void swap_index(
int i,
int j);
85 void lru_delete(head_t *h);
86 void lru_insert(head_t *h);
89 Cache::Cache(
int l_,
long int size_):l(l_),size(size_)
91 head = (head_t *)calloc(l,
sizeof(head_t));
92 size /=
sizeof(Qfloat);
93 size -= l *
sizeof(head_t) /
sizeof(Qfloat);
94 size = std::max(size, 2 * (
long int) l);
95 lru_head.next = lru_head.prev = &lru_head;
100 for(head_t *h = lru_head.next; h != &lru_head; h=h->next)
105 void Cache::lru_delete(head_t *h)
108 h->prev->next = h->next;
109 h->next->prev = h->prev;
112 void Cache::lru_insert(head_t *h)
116 h->prev = lru_head.prev;
121 int Cache::get_data(
const int index, Qfloat **data,
int len)
123 head_t *h = &head[index];
124 if(h->len) lru_delete(h);
125 int more = len - h->len;
132 head_t *old = lru_head.next;
141 h->data = (Qfloat *)realloc(h->data,
sizeof(Qfloat)*len);
143 std::swap(h->len,len);
151 void Cache::swap_index(
int i,
int j)
155 if(head[i].len) lru_delete(&head[i]);
156 if(head[j].len) lru_delete(&head[j]);
157 std::swap(head[i].data,head[j].data);
158 std::swap(head[i].len,head[j].len);
159 if(head[i].len) lru_insert(&head[i]);
160 if(head[j].len) lru_insert(&head[j]);
162 if(i>j) std::swap(i,j);
163 for(head_t *h = lru_head.next; h!=&lru_head; h=h->next)
168 std::swap(h->data[i],h->data[j]);
191 virtual Qfloat *get_Q(
int column,
int len)
const = 0;
192 virtual double *get_QD()
const = 0;
193 virtual void swap_index(
int i,
int j)
const = 0;
204 virtual Qfloat *get_Q(
int column,
int len)
const = 0;
205 virtual double *get_QD()
const = 0;
206 virtual void swap_index(
int i,
int j)
const
208 std::swap(x[i],x[j]);
209 if(x_square) std::swap(x_square[i],x_square[j]);
213 double (
Kernel::*kernel_function)(
int i,
int j)
const;
220 const int kernel_type;
226 double kernel_linear(
int i,
int j)
const
228 return dot(x[i],x[j]);
230 double kernel_poly(
int i,
int j)
const
232 return powi(gamma*dot(x[i],x[j])+coef0,degree);
234 double kernel_rbf(
int i,
int j)
const
236 return exp(-gamma*(x_square[i]+x_square[j]-2*dot(x[i],x[j])));
238 double kernel_sigmoid(
int i,
int j)
const
240 return tanh(gamma*dot(x[i],x[j])+coef0);
242 double kernel_precomputed(
int i,
int j)
const
244 return x[i][(int)(x[j][0].value)].value;
249 :kernel_type(param.kernel_type), degree(param.degree),
250 gamma(param.gamma), coef0(param.coef0)
255 kernel_function = &Kernel::kernel_linear;
258 kernel_function = &Kernel::kernel_poly;
261 kernel_function = &Kernel::kernel_rbf;
264 kernel_function = &Kernel::kernel_sigmoid;
267 kernel_function = &Kernel::kernel_precomputed;
273 if(kernel_type == RBF)
275 x_square =
new double[l];
277 x_square[i] = dot(x[i],x[i]);
289 double Kernel::dot(
const svm_node *px,
const svm_node *py)
292 while(px->index != -1 && py->index != -1)
294 if(px->index == py->index)
296 sum += px->value * py->value;
302 if(px->index > py->index)
311 double Kernel::k_function(
const svm_node *x,
const svm_node *y,
312 const svm_parameter& param)
314 switch(param.kernel_type)
319 return powi(param.gamma*dot(x,y)+param.coef0,param.degree);
323 while(x->index != -1 && y->index !=-1)
325 if(x->index == y->index)
327 double d = x->value - y->value;
334 if(x->index > y->index)
336 sum += y->value * y->value;
341 sum += x->value * x->value;
347 while(x->index != -1)
349 sum += x->value * x->value;
353 while(y->index != -1)
355 sum += y->value * y->value;
359 return exp(-param.gamma*sum);
362 return tanh(param.gamma*dot(x,y)+param.coef0);
364 return x[(int)(y->value)].value;
396 double upper_bound_p;
397 double upper_bound_n;
401 void Solve(
int l,
const QMatrix& Q,
const double *p_,
const schar *y_,
402 double *alpha_,
double Cp,
double Cn,
double eps,
408 enum { LOWER_BOUND, UPPER_BOUND, FREE };
423 return (y[i] > 0)? Cp : Cn;
425 void update_alpha_status(
int i)
427 if(alpha[i] >= get_C(i))
428 alpha_status[i] = UPPER_BOUND;
429 else if(alpha[i] <= 0)
430 alpha_status[i] = LOWER_BOUND;
431 else alpha_status[i] = FREE;
433 bool is_upper_bound(
int i) {
return alpha_status[i] == UPPER_BOUND; }
434 bool is_lower_bound(
int i) {
return alpha_status[i] == LOWER_BOUND; }
435 bool is_free(
int i) {
return alpha_status[i] == FREE; }
436 void swap_index(
int i,
int j);
437 void reconstruct_gradient();
438 virtual int select_working_set(
int &i,
int &j);
439 virtual double calculate_rho();
440 virtual void do_shrinking();
442 bool be_shrunk(
int i,
double Gmax1,
double Gmax2);
445 void Solver::swap_index(
int i,
int j)
448 std::swap(y[i],y[j]);
449 std::swap(G[i],G[j]);
450 std::swap(alpha_status[i],alpha_status[j]);
451 std::swap(alpha[i],alpha[j]);
452 std::swap(p[i],p[j]);
453 std::swap(active_set[i],active_set[j]);
454 std::swap(G_bar[i],G_bar[j]);
457 void Solver::reconstruct_gradient()
461 if(active_size == l)
return;
466 for(j=active_size;j<l;j++)
467 G[j] = G_bar[j] + p[j];
469 for(j=0;j<active_size;j++)
473 if(2*nr_free < active_size)
474 info(
"\nWARNING: using -h 0 may be faster\n");
476 if (nr_free*l > 2*active_size*(l-active_size))
478 for(i=active_size;i<l;i++)
480 const Qfloat *Q_i = Q->get_Q(i,active_size);
481 for(j=0;j<active_size;j++)
483 G[i] += alpha[j] * Q_i[j];
488 for(i=0;i<active_size;i++)
491 const Qfloat *Q_i = Q->get_Q(i,l);
492 double alpha_i = alpha[i];
493 for(j=active_size;j<l;j++)
494 G[j] += alpha_i * Q_i[j];
499 void Solver::Solve(
int l,
const QMatrix& Q,
const double *p_,
const schar *y_,
500 double *alpha_,
double Cp,
double Cn,
double eps,
501 SolutionInfo* si,
int shrinking)
508 clone(alpha,alpha_,l);
516 alpha_status =
new char[l];
518 update_alpha_status(i);
523 active_set =
new int[l];
532 G_bar =
new double[l];
540 if(!is_lower_bound(i))
542 const Qfloat *Q_i = Q.get_Q(i,l);
543 double alpha_i = alpha[i];
546 G[j] += alpha_i*Q_i[j];
547 if(is_upper_bound(i))
549 G_bar[j] += get_C(i) * Q_i[j];
556 int max_iter = std::max(10000000, l>INT_MAX/100 ? INT_MAX : 100*l);
557 int counter = std::min(l,1000)+1;
559 while(iter < max_iter)
565 counter = std::min(l,1000);
566 if(shrinking) do_shrinking();
571 if(select_working_set(i,j)!=0)
574 reconstruct_gradient();
578 if(select_working_set(i,j)!=0)
588 const Qfloat *Q_i = Q.get_Q(i,active_size);
589 const Qfloat *Q_j = Q.get_Q(j,active_size);
591 double C_i = get_C(i);
592 double C_j = get_C(j);
594 double old_alpha_i = alpha[i];
595 double old_alpha_j = alpha[j];
599 double quad_coef = QD[i]+QD[j]+2*Q_i[j];
602 double delta = (-G[i]-G[j])/quad_coef;
603 double diff = alpha[i] - alpha[j];
628 alpha[j] = C_i - diff;
636 alpha[i] = C_j + diff;
642 double quad_coef = QD[i]+QD[j]-2*Q_i[j];
645 double delta = (G[i]-G[j])/quad_coef;
646 double sum = alpha[i] + alpha[j];
655 alpha[j] = sum - C_i;
671 alpha[i] = sum - C_j;
686 double delta_alpha_i = alpha[i] - old_alpha_i;
687 double delta_alpha_j = alpha[j] - old_alpha_j;
689 for(
int k=0;k<active_size;k++)
691 G[k] += Q_i[k]*delta_alpha_i + Q_j[k]*delta_alpha_j;
697 bool ui = is_upper_bound(i);
698 bool uj = is_upper_bound(j);
699 update_alpha_status(i);
700 update_alpha_status(j);
702 if(ui != is_upper_bound(i))
707 G_bar[k] -= C_i * Q_i[k];
710 G_bar[k] += C_i * Q_i[k];
713 if(uj != is_upper_bound(j))
718 G_bar[k] -= C_j * Q_j[k];
721 G_bar[k] += C_j * Q_j[k];
731 reconstruct_gradient();
735 info(
"\nWARNING: reaching max number of iterations");
740 si->rho = calculate_rho();
747 v += alpha[i] * (G[i] + p[i]);
755 alpha_[active_set[i]] = alpha[i];
766 si->upper_bound_p = Cp;
767 si->upper_bound_n = Cn;
769 info(
"\noptimization finished, #iter = %d\n",iter);
774 delete[] alpha_status;
781 int Solver::select_working_set(
int &out_i,
int &out_j)
793 double obj_diff_min = INF;
795 for(
int t=0;t<active_size;t++)
798 if(!is_upper_bound(t))
807 if(!is_lower_bound(t))
816 const Qfloat *Q_i = NULL;
818 Q_i = Q->get_Q(i,active_size);
820 for(
int j=0;j<active_size;j++)
824 if (!is_lower_bound(j))
826 double grad_diff=Gmax+G[j];
832 double quad_coef = QD[i]+QD[j]-2.0*y[i]*Q_i[j];
834 obj_diff = -(grad_diff*grad_diff)/quad_coef;
836 obj_diff = -(grad_diff*grad_diff)/TAU;
838 if (obj_diff <= obj_diff_min)
841 obj_diff_min = obj_diff;
848 if (!is_upper_bound(j))
850 double grad_diff= Gmax-G[j];
856 double quad_coef = QD[i]+QD[j]+2.0*y[i]*Q_i[j];
858 obj_diff = -(grad_diff*grad_diff)/quad_coef;
860 obj_diff = -(grad_diff*grad_diff)/TAU;
862 if (obj_diff <= obj_diff_min)
865 obj_diff_min = obj_diff;
880 bool Solver::be_shrunk(
int i,
double Gmax1,
double Gmax2)
882 if(is_upper_bound(i))
885 return(-G[i] > Gmax1);
887 return(-G[i] > Gmax2);
889 else if(is_lower_bound(i))
892 return(G[i] > Gmax2);
894 return(G[i] > Gmax1);
900 void Solver::do_shrinking()
907 for(i=0;i<active_size;i++)
911 if(!is_upper_bound(i))
916 if(!is_lower_bound(i))
924 if(!is_upper_bound(i))
929 if(!is_lower_bound(i))
937 if(unshrink ==
false && Gmax1 + Gmax2 <= eps*10)
940 reconstruct_gradient();
945 for(i=0;i<active_size;i++)
946 if (be_shrunk(i, Gmax1, Gmax2))
949 while (active_size > i)
951 if (!be_shrunk(active_size, Gmax1, Gmax2))
953 swap_index(i,active_size);
961 double Solver::calculate_rho()
965 double ub = INF, lb = -INF, sum_free = 0;
966 for(
int i=0;i<active_size;i++)
968 double yG = y[i]*G[i];
970 if(is_upper_bound(i))
973 ub = std::min(ub,yG);
975 lb = std::max(lb,yG);
977 else if(is_lower_bound(i))
980 ub = std::min(ub,yG);
982 lb = std::max(lb,yG);
992 r = sum_free/nr_free;
1008 void Solve(
int l,
const QMatrix& Q,
const double *p,
const schar *y,
1009 double *alpha,
double Cp,
double Cn,
double eps,
1010 SolutionInfo* si,
int shrinking)
1013 Solver::Solve(l,Q,p,y,alpha,Cp,Cn,eps,si,shrinking);
1017 int select_working_set(
int &i,
int &j);
1018 double calculate_rho();
1019 bool be_shrunk(
int i,
double Gmax1,
double Gmax2,
double Gmax3,
double Gmax4);
1020 void do_shrinking();
1024 int Solver_NU::select_working_set(
int &out_i,
int &out_j)
1032 double Gmaxp = -INF;
1033 double Gmaxp2 = -INF;
1036 double Gmaxn = -INF;
1037 double Gmaxn2 = -INF;
1041 double obj_diff_min = INF;
1043 for(
int t=0;t<active_size;t++)
1046 if(!is_upper_bound(t))
1055 if(!is_lower_bound(t))
1065 const Qfloat *Q_ip = NULL;
1066 const Qfloat *Q_in = NULL;
1068 Q_ip = Q->get_Q(ip,active_size);
1070 Q_in = Q->get_Q(in,active_size);
1072 for(
int j=0;j<active_size;j++)
1076 if (!is_lower_bound(j))
1078 double grad_diff=Gmaxp+G[j];
1084 double quad_coef = QD[ip]+QD[j]-2*Q_ip[j];
1086 obj_diff = -(grad_diff*grad_diff)/quad_coef;
1088 obj_diff = -(grad_diff*grad_diff)/TAU;
1090 if (obj_diff <= obj_diff_min)
1093 obj_diff_min = obj_diff;
1100 if (!is_upper_bound(j))
1102 double grad_diff=Gmaxn-G[j];
1103 if (-G[j] >= Gmaxn2)
1108 double quad_coef = QD[in]+QD[j]-2*Q_in[j];
1110 obj_diff = -(grad_diff*grad_diff)/quad_coef;
1112 obj_diff = -(grad_diff*grad_diff)/TAU;
1114 if (obj_diff <= obj_diff_min)
1117 obj_diff_min = obj_diff;
1124 if(std::max(Gmaxp+Gmaxp2,Gmaxn+Gmaxn2) < eps)
1127 if (y[Gmin_idx] == +1)
1136 bool Solver_NU::be_shrunk(
int i,
double Gmax1,
double Gmax2,
double Gmax3,
double Gmax4)
1138 if(is_upper_bound(i))
1141 return(-G[i] > Gmax1);
1143 return(-G[i] > Gmax4);
1145 else if(is_lower_bound(i))
1148 return(G[i] > Gmax2);
1150 return(G[i] > Gmax3);
1156 void Solver_NU::do_shrinking()
1158 double Gmax1 = -INF;
1159 double Gmax2 = -INF;
1160 double Gmax3 = -INF;
1161 double Gmax4 = -INF;
1165 for(i=0;i<active_size;i++)
1167 if(!is_upper_bound(i))
1171 if(-G[i] > Gmax1) Gmax1 = -G[i];
1173 else if(-G[i] > Gmax4) Gmax4 = -G[i];
1175 if(!is_lower_bound(i))
1179 if(G[i] > Gmax2) Gmax2 = G[i];
1181 else if(G[i] > Gmax3) Gmax3 = G[i];
1185 if(unshrink ==
false && std::max(Gmax1+Gmax2,Gmax3+Gmax4) <= eps*10)
1188 reconstruct_gradient();
1192 for(i=0;i<active_size;i++)
1193 if (be_shrunk(i, Gmax1, Gmax2, Gmax3, Gmax4))
1196 while (active_size > i)
1198 if (!be_shrunk(active_size, Gmax1, Gmax2, Gmax3, Gmax4))
1200 swap_index(i,active_size);
1208 double Solver_NU::calculate_rho()
1210 int nr_free1 = 0,nr_free2 = 0;
1211 double ub1 = INF, ub2 = INF;
1212 double lb1 = -INF, lb2 = -INF;
1213 double sum_free1 = 0, sum_free2 = 0;
1215 for(
int i=0;i<active_size;i++)
1219 if(is_upper_bound(i))
1220 lb1 = std::max(lb1,G[i]);
1221 else if(is_lower_bound(i))
1222 ub1 = std::min(ub1,G[i]);
1231 if(is_upper_bound(i))
1232 lb2 = std::max(lb2,G[i]);
1233 else if(is_lower_bound(i))
1234 ub2 = std::min(ub2,G[i]);
1245 r1 = sum_free1/nr_free1;
1250 r2 = sum_free2/nr_free2;
1265 :
Kernel(prob.l, prob.x, param)
1268 cache =
new Cache(prob.l,(
long int)(param.cache_size*(1<<20)));
1269 QD =
new double[prob.l];
1270 for(
int i=0;i<prob.l;i++)
1271 QD[i] = (this->*kernel_function)(i,i);
1274 Qfloat *get_Q(
int i,
int len)
const
1278 if((start = cache->get_data(i,&data,len)) < len)
1280 for(j=start;j<len;j++)
1281 data[j] = (Qfloat)(y[i]*y[j]*(this->*kernel_function)(i,j));
1286 double *get_QD()
const
1291 void swap_index(
int i,
int j)
const
1293 cache->swap_index(i,j);
1294 Kernel::swap_index(i,j);
1295 std::swap(y[i],y[j]);
1296 std::swap(QD[i],QD[j]);
1315 :
Kernel(prob.l, prob.x, param)
1317 cache =
new Cache(prob.l,(
long int)(param.cache_size*(1<<20)));
1318 QD =
new double[prob.l];
1319 for(
int i=0;i<prob.l;i++)
1320 QD[i] = (this->*kernel_function)(i,i);
1323 Qfloat *get_Q(
int i,
int len)
const
1327 if((start = cache->get_data(i,&data,len)) < len)
1329 for(j=start;j<len;j++)
1330 data[j] = (Qfloat)(this->*kernel_function)(i,j);
1335 double *get_QD()
const
1340 void swap_index(
int i,
int j)
const
1342 cache->swap_index(i,j);
1343 Kernel::swap_index(i,j);
1344 std::swap(QD[i],QD[j]);
1361 :
Kernel(prob.l, prob.x, param)
1364 cache =
new Cache(l,(
long int)(param.cache_size*(1<<20)));
1365 QD =
new double[2*l];
1366 sign =
new schar[2*l];
1367 index =
new int[2*l];
1368 for(
int k=0;k<l;k++)
1374 QD[k] = (this->*kernel_function)(k,k);
1377 buffer[0] =
new Qfloat[2*l];
1378 buffer[1] =
new Qfloat[2*l];
1382 void swap_index(
int i,
int j)
const
1384 std::swap(sign[i],sign[j]);
1385 std::swap(index[i],index[j]);
1386 std::swap(QD[i],QD[j]);
1389 Qfloat *get_Q(
int i,
int len)
const
1392 int j, real_i = index[i];
1393 if(cache->get_data(real_i,&data,l) < l)
1396 data[j] = (Qfloat)(this->*kernel_function)(real_i,j);
1400 Qfloat *buf = buffer[next_buffer];
1401 next_buffer = 1 - next_buffer;
1404 buf[j] = (Qfloat) si * (Qfloat) sign[j] * data[index[j]];
1408 double *get_QD()
const
1427 mutable int next_buffer;
1435 static void solve_c_svc(
1440 double *minus_ones =
new double[l];
1441 schar *y =
new schar[l];
1449 if(prob->y[i] > 0) y[i] = +1;
else y[i] = -1;
1453 s.Solve(l, SVC_Q(*prob,*param,y), minus_ones, y,
1454 alpha, Cp, Cn, param->eps, si, param->shrinking);
1458 sum_alpha += alpha[i];
1461 info(
"nu = %f\n", sum_alpha/(Cp*prob->l));
1466 delete[] minus_ones;
1470 static void solve_nu_svc(
1471 const svm_problem *prob,
const svm_parameter *param,
1472 double *alpha, Solver::SolutionInfo* si)
1476 double nu = param->nu;
1478 schar *y =
new schar[l];
1486 double sum_pos = nu*l/2;
1487 double sum_neg = nu*l/2;
1492 alpha[i] = std::min(1.0,sum_pos);
1493 sum_pos -= alpha[i];
1497 alpha[i] = std::min(1.0,sum_neg);
1498 sum_neg -= alpha[i];
1501 double *zeros =
new double[l];
1507 s.Solve(l, SVC_Q(*prob,*param,y), zeros, y,
1508 alpha, 1.0, 1.0, param->eps, si, param->shrinking);
1511 info(
"C = %f\n",1/r);
1518 si->upper_bound_p = 1/r;
1519 si->upper_bound_n = 1/r;
1525 static void solve_one_class(
1526 const svm_problem *prob,
const svm_parameter *param,
1527 double *alpha, Solver::SolutionInfo* si)
1530 double *zeros =
new double[l];
1531 schar *ones =
new schar[l];
1534 int n = (int)(param->nu*prob->l);
1539 alpha[n] = param->nu * prob->l - n;
1550 s.Solve(l, ONE_CLASS_Q(*prob,*param), zeros, ones,
1551 alpha, 1.0, 1.0, param->eps, si, param->shrinking);
1557 static void solve_epsilon_svr(
1558 const svm_problem *prob,
const svm_parameter *param,
1559 double *alpha, Solver::SolutionInfo* si)
1562 double *alpha2 =
new double[2*l];
1563 double *linear_term =
new double[2*l];
1564 schar *y =
new schar[2*l];
1570 linear_term[i] = param->p - prob->y[i];
1574 linear_term[i+l] = param->p + prob->y[i];
1579 s.Solve(2*l, SVR_Q(*prob,*param), linear_term, y,
1580 alpha2, param->C, param->C, param->eps, si, param->shrinking);
1582 double sum_alpha = 0;
1585 alpha[i] = alpha2[i] - alpha2[i+l];
1586 sum_alpha += fabs(alpha[i]);
1588 info(
"nu = %f\n",sum_alpha/(param->C*l));
1591 delete[] linear_term;
1595 static void solve_nu_svr(
1596 const svm_problem *prob,
const svm_parameter *param,
1597 double *alpha, Solver::SolutionInfo* si)
1600 double C = param->C;
1601 double *alpha2 =
new double[2*l];
1602 double *linear_term =
new double[2*l];
1603 schar *y =
new schar[2*l];
1606 double sum = C * param->nu * l / 2;
1609 alpha2[i] = alpha2[i+l] = std::min(sum,C);
1612 linear_term[i] = - prob->y[i];
1615 linear_term[i+l] = prob->y[i];
1620 s.Solve(2*l, SVR_Q(*prob,*param), linear_term, y,
1621 alpha2, C, C, param->eps, si, param->shrinking);
1623 info(
"epsilon = %f\n",-si->r);
1626 alpha[i] = alpha2[i] - alpha2[i+l];
1629 delete[] linear_term;
1644 double Cp,
double Cn)
1646 double *alpha = Malloc(
double,prob->l);
1648 switch(param->svm_type)
1651 solve_c_svc(prob,param,alpha,&si,Cp,Cn);
1654 solve_nu_svc(prob,param,alpha,&si);
1657 solve_one_class(prob,param,alpha,&si);
1660 solve_epsilon_svr(prob,param,alpha,&si);
1663 solve_nu_svr(prob,param,alpha,&si);
1667 info(
"obj = %f, rho = %f\n",si.obj,si.rho);
1673 for(
int i=0;i<prob->l;i++)
1675 if(fabs(alpha[i]) > 0)
1680 if(fabs(alpha[i]) >= si.upper_bound_p)
1685 if(fabs(alpha[i]) >= si.upper_bound_n)
1691 info(
"nSV = %d, nBSV = %d\n",nSV,nBSV);
1693 decision_function f;
1700 static void sigmoid_train(
1701 int l,
const double *dec_values,
const double *labels,
1702 double& A,
double& B)
1704 double prior1=0, prior0 = 0;
1708 if (labels[i] > 0) prior1+=1;
1712 double min_step=1e-10;
1715 double hiTarget=(prior1+1.0)/(prior1+2.0);
1716 double loTarget=1/(prior0+2.0);
1717 double *t=Malloc(
double,l);
1718 double fApB,p,q,h11,h22,h21,g1,g2,det,dA,dB,gd,stepsize;
1719 double newA,newB,newf,d1,d2;
1723 A=0.0; B=log((prior0+1.0)/(prior1+1.0));
1728 if (labels[i]>0) t[i]=hiTarget;
1730 fApB = dec_values[i]*A+B;
1732 fval += t[i]*fApB + log(1+exp(-fApB));
1734 fval += (t[i] - 1)*fApB +log(1+exp(fApB));
1736 for (iter=0;iter<max_iter;iter++)
1741 h21=0.0;g1=0.0;g2=0.0;
1744 fApB = dec_values[i]*A+B;
1747 p=exp(-fApB)/(1.0+exp(-fApB));
1748 q=1.0/(1.0+exp(-fApB));
1752 p=1.0/(1.0+exp(fApB));
1753 q=exp(fApB)/(1.0+exp(fApB));
1756 h11+=dec_values[i]*dec_values[i]*d2;
1758 h21+=dec_values[i]*d2;
1760 g1+=dec_values[i]*d1;
1765 if (fabs(g1)<eps && fabs(g2)<eps)
1769 det=h11*h22-h21*h21;
1770 dA=-(h22*g1 - h21 * g2) / det;
1771 dB=-(-h21*g1+ h11 * g2) / det;
1776 while (stepsize >= min_step)
1778 newA = A + stepsize * dA;
1779 newB = B + stepsize * dB;
1785 fApB = dec_values[i]*newA+newB;
1787 newf += t[i]*fApB + log(1+exp(-fApB));
1789 newf += (t[i] - 1)*fApB +log(1+exp(fApB));
1792 if (newf<fval+0.0001*stepsize*gd)
1794 A=newA;B=newB;fval=newf;
1798 stepsize = stepsize / 2.0;
1801 if (stepsize < min_step)
1803 info(
"Line search fails in two-class probability estimates\n");
1809 info(
"Reaching maximal iterations in two-class probability estimates\n");
1813 static double sigmoid_predict(
double decision_value,
double A,
double B)
1815 double fApB = decision_value*A+B;
1818 return exp(-fApB)/(1.0+exp(-fApB));
1820 return 1.0/(1+exp(fApB)) ;
1824 static void multiclass_probability(
int k,
double **r,
double *p)
1827 int iter = 0, max_iter=std::max(100,k);
1828 double **Q=Malloc(
double *,k);
1829 double *Qp=Malloc(
double,k);
1830 double pQp, eps=0.005/k;
1835 Q[t]=Malloc(
double,k);
1839 Q[t][t]+=r[j][t]*r[j][t];
1844 Q[t][t]+=r[j][t]*r[j][t];
1845 Q[t][j]=-r[j][t]*r[t][j];
1848 for (iter=0;iter<max_iter;iter++)
1856 Qp[t]+=Q[t][j]*p[j];
1862 double error=fabs(Qp[t]-pQp);
1863 if (error>max_error)
1866 if (max_error<eps)
break;
1870 double diff=(-Qp[t]+pQp)/Q[t][t];
1872 pQp=(pQp+diff*(diff*Q[t][t]+2*Qp[t]))/(1+diff)/(1+diff);
1875 Qp[j]=(Qp[j]+diff*Q[t][j])/(1+diff);
1881 info(
"Exceeds max_iter in multiclass_prob\n");
1882 for(t=0;t<k;t++) free(Q[t]);
1888 static void svm_binary_svc_probability(
1889 const svm_problem *prob,
const svm_parameter *param,
1890 double Cp,
double Cn,
double& probA,
double& probB)
1894 int *perm = Malloc(
int,prob->l);
1895 double *dec_values = Malloc(
double,prob->l);
1898 for(i=0;i<prob->l;i++) perm[i]=i;
1899 for(i=0;i<prob->l;i++)
1901 int j = i+rand()%(prob->l-i);
1902 std::swap(perm[i],perm[j]);
1904 for(i=0;i<nr_fold;i++)
1906 int begin = i*prob->l/nr_fold;
1907 int end = (i+1)*prob->l/nr_fold;
1909 struct svm_problem subprob;
1911 subprob.l = prob->l-(end-begin);
1912 subprob.x = Malloc(
struct svm_node*,subprob.l);
1913 subprob.y = Malloc(
double,subprob.l);
1916 for(j=0;j<begin;j++)
1918 subprob.x[k] = prob->x[perm[j]];
1919 subprob.y[k] = prob->y[perm[j]];
1922 for(j=end;j<prob->l;j++)
1924 subprob.x[k] = prob->x[perm[j]];
1925 subprob.y[k] = prob->y[perm[j]];
1928 int p_count=0,n_count=0;
1935 if(p_count==0 && n_count==0)
1936 for(j=begin;j<end;j++)
1937 dec_values[perm[j]] = 0;
1938 else if(p_count > 0 && n_count == 0)
1939 for(j=begin;j<end;j++)
1940 dec_values[perm[j]] = 1;
1941 else if(p_count == 0 && n_count > 0)
1942 for(j=begin;j<end;j++)
1943 dec_values[perm[j]] = -1;
1946 svm_parameter subparam = *param;
1947 subparam.probability=0;
1949 subparam.nr_weight=2;
1950 subparam.weight_label = Malloc(
int,2);
1951 subparam.weight = Malloc(
double,2);
1952 subparam.weight_label[0]=+1;
1953 subparam.weight_label[1]=-1;
1954 subparam.weight[0]=Cp;
1955 subparam.weight[1]=Cn;
1956 struct svm_model *submodel = svm_train(&subprob,&subparam);
1957 for(j=begin;j<end;j++)
1959 svm_predict_values(submodel,prob->x[perm[j]],&(dec_values[perm[j]]));
1961 dec_values[perm[j]] *= submodel->label[0];
1963 svm_free_and_destroy_model(&submodel);
1964 svm_destroy_param(&subparam);
1969 sigmoid_train(prob->l,dec_values,prob->y,probA,probB);
1975 static double svm_svr_probability(
1976 const svm_problem *prob,
const svm_parameter *param)
1980 double *ymv = Malloc(
double,prob->l);
1983 svm_parameter newparam = *param;
1984 newparam.probability = 0;
1985 svm_cross_validation(prob,&newparam,nr_fold,ymv);
1986 for(i=0;i<prob->l;i++)
1988 ymv[i]=prob->y[i]-ymv[i];
1989 mae += fabs(ymv[i]);
1992 double std=sqrt(2*mae*mae);
1995 for(i=0;i<prob->l;i++)
1996 if (fabs(ymv[i]) > 5*std)
2000 mae /= (prob->l-count);
2001 info(
"Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma= %g\n",mae);
2009 static void svm_group_classes(
const svm_problem *prob,
int *nr_class_ret,
int **label_ret,
int **start_ret,
int **count_ret,
int *perm)
2012 int max_nr_class = 16;
2014 int *label = Malloc(
int,max_nr_class);
2015 int *count = Malloc(
int,max_nr_class);
2016 int *data_label = Malloc(
int,l);
2021 int this_label = (int)prob->y[i];
2023 for(j=0;j<nr_class;j++)
2025 if(this_label == label[j])
2034 if(nr_class == max_nr_class)
2037 label = (
int *)realloc(label,max_nr_class*
sizeof(
int));
2038 count = (
int *)realloc(count,max_nr_class*
sizeof(
int));
2040 label[nr_class] = this_label;
2041 count[nr_class] = 1;
2046 int *start = Malloc(
int,nr_class);
2048 for(i=1;i<nr_class;i++)
2049 start[i] = start[i-1]+count[i-1];
2052 perm[start[data_label[i]]] = i;
2053 ++start[data_label[i]];
2056 for(i=1;i<nr_class;i++)
2057 start[i] = start[i-1]+count[i-1];
2059 *nr_class_ret = nr_class;
2069 svm_model *svm_train(
const svm_problem *prob,
const svm_parameter *param)
2071 svm_model *model = Malloc(svm_model,1);
2072 model->param = *param;
2075 if(param->svm_type == ONE_CLASS ||
2076 param->svm_type == EPSILON_SVR ||
2077 param->svm_type == NU_SVR)
2080 model->nr_class = 2;
2081 model->label = NULL;
2083 model->probA = NULL; model->probB = NULL;
2084 model->sv_coef = Malloc(
double *,1);
2086 if(param->probability &&
2087 (param->svm_type == EPSILON_SVR ||
2088 param->svm_type == NU_SVR))
2090 model->probA = Malloc(
double,1);
2091 model->probA[0] = svm_svr_probability(prob,param);
2094 decision_function f = svm_train_one(prob,param,0,0);
2095 model->rho = Malloc(
double,1);
2096 model->rho[0] = f.rho;
2100 for(i=0;i<prob->l;i++)
2101 if(fabs(f.alpha[i]) > 0) ++nSV;
2103 model->SV = Malloc(svm_node *,nSV);
2104 model->sv_coef[0] = Malloc(
double,nSV);
2106 for(i=0;i<prob->l;i++)
2107 if(fabs(f.alpha[i]) > 0)
2109 model->SV[j] = prob->x[i];
2110 model->sv_coef[0][j] = f.alpha[i];
2124 int *perm = Malloc(
int,l);
2127 svm_group_classes(prob,&nr_class,&label,&start,&count,perm);
2129 info(
"WARNING: training data in only one class. See README for details.\n");
2131 svm_node **x = Malloc(svm_node *,l);
2134 x[i] = prob->x[perm[i]];
2138 double *weighted_C = Malloc(
double, nr_class);
2139 for(i=0;i<nr_class;i++)
2140 weighted_C[i] = param->C;
2141 for(i=0;i<param->nr_weight;i++)
2144 for(j=0;j<nr_class;j++)
2145 if(param->weight_label[i] == label[j])
2148 fprintf(stderr,
"WARNING: class label %d specified in weight is not found\n", param->weight_label[i]);
2150 weighted_C[j] *= param->weight[i];
2155 bool *nonzero = Malloc(
bool,l);
2158 decision_function *f = Malloc(decision_function,nr_class*(nr_class-1)/2);
2160 double *probA=NULL,*probB=NULL;
2161 if (param->probability)
2163 probA=Malloc(
double,nr_class*(nr_class-1)/2);
2164 probB=Malloc(
double,nr_class*(nr_class-1)/2);
2168 for(i=0;i<nr_class;i++)
2169 for(
int j=i+1;j<nr_class;j++)
2171 svm_problem sub_prob;
2172 int si = start[i], sj = start[j];
2173 int ci = count[i], cj = count[j];
2175 sub_prob.x = Malloc(svm_node *,sub_prob.l);
2176 sub_prob.y = Malloc(
double,sub_prob.l);
2180 sub_prob.x[k] = x[si+k];
2185 sub_prob.x[ci+k] = x[sj+k];
2186 sub_prob.y[ci+k] = -1;
2189 if(param->probability)
2190 svm_binary_svc_probability(&sub_prob,param,weighted_C[i],weighted_C[j],probA[p],probB[p]);
2192 f[p] = svm_train_one(&sub_prob,param,weighted_C[i],weighted_C[j]);
2194 if(!nonzero[si+k] && fabs(f[p].alpha[k]) > 0)
2195 nonzero[si+k] =
true;
2197 if(!nonzero[sj+k] && fabs(f[p].alpha[ci+k]) > 0)
2198 nonzero[sj+k] =
true;
2206 model->nr_class = nr_class;
2208 model->label = Malloc(
int,nr_class);
2209 for(i=0;i<nr_class;i++)
2210 model->label[i] = label[i];
2212 model->rho = Malloc(
double,nr_class*(nr_class-1)/2);
2213 for(i=0;i<nr_class*(nr_class-1)/2;i++)
2214 model->rho[i] = f[i].rho;
2216 if(param->probability)
2218 model->probA = Malloc(
double,nr_class*(nr_class-1)/2);
2219 model->probB = Malloc(
double,nr_class*(nr_class-1)/2);
2220 for(i=0;i<nr_class*(nr_class-1)/2;i++)
2222 model->probA[i] = probA[i];
2223 model->probB[i] = probB[i];
2233 int *nz_count = Malloc(
int,nr_class);
2234 model->nSV = Malloc(
int,nr_class);
2235 for(i=0;i<nr_class;i++)
2238 for(
int j=0;j<count[i];j++)
2239 if(nonzero[start[i]+j])
2244 model->nSV[i] = nSV;
2248 info(
"Total nSV = %d\n",total_sv);
2250 model->l = total_sv;
2251 model->SV = Malloc(svm_node *,total_sv);
2254 if(nonzero[i]) model->SV[p++] = x[i];
2256 int *nz_start = Malloc(
int,nr_class);
2258 for(i=1;i<nr_class;i++)
2259 nz_start[i] = nz_start[i-1]+nz_count[i-1];
2261 model->sv_coef = Malloc(
double *,nr_class-1);
2262 for(i=0;i<nr_class-1;i++)
2263 model->sv_coef[i] = Malloc(
double,total_sv);
2266 for(i=0;i<nr_class;i++)
2267 for(
int j=i+1;j<nr_class;j++)
2278 int q = nz_start[i];
2282 model->sv_coef[j-1][q++] = f[p].alpha[k];
2286 model->sv_coef[i][q++] = f[p].alpha[ci+k];
2299 for(i=0;i<nr_class*(nr_class-1)/2;i++)
2309 void svm_cross_validation(
const svm_problem *prob,
const svm_parameter *param,
int nr_fold,
double *target)
2312 int *fold_start = Malloc(
int,nr_fold+1);
2314 int *perm = Malloc(
int,l);
2319 if((param->svm_type == C_SVC ||
2320 param->svm_type == NU_SVC) && nr_fold < l)
2325 svm_group_classes(prob,&nr_class,&label,&start,&count,perm);
2328 int *fold_count = Malloc(
int,nr_fold);
2330 int *index = Malloc(
int,l);
2333 for (c=0; c<nr_class; c++)
2334 for(i=0;i<count[c];i++)
2336 int j = i+rand()%(count[c]-i);
2337 std::swap(index[start[c]+j],index[start[c]+i]);
2339 for(i=0;i<nr_fold;i++)
2342 for (c=0; c<nr_class;c++)
2343 fold_count[i]+=(i+1)*count[c]/nr_fold-i*count[c]/nr_fold;
2346 for (i=1;i<=nr_fold;i++)
2347 fold_start[i] = fold_start[i-1]+fold_count[i-1];
2348 for (c=0; c<nr_class;c++)
2349 for(i=0;i<nr_fold;i++)
2351 int begin = start[c]+i*count[c]/nr_fold;
2352 int end = start[c]+(i+1)*count[c]/nr_fold;
2353 for(
int j=begin;j<end;j++)
2355 perm[fold_start[i]] = index[j];
2360 for (i=1;i<=nr_fold;i++)
2361 fold_start[i] = fold_start[i-1]+fold_count[i-1];
2370 for(i=0;i<l;i++) perm[i]=i;
2373 int j = i+rand()%(l-i);
2374 std::swap(perm[i],perm[j]);
2376 for(i=0;i<=nr_fold;i++)
2377 fold_start[i]=i*l/nr_fold;
2380 for(i=0;i<nr_fold;i++)
2382 int begin = fold_start[i];
2383 int end = fold_start[i+1];
2385 struct svm_problem subprob;
2387 subprob.l = l-(end-begin);
2388 subprob.x = Malloc(
struct svm_node*,subprob.l);
2389 subprob.y = Malloc(
double,subprob.l);
2392 for(j=0;j<begin;j++)
2394 subprob.x[k] = prob->x[perm[j]];
2395 subprob.y[k] = prob->y[perm[j]];
2400 subprob.x[k] = prob->x[perm[j]];
2401 subprob.y[k] = prob->y[perm[j]];
2404 struct svm_model *submodel = svm_train(&subprob,param);
2405 if(param->probability &&
2406 (param->svm_type == C_SVC || param->svm_type == NU_SVC))
2408 double *prob_estimates=Malloc(
double,svm_get_nr_class(submodel));
2409 for(j=begin;j<end;j++)
2410 target[perm[j]] = svm_predict_probability(submodel,prob->x[perm[j]],prob_estimates);
2411 free(prob_estimates);
2414 for(j=begin;j<end;j++)
2415 target[perm[j]] = svm_predict(submodel,prob->x[perm[j]]);
2416 svm_free_and_destroy_model(&submodel);
2425 int svm_get_svm_type(
const svm_model *model)
2427 return model->param.svm_type;
2430 int svm_get_nr_class(
const svm_model *model)
2432 return model->nr_class;
2435 void svm_get_labels(
const svm_model *model,
int* label)
2437 if (model->label != NULL)
2438 for(
int i=0;i<model->nr_class;i++)
2439 label[i] = model->label[i];
2442 double svm_get_svr_probability(
const svm_model *model)
2444 if ((model->param.svm_type == EPSILON_SVR || model->param.svm_type == NU_SVR) &&
2446 return model->probA[0];
2449 fprintf(stderr,
"Model doesn't contain information for SVR probability inference\n");
2454 double svm_predict_values(
const svm_model *model,
const svm_node *x,
double* dec_values)
2457 if(model->param.svm_type == ONE_CLASS ||
2458 model->param.svm_type == EPSILON_SVR ||
2459 model->param.svm_type == NU_SVR)
2461 double *sv_coef = model->sv_coef[0];
2463 for(i=0;i<model->l;i++)
2464 sum += sv_coef[i] * Kernel::k_function(x,model->SV[i],model->param);
2465 sum -= model->rho[0];
2468 if(model->param.svm_type == ONE_CLASS)
2469 return (sum>0)?1:-1;
2475 int nr_class = model->nr_class;
2478 double *kvalue = Malloc(
double,l);
2480 kvalue[i] = Kernel::k_function(x,model->SV[i],model->param);
2482 int *start = Malloc(
int,nr_class);
2484 for(i=1;i<nr_class;i++)
2485 start[i] = start[i-1]+model->nSV[i-1];
2487 int *vote = Malloc(
int,nr_class);
2488 for(i=0;i<nr_class;i++)
2492 for(i=0;i<nr_class;i++)
2493 for(
int j=i+1;j<nr_class;j++)
2498 int ci = model->nSV[i];
2499 int cj = model->nSV[j];
2502 double *coef1 = model->sv_coef[j-1];
2503 double *coef2 = model->sv_coef[i];
2505 sum += coef1[si+k] * kvalue[si+k];
2507 sum += coef2[sj+k] * kvalue[sj+k];
2508 sum -= model->rho[p];
2509 dec_values[p] = sum;
2511 if(dec_values[p] > 0)
2518 int vote_max_idx = 0;
2519 for(i=1;i<nr_class;i++)
2520 if(vote[i] > vote[vote_max_idx])
2526 return model->label[vote_max_idx];
2530 double svm_predict(
const svm_model *model,
const svm_node *x)
2532 int nr_class = model->nr_class;
2534 if(model->param.svm_type == ONE_CLASS ||
2535 model->param.svm_type == EPSILON_SVR ||
2536 model->param.svm_type == NU_SVR)
2537 dec_values = Malloc(
double, 1);
2539 dec_values = Malloc(
double, nr_class*(nr_class-1)/2);
2540 double pred_result = svm_predict_values(model, x, dec_values);
2545 double svm_predict_probability(
2546 const svm_model *model,
const svm_node *x,
double *prob_estimates)
2548 if ((model->param.svm_type == C_SVC || model->param.svm_type == NU_SVC) &&
2549 model->probA!=NULL && model->probB!=NULL)
2552 int nr_class = model->nr_class;
2553 double *dec_values = Malloc(
double, nr_class*(nr_class-1)/2);
2554 svm_predict_values(model, x, dec_values);
2556 double min_prob=1e-7;
2557 double **pairwise_prob=Malloc(
double *,nr_class);
2558 for(i=0;i<nr_class;i++)
2559 pairwise_prob[i]=Malloc(
double,nr_class);
2561 for(i=0;i<nr_class;i++)
2562 for(
int j=i+1;j<nr_class;j++)
2564 pairwise_prob[i][j]=std::min(std::max(sigmoid_predict(dec_values[k],model->probA[k],model->probB[k]),min_prob),1-min_prob);
2565 pairwise_prob[j][i]=1-pairwise_prob[i][j];
2568 multiclass_probability(nr_class,pairwise_prob,prob_estimates);
2570 int prob_max_idx = 0;
2571 for(i=1;i<nr_class;i++)
2572 if(prob_estimates[i] > prob_estimates[prob_max_idx])
2574 for(i=0;i<nr_class;i++)
2575 free(pairwise_prob[i]);
2577 free(pairwise_prob);
2578 return model->label[prob_max_idx];
2581 return svm_predict(model, x);
2584 static const char *svm_type_table[] =
2586 "c_svc",
"nu_svc",
"one_class",
"epsilon_svr",
"nu_svr",NULL
2589 static const char *kernel_type_table[]=
2591 "linear",
"polynomial",
"rbf",
"sigmoid",
"precomputed",NULL
2594 int svm_save_model(
const char *model_file_name,
const svm_model *model)
2596 FILE *fp = fopen(model_file_name,
"w");
2597 if(fp==NULL)
return -1;
2599 char *old_locale = strdup(setlocale(LC_ALL, NULL));
2600 setlocale(LC_ALL,
"C");
2602 const svm_parameter& param = model->param;
2604 fprintf(fp,
"svm_type %s\n", svm_type_table[param.svm_type]);
2605 fprintf(fp,
"kernel_type %s\n", kernel_type_table[param.kernel_type]);
2607 if(param.kernel_type == POLY)
2608 fprintf(fp,
"degree %d\n", param.degree);
2610 if(param.kernel_type == POLY || param.kernel_type == RBF || param.kernel_type == SIGMOID)
2611 fprintf(fp,
"gamma %g\n", param.gamma);
2613 if(param.kernel_type == POLY || param.kernel_type == SIGMOID)
2614 fprintf(fp,
"coef0 %g\n", param.coef0);
2616 int nr_class = model->nr_class;
2618 fprintf(fp,
"nr_class %d\n", nr_class);
2619 fprintf(fp,
"total_sv %d\n",l);
2623 for(
int i=0;i<nr_class*(nr_class-1)/2;i++)
2624 fprintf(fp,
" %g",model->rho[i]);
2630 fprintf(fp,
"label");
2631 for(
int i=0;i<nr_class;i++)
2632 fprintf(fp,
" %d",model->label[i]);
2638 fprintf(fp,
"probA");
2639 for(
int i=0;i<nr_class*(nr_class-1)/2;i++)
2640 fprintf(fp,
" %g",model->probA[i]);
2645 fprintf(fp,
"probB");
2646 for(
int i=0;i<nr_class*(nr_class-1)/2;i++)
2647 fprintf(fp,
" %g",model->probB[i]);
2653 fprintf(fp,
"nr_sv");
2654 for(
int i=0;i<nr_class;i++)
2655 fprintf(fp,
" %d",model->nSV[i]);
2659 fprintf(fp,
"SV\n");
2660 const double *
const *sv_coef = model->sv_coef;
2661 const svm_node *
const *SV = model->SV;
2663 for(
int i=0;i<l;i++)
2665 for(
int j=0;j<nr_class-1;j++)
2666 fprintf(fp,
"%.16g ",sv_coef[j][i]);
2668 const svm_node *p = SV[i];
2670 if(param.kernel_type == PRECOMPUTED)
2671 fprintf(fp,
"0:%d ",(
int)(p->value));
2673 while(p->index != -1)
2675 fprintf(fp,
"%d:%.8g ",p->index,p->value);
2681 setlocale(LC_ALL, old_locale);
2684 if (ferror(fp) != 0 || fclose(fp) != 0)
return -1;
2688 static char *line = NULL;
2689 static int max_line_len;
2691 static char* readline(FILE *input)
2695 if(fgets(line,max_line_len,input) == NULL)
2698 while(strrchr(line,
'\n') == NULL)
2701 line = (
char *) realloc(line,max_line_len);
2702 len = (int) strlen(line);
2703 if(fgets(line+len,max_line_len-len,input) == NULL)
2709 svm_model *svm_load_model(
const char *model_file_name)
2711 FILE *fp = fopen(model_file_name,
"rb");
2712 if(fp==NULL)
return NULL;
2714 char *old_locale = strdup(setlocale(LC_ALL, NULL));
2715 setlocale(LC_ALL,
"C");
2719 svm_model *model = Malloc(svm_model,1);
2720 svm_parameter& param = model->param;
2722 model->probA = NULL;
2723 model->probB = NULL;
2724 model->label = NULL;
2728 for(
unsigned int i=0; i<81; i++) cmd[i] =
'\0';
2731 fscanf(fp,
"%80s",cmd);
2733 if(strcmp(cmd,
"svm_type")==0)
2735 fscanf(fp,
"%80s",cmd);
2737 for(i=0;svm_type_table[i];i++)
2739 if(strcmp(svm_type_table[i],cmd)==0)
2745 if(svm_type_table[i] == NULL)
2747 fprintf(stderr,
"unknown svm type.\n");
2749 setlocale(LC_ALL, old_locale);
2758 else if(strcmp(cmd,
"kernel_type")==0)
2760 fscanf(fp,
"%80s",cmd);
2762 for(i=0;kernel_type_table[i];i++)
2764 if(strcmp(kernel_type_table[i],cmd)==0)
2766 param.kernel_type=i;
2770 if(kernel_type_table[i] == NULL)
2772 fprintf(stderr,
"unknown kernel function.\n");
2774 setlocale(LC_ALL, old_locale);
2783 else if(strcmp(cmd,
"degree")==0)
2784 fscanf(fp,
"%d",¶m.degree);
2785 else if(strcmp(cmd,
"gamma")==0)
2786 fscanf(fp,
"%lf",¶m.gamma);
2787 else if(strcmp(cmd,
"coef0")==0)
2788 fscanf(fp,
"%lf",¶m.coef0);
2789 else if(strcmp(cmd,
"nr_class")==0)
2790 fscanf(fp,
"%d",&model->nr_class);
2791 else if(strcmp(cmd,
"total_sv")==0)
2792 fscanf(fp,
"%d",&model->l);
2793 else if(strcmp(cmd,
"rho")==0)
2795 int n = model->nr_class * (model->nr_class-1)/2;
2796 model->rho = Malloc(
double,n);
2797 for(
int i=0;i<n;i++)
2798 fscanf(fp,
"%lf",&model->rho[i]);
2800 else if(strcmp(cmd,
"label")==0)
2802 int n = model->nr_class;
2803 model->label = Malloc(
int,n);
2804 for(
int i=0;i<n;i++)
2805 fscanf(fp,
"%d",&model->label[i]);
2807 else if(strcmp(cmd,
"probA")==0)
2809 int n = model->nr_class * (model->nr_class-1)/2;
2810 model->probA = Malloc(
double,n);
2811 for(
int i=0;i<n;i++)
2812 fscanf(fp,
"%lf",&model->probA[i]);
2814 else if(strcmp(cmd,
"probB")==0)
2816 int n = model->nr_class * (model->nr_class-1)/2;
2817 model->probB = Malloc(
double,n);
2818 for(
int i=0;i<n;i++)
2819 fscanf(fp,
"%lf",&model->probB[i]);
2821 else if(strcmp(cmd,
"nr_sv")==0)
2823 int n = model->nr_class;
2824 model->nSV = Malloc(
int,n);
2825 for(
int i=0;i<n;i++)
2826 fscanf(fp,
"%d",&model->nSV[i]);
2828 else if(strcmp(cmd,
"SV")==0)
2833 if(c==EOF || c==
'\n')
break;
2839 fprintf(stderr,
"unknown text in model file: [%s]\n",cmd);
2841 setlocale(LC_ALL, old_locale);
2854 long pos = ftell(fp);
2856 max_line_len = 1024;
2857 line = Malloc(
char,max_line_len);
2858 char *p,*endptr,*idx,*val;
2860 while(readline(fp)!=NULL)
2862 p = strtok(line,
":");
2865 p = strtok(NULL,
":");
2871 elements += model->l;
2873 fseek(fp,pos,SEEK_SET);
2875 int m = model->nr_class - 1;
2877 model->sv_coef = Malloc(
double *,m);
2880 model->sv_coef[i] = Malloc(
double,l);
2881 model->SV = Malloc(svm_node*,l);
2882 svm_node *x_space = NULL;
2883 if(l>0) x_space = Malloc(svm_node,elements);
2889 model->SV[i] = &x_space[j];
2891 p = strtok(line,
" \t");
2892 model->sv_coef[0][i] = strtod(p,&endptr);
2893 for(
int k=1;k<m;k++)
2895 p = strtok(NULL,
" \t");
2896 model->sv_coef[k][i] = strtod(p,&endptr);
2901 idx = strtok(NULL,
":");
2902 val = strtok(NULL,
" \t");
2906 x_space[j].index = (int) strtol(idx,&endptr,10);
2907 x_space[j].value = strtod(val,&endptr);
2911 x_space[j++].index = -1;
2915 setlocale(LC_ALL, old_locale);
2918 if (ferror(fp) != 0 || fclose(fp) != 0)
2925 void svm_free_model_content(svm_model* model_ptr)
2927 if(model_ptr->free_sv && model_ptr->l > 0 && model_ptr->SV != NULL)
2928 free((
void *)(model_ptr->SV[0]));
2929 if(model_ptr->sv_coef)
2931 for(
int i=0;i<model_ptr->nr_class-1;i++)
2932 free(model_ptr->sv_coef[i]);
2935 free(model_ptr->SV);
2936 model_ptr->SV = NULL;
2938 free(model_ptr->sv_coef);
2939 model_ptr->sv_coef = NULL;
2941 free(model_ptr->rho);
2942 model_ptr->rho = NULL;
2944 free(model_ptr->label);
2945 model_ptr->label= NULL;
2947 free(model_ptr->probA);
2948 model_ptr->probA = NULL;
2950 free(model_ptr->probB);
2951 model_ptr->probB= NULL;
2953 free(model_ptr->nSV);
2954 model_ptr->nSV = NULL;
2957 void svm_free_and_destroy_model(svm_model** model_ptr_ptr)
2959 if(model_ptr_ptr != NULL && *model_ptr_ptr != NULL)
2961 svm_free_model_content(*model_ptr_ptr);
2962 free(*model_ptr_ptr);
2963 *model_ptr_ptr = NULL;
2967 void svm_destroy_param(svm_parameter* param)
2969 free(param->weight_label);
2970 free(param->weight);
2973 const char *svm_check_parameter(
const svm_problem *prob,
const svm_parameter *param)
2976 int svm_type = param->svm_type;
2977 if(svm_type != C_SVC &&
2978 svm_type != NU_SVC &&
2979 svm_type != ONE_CLASS &&
2980 svm_type != EPSILON_SVR &&
2982 return "unknown svm type";
2985 int kernel_type = param->kernel_type;
2986 if(kernel_type != LINEAR &&
2987 kernel_type != POLY &&
2988 kernel_type != RBF &&
2989 kernel_type != SIGMOID &&
2990 kernel_type != PRECOMPUTED)
2991 return "unknown kernel type";
2993 if(param->gamma < 0)
2996 if(param->degree < 0)
2997 return "degree of polynomial kernel < 0";
3001 if(param->cache_size <= 0)
3002 return "cache_size <= 0";
3007 if(svm_type == C_SVC ||
3008 svm_type == EPSILON_SVR ||
3013 if(svm_type == NU_SVC ||
3014 svm_type == ONE_CLASS ||
3016 if(param->nu <= 0 || param->nu > 1)
3017 return "nu <= 0 or nu > 1";
3019 if(svm_type == EPSILON_SVR)
3023 if(param->shrinking != 0 &&
3024 param->shrinking != 1)
3025 return "shrinking != 0 and shrinking != 1";
3027 if(param->probability != 0 &&
3028 param->probability != 1)
3029 return "probability != 0 and probability != 1";
3031 if(param->probability == 1 &&
3032 svm_type == ONE_CLASS)
3033 return "one-class SVM probability output not supported yet";
3037 if(svm_type == NU_SVC)
3040 int max_nr_class = 16;
3042 int *label = Malloc(
int,max_nr_class);
3043 int *count = Malloc(
int,max_nr_class);
3048 int this_label = (int)prob->y[i];
3050 for(j=0;j<nr_class;j++)
3051 if(this_label == label[j])
3058 if(nr_class == max_nr_class)
3061 label = (
int *)realloc(label,max_nr_class*
sizeof(
int));
3062 count = (
int *)realloc(count,max_nr_class*
sizeof(
int));
3064 label[nr_class] = this_label;
3065 count[nr_class] = 1;
3070 for(i=0;i<nr_class;i++)
3073 for(
int j=i+1;j<nr_class;j++)
3076 if(param->nu*(n1+n2)/2 > std::min(n1,n2))
3080 return "specified nu is infeasible";
3091 int svm_check_probability_model(
const svm_model *model)
3093 return ((model->param.svm_type == C_SVC || model->param.svm_type == NU_SVC) &&
3094 model->probA!=NULL && model->probB!=NULL) ||
3095 ((model->param.svm_type == EPSILON_SVR || model->param.svm_type == NU_SVR) &&
3096 model->probA!=NULL);
3099 void svm_set_print_string_function(
void (*print_func)(
const char *))
3101 if(print_func == NULL)
3102 svm_print_string = &print_string_stdout;
3104 svm_print_string = print_func;