1 #include "PredictorWrapper.h"
8 namespace py = boost::python;
11 using namespace suanzi;
14 const static std::string TAG = "PredictorWrapper";
17 boost::python::list toPythonList(const std::vector<T>& v) {
18 typename std::vector<T>::iterator iter;
19 boost::python::list list;
20 for(const auto& vv : v){
26 #define CALL_WITH_EXCEPTION(expr, ret_val) \
28 py::object py_ret = expr; \
29 ret_val = py::extract<decltype(ret_val)>(py_ret); \
30 }catch(boost::python::error_already_set const &){ \
31 LOG_ERROR(TAG, PyWrapper::parse_python_exception()); \
35 PredictorWrapper::PredictorWrapper(const string& module, const string& pydir)
37 PyWrapperPtr interpreter = PyWrapper::getInstance(pydir);
39 m_module = interpreter->import(module);
40 } catch (boost::python::error_already_set const &){
41 LOG_ERROR(TAG, PyWrapper::parse_python_exception());
45 bool PredictorWrapper::load(const string& fname)
47 LOG_DEBUG(TAG, "load " + fname);
48 py::object func = m_module.attr("init");
50 CALL_WITH_EXCEPTION(func(fname.c_str()), ret);
54 void PredictorWrapper::dump()
56 LOG_DEBUG(TAG, "dump");
57 py::object func = m_module.attr("dump");
59 CALL_WITH_EXCEPTION(func(), ret);
63 double PredictorWrapper::predict(int index, const vector<double>& features)
65 py::object func = m_module.attr("predict");
67 CALL_WITH_EXCEPTION(func(index, toPythonList(features)), rr);