svm.cpp 85 KB

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