svm.cpp 67 KB

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