SHOGUN  3.2.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
LibSVMOneClass.cpp
Go to the documentation of this file.
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 3 of the License, or
5  * (at your option) any later version.
6  *
7  * Written (W) 2006 Christian Gehl
8  * Written (W) 2006-2009 Soeren Sonnenburg
9  * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society
10  */
11 
13 #include <shogun/io/SGIO.h>
14 
15 using namespace shogun;
16 
18 : CSVM(), model(NULL)
19 {
20 }
21 
23 : CSVM(C, k, NULL), model(NULL)
24 {
25 }
26 
28 {
29  SG_FREE(model);
30 }
31 
33 {
34  ASSERT(kernel)
35  if (data)
36  kernel->init(data, data);
37 
39 
40  struct svm_node* x_space;
41  SG_INFO("%d train data points\n", problem.l)
42 
43  problem.y=NULL;
44  problem.x=SG_MALLOC(struct svm_node*, problem.l);
45  x_space=SG_MALLOC(struct svm_node, 2*problem.l);
46 
47  for (int32_t i=0; i<problem.l; i++)
48  {
49  problem.x[i]=&x_space[2*i];
50  x_space[2*i].index=i;
51  x_space[2*i+1].index=-1;
52  }
53 
54  int32_t weights_label[2]={-1,+1};
55  float64_t weights[2]={1.0,get_C2()/get_C1()};
56 
57  param.svm_type=ONE_CLASS; // C SVM
58  param.kernel_type = LINEAR;
59  param.degree = 3;
60  param.gamma = 0; // 1/k
61  param.coef0 = 0;
62  param.nu = get_nu();
63  param.kernel=kernel;
64  param.cache_size = kernel->get_cache_size();
65  param.max_train_time = m_max_train_time;
66  param.C = get_C1();
67  param.eps = epsilon;
68  param.p = 0.1;
69  param.shrinking = 1;
70  param.nr_weight = 2;
71  param.weight_label = weights_label;
72  param.weight = weights;
73  param.use_bias = get_bias_enabled();
74 
75  const char* error_msg = svm_check_parameter(&problem,&param);
76 
77  if(error_msg)
78  SG_ERROR("Error: %s\n",error_msg)
79 
80  model = svm_train(&problem, &param);
81 
82  if (model)
83  {
84  ASSERT(model->nr_class==2)
85  ASSERT((model->l==0) || (model->l>0 && model->SV && model->sv_coef && model->sv_coef[0]))
86 
87  int32_t num_sv=model->l;
88 
89  create_new_model(num_sv);
90  CSVM::set_objective(model->objective);
91 
92  set_bias(-model->rho[0]);
93  for (int32_t i=0; i<num_sv; i++)
94  {
95  set_support_vector(i, (model->SV[i])->index);
96  set_alpha(i, model->sv_coef[0][i]);
97  }
98 
99  SG_FREE(problem.x);
100  SG_FREE(x_space);
101  svm_destroy_model(model);
102  model=NULL;
103 
104  return true;
105  }
106  else
107  return false;
108 }

SHOGUN Machine Learning Toolbox - Documentation