Created
October 6, 2014 18:22
-
-
Save smartkiwi/9a9da49446badd6d87e1 to your computer and use it in GitHub Desktop.
vw cffi example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from cffi import FFI | |
# create ffi wrapper object | |
ffi = FFI() | |
ffi.cdef(''' | |
void* VW_InitializeA(char *); | |
void* VW_ReadExampleA(void*, char*); | |
float VW_Learn(void*, void*); | |
void VW_FinishExample(void*, void*); | |
void VW_Finish(void*); | |
''') | |
ffilib = ffi.verify(''' | |
typedef short char16_t; | |
#define bool int | |
#define true (1) | |
#define false (0) | |
#include "vwdll.h" | |
''', | |
include_dirs=['/usr/local/include/vowpalwabbit', './vw_cffi', '/usr/include', '.'], | |
library_dirs=['/usr/lib', '/usr/lib64'], | |
libraries=['vw_c_wrapper', "vw", "allreduce"], | |
ext_package='vw' | |
) | |
class VWModel(object): | |
def __init__(self, params_str): | |
self._vw = ffilib.VW_InitializeA(params_str) | |
if not self._vw: | |
raise VWModelError("VW Model failed to init") | |
def getScore(self, example_str): | |
example = ffilib.VW_ReadExampleA(self._vw, example_str) | |
score = ffilib.VW_Learn(self._vw, example) | |
ffilib.VW_FinishExample(self._vw, example) | |
return score | |
def close(self): | |
if self._vw: | |
ffilib.VW_Finish(self._vw) | |
self._vw = None | |
def __del__(self): | |
self.close() | |
if __name__ == "__main__": | |
vw_model = VWModel("-b29 -t -i %s -q pm -q po -q pw -q pf -q ps --quiet" % "./magnetic_ctr_prediction_vw_incremental_build.vw") | |
score = vw_model.getScore("| w Chrome 31.0.1650 |c 909 |a 22-05 |y USA |b 6941 |z 728x90 |e n |f 0 |k |m n-1357 |o Windows Vista |p youtube.com |r OH |s 3287 ") | |
print score | |
vw_model.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment