pysvmlight / svmlight / svmlight.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
from ctypes import *

import localdata

VERSION = "V6.02"
VERSION_DATE = "14.08.08"

CFLOAT = c_float
FNUM   = c_long
FVAL   = c_float

MAXFEATNUM = 99999999

LINEAR  = 0
POLY    = 1
RBF     = 2
SIGMOID = 3

CLASSIFICATION = 1
REGRESSION     = 2
RANKING        = 3
OPTIMIZATION   = 4

MAXSHRINK = 50000
svm = CDLL("./svmlight.so")


class WORD(Structure):
    _fields_ = [("wnum",   FNUM),
                ("weight", FVAL)]
# ----------------------------------------------

class SVECTOR(Structure):
    pass

SVECTOR._fields_ = [("words",       POINTER(WORD)),
                    ("twonorm_sq",  c_double),
                    ("userdefined", POINTER(c_char)),
                    ("kernel_id",   c_long),
                    ("next",        POINTER(SVECTOR)),
                    ("factor",      c_double)]
# ----------------------------------------------

class DOC(Structure):
    _fields_ = [("docnum",     c_long),
                ("queryid",    c_long),
                ("costfactor", c_double),
                ("slackid",    c_long),
                ("fvec",       POINTER(SVECTOR))]
# ----------------------------------------------

class LEARN_PARM(Structure):
    _fields_ = [("type",                  c_long),
                ("svm_c",                 c_double),
                ("eps",                   c_double),
                ("svm_costratio",         c_double),
                ("transduction_posratio", c_double),
                ("biased_hyperplane",     c_long),
                ("sharedslack",           c_long),
                ("svm_maxqpsize",         c_long),
                ("svm_newvarsinqp",       c_long),
                ("kernel_cache_size",     c_long),
                ("epsilon_crit",          c_double),
                ("epsilon_shrink",        c_double),
                ("svm_iter_to_shrink",    c_long),
                ("maxiter",               c_long),
                ("remove_inconsistent",   c_long),
                ("skip_final_opt_check",  c_long),
                ("compute_loo",           c_long),
                ("rho",                   c_double),
                ("xa_depth",              c_long),
                ("predfile",              (c_char * 200)),
                ("alphafile",             (c_char * 200)),
                ("epsilon_const",         c_double),
                ("epsilon_a",             c_double),
                ("opt_precision",         c_double),
                ("svm_c_steps",           c_long),
                ("svm_c_factor",          c_double),
                ("svm_costratio_unlab",   c_double),
                ("svm_unlabbound",        c_double),
                ("svm_cost",              POINTER(c_double)),
                ("totwords",              c_long)]
# ----------------------------------------------

class KERNEL_PARM(Structure):
    _fields_ = [("kernel_type",     c_long),
                ("poly_degree",     c_long),
                ("rbf_gamma",       c_double),
                ("coef_lin",        c_double),
                ("coef_const",      c_double),
                ("custom",          (c_char * 50))]
# ----------------------------------------------

class MODEL(Structure):
    _fields_ = [("sv_num",          c_long),
                ("at_upper_bound",  c_long),
                ("b",               c_double),
                ("supvec",          POINTER(POINTER(DOC))),
                ("alpha",           POINTER(c_double)),
                ("index",           POINTER(c_long)),
                ("totwords",        c_long),
                ("totdoc",          c_long),
                ("kernel_parm",     KERNEL_PARM),
                ("loo_error",       c_double),
                ("loo_recall",      c_double),
                ("loo_precision",   c_double),
                ("xa_error",        c_double),
                ("xa_recall",       c_double),
                ("xa_precision",    c_double),
                ("lin_weights",     POINTER(c_double)),
                ("maxdiff",         c_double)]
# ----------------------------------------------

class QP(Structure):
    _fields_ = [("opt_n",     c_long),
                ("opt_m",     c_long),
                ("opt_ce",    POINTER(c_double)),
                ("opt_ce0",   POINTER(c_double)),
                ("opt_g",     POINTER(c_double)),
                ("opt_g0",    POINTER(c_double)),
                ("opt_xinit", POINTER(c_double)),
                ("opt_low",   POINTER(c_double)),
                ("opt_up",    POINTER(c_double))]
# ----------------------------------------------

class KERNEL_CACHE(Structure):
  _fields_ = [("index",         POINTER(c_long)),
              ("buffer",        POINTER(CFLOAT)),
              ("invindex",      POINTER(c_long)),
              ("active2totdoc", POINTER(c_long)),
              ("totdoc2active", POINTER(c_long)),
              ("lru",           POINTER(c_long)),
              ("occu",          POINTER(c_long)),
              ("elems",         c_long),
              ("max_elems",     c_long),
              ("time",          c_long),
              ("activenum",     c_long),
              ("buffsize",      c_long)]
# ----------------------------------------------

class TIMING(Structure):
    _fields_ = [("time_kernel",     c_long),
                ("time_opti",       c_long),
                ("time_shrink",     c_long),
                ("time_update",     c_long),
                ("time_model",      c_long),
                ("time_check",      c_long),
                ("time_select",     c_long)]
# ----------------------------------------------

class SHRINK_STATE(Structure):
    _fields_ = [("active",          POINTER(c_long)),
                ("inactive_since",  POINTER(c_long)),
                ("deactnum",        c_long),
                ("a_history",       POINTER(POINTER(c_double))),
                ("maxhistory",      c_long),
                ("last_a",          POINTER(c_double)),
                ("last_lin",        POINTER(c_double))]
# ----------------------------------------------

''' This auxiliary function to svm_learn reads some parameters from the keywords to
 * the function and fills the rest in with defaults (from read_input_parameters()
 * in svm_learn_main.c:109).
 
 returns an int
'''

def read_learning_parameters( client_data, **kwds):
    
    verbosity = client_data.pverb
    learn_parm = client_data.plearn
    kernel_parm = client_data.kparm

    learn_parm.predfile = "trans_predictions"
    learn_parm.alphafile = ""
    verbosity = 0
    learn_parm.biased_hyperplane = 1
    learn_parm.sharedslack = 0
    learn_parm.remove_inconsistent = 0
    learn_parm.skip_final_opt_check = 0
    learn_parm.svm_maxqpsize = 10
    learn_parm.svm_newvarsinqp = 0
    learn_parm.svm_iter_to_shrink = -9999
    learn_parm.maxiter = 100000
    learn_parm.kernel_cache_size = 40
    learn_parm.svm_c = 0.0
    learn_parm.eps = 0.1
    learn_parm.transduction_posratio = -1.0
    learn_parm.svm_costratio = 1.0
    learn_parm.svm_costratio_unlab = 1.0
    learn_parm.svm_unlabbound = 1E-5
    learn_parm.epsilon_crit = 0.001
    learn_parm.epsilon_a = 1E-15
    learn_parm.compute_loo = 0
    learn_parm.rho = 1.0
    learn_parm.xa_depth = 0
    kernel_parm.kernel_type = 0
    kernel_parm.poly_degree = 3
    kernel_parm.rbf_gamma = 1.0
    kernel_parm.coef_lin = 1
    kernel_parm.coef_const = 1
    kernel_parm.custom = "empty"
    learn_parm.type = CLASSIFICATION

    if "type" in kwds:
        typ = kwds["type"]
        if typ == "classification":
            learn_parm.type = CLASSIFICATION
        elif typ == "regression":
            learn_parm.type = REGRESSION
        elif typ == "ranking":
            learn_parm.type = RANKING
        elif typ == "optimization":
            learn_parm.type = OPTIMIZATION
        else:
            raise Exception("unknown learning type specified. Valid types are: 'classification', 'regression', 'ranking' and 'optimization'.")

    print 'Type:'
    print learn_parm.type

    if "kernel" in kwds:
        kernel = kwds["kernel"]
        if kernel == "linear":
            kernel_parm.kernel_type = LINEAR
        elif kernel == "polynomial":
            kernel_parm.kernel_type = POLY
        elif kernel == "rbf":
            kernel_parm.kernel_type = RBF
        elif kernel == "sigmoid":
            kernel_parm.kernel_type = SIGMOID
        else:
            raise Exception("unknown kernel type specified. Valid types are: 'linear', 'polynomial', 'rbf' and 'sigmoid'.")

    if "verbosity" in kwds:
        verbosity = kwds["verbosity"]

    if "C" in kwds:
        learn_parm.svm_c = kwds["C"]

    if "poly_degree" in kwds:
        kernel_parm.poly_degree = kwds["poly_degree"]

    if "rbf_gamma" in kwds:
        kernel_parm.rbf_gamma = kwds["rbf_gamma"]
   
    if "coef_lin" in kwds:
        kernel_parm.coef_lin = kwds["coef_lin"]

    if "coef_const" in kwds:
        kernel_parm.coef_const = kwds["coef_const"]
    
    if learn_parm.svm_iter_to_shrink == -9999:
        if kernel_parm.kernel_type == LINEAR:
            learn_parm.svm_iter_to_shrink = 2
        else:
            learn_parm.svm_iter_to_shrink = 100

    return 1
# ----------------------------------------------

def count_doclist( doclist ):
    max_docs = len( doclist )
    max_words = 0
    for doctuple in iter( doclist ):
        words_list = doctuple[1]
        list_length = len( words_list )
        if list_length > max_words:
            max_words = list_length

    return ( max_docs, max_words )
# ----------------------------------------------

'''
class UnpackData:
    def __init__(self):
        self.doc_label = 0.0
        self.queryid = 0
        self.slackid = 0
        self.costfactor = 0.0
        self.wpos = 0
'''

UnpackData = namedtuple('Unpackdata', 'words doc_label queryid slackid costfactor numwords')

WordTuple = namedtuple('WordTuple', 'wnum weight' )

'''
class UnpackDocument(Structure):
    _fields_ = [("docobj",),
                ("words",)
                ("label",)
                ("queryid",)
                ("slackid",)
                ("costfactor",)
                ("numwords",)'''


def unpack_document(docobj, numwords, max_words_doc):

    # We initialize these parameters with their default values, since we won't
    # be reading them from the feature pairs (don't really care).
    queryid = 0
    slackid = 0
    costfactor = 1

    if type(docobj) != tuple:
        raise Exception("document should be a tuple")

    label     = docobj[0]
    words_list = docobj[1]
    if len( docobj ) > 2:
        queryid = docobj[2]

    if type(words_list) != list:
        raise Exception("expected list of feature pairs")

    for feature_pair in words_list:
        if len( words ) >= max_words_doc:
            break 
    words.append( WordTuple( feature_pair[0], feature_pair[1] ) )

    returnval = Unpackdata( words, doc_label, queryid, slackid, costfactor )
    return returnval

class DOCLISTDATA(Structure):
    _fields_ = [("docs", POINTER(DOC)),
            ("totwords",  c_int),
            ("totdoc",  c_int)]

# ----------------------------------------------

def unpack_doclist( doclist, doclistdata ):
    
    try:
    doc_iterator = iter(doclist)
    except TypeError, te:
    raise Exception("Not iterable")

     (max_docs, max_words) = count_doclist( doclist )

     templist = []
     totwords = 0
     for item in doc_iterator:
         unpackdata = unpack_document( item, max_words )
         numwords = len( unpackdata.words )
         if numwords > 0:
             candidatewords = unpackdata.words[-1].wnum
             if candidatewords > totwords:
                 totwords = candidatewords

         docnum = unpackdata.doc_label
         
         newdoc = DOC()
         newdoc.docnum = docnum
         newdoc.queryid = unpackdata.queryid
         newdoc.costfactor = unpackdata.costfactor
         newdoc.slackid = unpackdata.slackid
         newdoc.fvec = create_svector( unpackdata.words, "", 1.0 )
         templist.append( newdoc )

     totdoc = len( doclist )

     carray = ( DOC * totdoc )()
     counter = 0
     for item in iter( templist ):
         carray[ counter ] = item
         counter += 1

     result = DOCLISTDATA()

     result.docs = pointer( carray )
     result.totwords = totwords
     result.totdoc = totdoc
     
     return result
# ----------------------------------------------

def generate_C_string_from_python( pythonstring ):
    cstring = ( c_char * len( pythonstring ) )()
    cstring[:] = pythonstring
    return cstring
# ----------------------------------------------

def create_fixed_size_words( words ):
    result = (WORD * len( words ))()
    index = 0
    for item in words:
        result[ index ].wnum = item.wnum
        result[ index ].weight = item.weight
        index += 1

    return result
         
# ----------------------------------------------         

def create_svector( words, userdefined, factor ):
    result = SVECTOR()
    cwords = create_fixed_size_words( words )
    result.words = pointer( cwords )
    svm.sprod_ss( result, result )

    result.userdefined = generate_C_string_from_python( userdefined )
    result.factor = factor
    result.kernel_id = 0
    result.next = 0
    
    return result
# ----------------------------------------------

'''
DOC *create_example(long docnum, long queryid, long slackid, 

            double costfactor, SVECTOR *fvec)

{

  DOC *example;
  example = (DOC *)my_malloc(sizeof(DOC));
  example->docnum=docnum;
  example->queryid=queryid;
  example->slackid=slackid;
  example->costfactor=costfactor;
  example->fvec=fvec;

  return(example);

}
'''
# ----------------------------------------------

def print_client_data( client_data ):
    verbosity = client_data.pverb
    learn_parm = client_data.plearn
    kernel_parm = client_data.kparm

    print 'Kernel:'
    print kernel_parm.kernel_type
    print 'Verbosity:'
    print verbosity
    print 'C:'
    print learn_parm.svm_c
    print 'poly_degree:'
    print kernel_parm.poly_degree
    print 'rbf_gamma:'
    print kernel_parm.rbf_gamma
    print 'coef_lin:'
    print kernel_parm.coef_lin
    print 'coef_const:'
    print kernel_parm.coef_const
# ----------------------------------------------

class CLIENTDATA(Structure):
    _fields_ = [("pverb",  c_long),
            ("plearn", LEARN_PARM),
            ("kparm",  KERNEL_PARM)]
# ----------------------------------------------

def svm_learn2(*args, **kwds):
    

    client_data = CLIENTDATA()

    #if(!PyArg_ParseTuple(args, "O", &doclist))
    #    return NULL;
    read_learning_parameters( client_data, **kwds )

    print_client_data( client_data )
    #if(!unpack_doclist(doclist, &docs, &target, &totwords, &totdoc))
    #    return NULL;

    # return (learn_parm, kernal_parm)
# ----------------------------------------------


# -------------------- MAIN --------------------
if __name__ == "__main__":
    result = svm_learn2( localdata.train0, type='classification' )
    print result
# ----------------------------------------------

'''

static PyObject *svm_learn(PyObject *self, PyObject *args, PyObject *kwds)
{
    #DOC **docs;
    double* target;
    int totwords, totdoc;
    KERNEL_CACHE *kernel_cache;
    LEARN_PARM learn_parm;
    KERNEL_PARM kernel_parm;
    long verbosity;
    PyObject *doclist;
    MODEL *model;
    MODEL_AND_DOCS *result;

    if(!PyArg_ParseTuple(args, "O", &doclist))
        return NULL;
    read_learning_parameters(kwds, &verbosity, &learn_parm, &kernel_parm);
    if(!unpack_doclist(doclist, &docs, &target, &totwords, &totdoc))
        return NULL;

    model = malloc(sizeof(MODEL));
    if(kernel_parm.kernel_type == LINEAR)
        kernel_cache = NULL;
    else
        kernel_cache = kernel_cache_init(totdoc, learn_parm.kernel_cache_size);

    # DO THIS ONE!
    if(learn_parm.type == CLASSIFICATION) {
        svm_learn_classification(docs, target, totdoc, totwords, &learn_parm,
                                 &kernel_parm, kernel_cache, model, NULL /* alpha_in */);
    }
    else if(learn_parm.type == REGRESSION) {
        svm_learn_regression(docs, target, totdoc, totwords, &learn_parm,
                             &kernel_parm, &kernel_cache, model);
    }
    else if(learn_parm.type == RANKING) {
        svm_learn_ranking(docs, target, totdoc, totwords, &learn_parm,
                          &kernel_parm, &kernel_cache, model);
    }
    else if(learn_parm.type == OPTIMIZATION) {
        svm_learn_optimization(docs, target, totdoc, totwords, &learn_parm,
                               &kernel_parm, kernel_cache, model, NULL /* alpha_in */);
    }
'''
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.