You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

svm.cpp 65 kB

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

A Python package for graph kernels, graph edit distances and graph pre-image problem.