"tests/git@developer.sourcefind.cn:OpenDAS/dgl.git" did not exist on "80de340d861d1f23eade25da4f6ce73393e55b47"
decision_functions.cpp 13 KB
Newer Older
1
2
// Copyright (C) 2013  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
3

Davis King's avatar
Davis King committed
4
#include "opaque_types.h"
5
#include <dlib/python.h>
6
#include "testing_results.h"
7
8
9
10
11
#include <dlib/svm.h>

using namespace dlib;
using namespace std;

12
namespace py = pybind11;
13

14
15
typedef matrix<double,0,1> sample_type;
typedef std::vector<std::pair<unsigned long,double> > sparse_vect;
16
17
18
19
20
21
22

template <typename decision_function>
double predict (
    const decision_function& df,
    const typename decision_function::kernel_type::sample_type& samp
)
{
23
    typedef typename decision_function::kernel_type::sample_type T;
24
25
26
27
    if (df.basis_vectors.size() == 0)
    {
        return 0;
    }
28
    else if (is_matrix<T>::value && df.basis_vectors(0).size() != samp.size())
29
30
    {
        std::ostringstream sout;
Davis King's avatar
Davis King committed
31
32
        sout << "Input vector should have " << df.basis_vectors(0).size() 
             << " dimensions, not " << samp.size() << ".";
33
34
        PyErr_SetString( PyExc_ValueError, sout.str().c_str() );
        throw py::error_already_set();
35
36
37
38
39
40
    }
    return df(samp);
}

template <typename kernel_type>
void add_df (
41
    py::module& m,
42
43
44
45
    const std::string name
)
{
    typedef decision_function<kernel_type> df_type;
46
    py::class_<df_type>(m, name.c_str())
47
        .def("__call__", &predict<df_type>)
48
49
50
51
52
53
54
55
56
        .def_property_readonly("alpha", [](const df_type& df) {return df.alpha;})
        .def_property_readonly("b", [](const df_type& df) {return df.b;})
        .def_property_readonly("kernel_function", [](const df_type& df) {return df.kernel_function;})
        .def_property_readonly("basis_vectors", [](const df_type& df) {
            std::vector<matrix<double,0,1>> temp;
            for (long i = 0; i < df.basis_vectors.size(); ++i)
                temp.push_back(sparse_to_dense(df.basis_vectors(i)));
            return temp;
        })
57
        .def(py::pickle(&getstate<df_type>, &setstate<df_type>));
58
59
}

Davis King's avatar
Davis King committed
60
61
62
63
64
65
66
template <typename df_type>
typename df_type::sample_type get_weights(
    const df_type& df
)
{
    if (df.basis_vectors.size() == 0)
    {
67
68
        PyErr_SetString( PyExc_ValueError, "Decision function is empty." );
        throw py::error_already_set();
Davis King's avatar
Davis King committed
69
70
71
72
73
74
75
76
77
78
79
80
    }
    df_type temp = simplify_linear_decision_function(df);
    return temp.basis_vectors(0);
}

template <typename df_type>
typename df_type::scalar_type get_bias(
    const df_type& df
)
{
    if (df.basis_vectors.size() == 0)
    {
81
82
        PyErr_SetString( PyExc_ValueError, "Decision function is empty." );
        throw py::error_already_set();
Davis King's avatar
Davis King committed
83
84
85
86
    }
    return df.b;
}

87
88
89
90
91
92
93
94
template <typename df_type>
void set_bias(
    df_type& df,
    double b
)
{
    if (df.basis_vectors.size() == 0)
    {
95
96
        PyErr_SetString( PyExc_ValueError, "Decision function is empty." );
        throw py::error_already_set();
97
98
99
100
    }
    df.b = b;
}

Davis King's avatar
Davis King committed
101
102
template <typename kernel_type>
void add_linear_df (
103
    py::module &m,
Davis King's avatar
Davis King committed
104
105
106
107
    const std::string name
)
{
    typedef decision_function<kernel_type> df_type;
108
    py::class_<df_type>(m, name.c_str())
109
        .def("__call__", predict<df_type>)
110
111
112
        .def_property_readonly("weights", &get_weights<df_type>)
        .def_property("bias", get_bias<df_type>, set_bias<df_type>)
        .def(py::pickle(&getstate<df_type>, &setstate<df_type>));
Davis King's avatar
Davis King committed
113
114
}

115
116
// ----------------------------------------------------------------------------------------

117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
std::string radial_basis_kernel__repr__(const radial_basis_kernel<sample_type>& item)
{
    std::ostringstream sout;
    sout << "radial_basis_kernel(gamma="<< item.gamma<<")"; 
    return sout.str();
}

std::string linear_kernel__repr__(const linear_kernel<sample_type>& item)
{
    std::ostringstream sout;
    sout << "linear_kernel()"; 
    return sout.str();
}

// ----------------------------------------------------------------------------------------

133
134
135
136
137
138
139
140
141
142
143
144
std::string binary_test__str__(const binary_test& item)
{
    std::ostringstream sout;
    sout << "class1_accuracy: "<< item.class1_accuracy << "  class2_accuracy: "<< item.class2_accuracy; 
    return sout.str();
}
std::string binary_test__repr__(const binary_test& item) { return "< " + binary_test__str__(item) + " >";}

std::string regression_test__str__(const regression_test& item)
{
    std::ostringstream sout;
    sout << "mean_squared_error: "<< item.mean_squared_error << "  R_squared: "<< item.R_squared; 
145
    sout << "  mean_average_error: "<< item.mean_average_error << "  mean_error_stddev: "<< item.mean_error_stddev; 
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
    return sout.str();
}
std::string regression_test__repr__(const regression_test& item) { return "< " + regression_test__str__(item) + " >";}

std::string ranking_test__str__(const ranking_test& item)
{
    std::ostringstream sout;
    sout << "ranking_accuracy: "<< item.ranking_accuracy << "  mean_ap: "<< item.mean_ap; 
    return sout.str();
}
std::string ranking_test__repr__(const ranking_test& item) { return "< " + ranking_test__str__(item) + " >";}

// ----------------------------------------------------------------------------------------

template <typename K>
binary_test  _test_binary_decision_function (
    const decision_function<K>& dec_funct,
    const std::vector<typename K::sample_type>& x_test,
    const std::vector<double>& y_test
) { return binary_test(test_binary_decision_function(dec_funct, x_test, y_test)); }

template <typename K>
regression_test _test_regression_function (
    const decision_function<K>& reg_funct,
    const std::vector<typename K::sample_type>& x_test,
    const std::vector<double>& y_test
) { return regression_test(test_regression_function(reg_funct, x_test, y_test)); }

template < typename K >
ranking_test _test_ranking_function1 (
    const decision_function<K>& funct,
    const std::vector<ranking_pair<typename K::sample_type> >& samples
) { return ranking_test(test_ranking_function(funct, samples)); }

template < typename K >
ranking_test _test_ranking_function2 (
    const decision_function<K>& funct,
    const ranking_pair<typename K::sample_type>& sample
) { return ranking_test(test_ranking_function(funct, sample)); }


187
void bind_decision_functions(py::module &m)
188
{
189
190
191
192
193
194
195
196
197
    add_linear_df<linear_kernel<sample_type> >(m, "_decision_function_linear");
    add_linear_df<sparse_linear_kernel<sparse_vect> >(m, "_decision_function_sparse_linear");

    add_df<histogram_intersection_kernel<sample_type> >(m, "_decision_function_histogram_intersection");
    add_df<sparse_histogram_intersection_kernel<sparse_vect> >(m, "_decision_function_sparse_histogram_intersection");

    add_df<polynomial_kernel<sample_type> >(m, "_decision_function_polynomial");
    add_df<sparse_polynomial_kernel<sparse_vect> >(m, "_decision_function_sparse_polynomial");

198
199
200
201
202
203
204
205

    py::class_<radial_basis_kernel<sample_type>>(m, "_radial_basis_kernel")
        .def("__repr__", radial_basis_kernel__repr__)
        .def_property_readonly("gamma", [](const radial_basis_kernel<sample_type>& k){return k.gamma; });

    py::class_<linear_kernel<sample_type>>(m, "_linear_kernel")
        .def("__repr__", linear_kernel__repr__);

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
    add_df<radial_basis_kernel<sample_type> >(m, "_decision_function_radial_basis");
    add_df<sparse_radial_basis_kernel<sparse_vect> >(m, "_decision_function_sparse_radial_basis");

    add_df<sigmoid_kernel<sample_type> >(m, "_decision_function_sigmoid");
    add_df<sparse_sigmoid_kernel<sparse_vect> >(m, "_decision_function_sparse_sigmoid");


    m.def("test_binary_decision_function", _test_binary_decision_function<linear_kernel<sample_type> >,
        py::arg("function"), py::arg("samples"), py::arg("labels"));
    m.def("test_binary_decision_function", _test_binary_decision_function<sparse_linear_kernel<sparse_vect> >,
        py::arg("function"), py::arg("samples"), py::arg("labels"));
    m.def("test_binary_decision_function", _test_binary_decision_function<radial_basis_kernel<sample_type> >,
        py::arg("function"), py::arg("samples"), py::arg("labels"));
    m.def("test_binary_decision_function", _test_binary_decision_function<sparse_radial_basis_kernel<sparse_vect> >,
        py::arg("function"), py::arg("samples"), py::arg("labels"));
    m.def("test_binary_decision_function", _test_binary_decision_function<polynomial_kernel<sample_type> >,
        py::arg("function"), py::arg("samples"), py::arg("labels"));
    m.def("test_binary_decision_function", _test_binary_decision_function<sparse_polynomial_kernel<sparse_vect> >,
        py::arg("function"), py::arg("samples"), py::arg("labels"));
    m.def("test_binary_decision_function", _test_binary_decision_function<histogram_intersection_kernel<sample_type> >,
        py::arg("function"), py::arg("samples"), py::arg("labels"));
    m.def("test_binary_decision_function", _test_binary_decision_function<sparse_histogram_intersection_kernel<sparse_vect> >,
        py::arg("function"), py::arg("samples"), py::arg("labels"));
    m.def("test_binary_decision_function", _test_binary_decision_function<sigmoid_kernel<sample_type> >,
        py::arg("function"), py::arg("samples"), py::arg("labels"));
    m.def("test_binary_decision_function", _test_binary_decision_function<sparse_sigmoid_kernel<sparse_vect> >,
        py::arg("function"), py::arg("samples"), py::arg("labels"));

    m.def("test_regression_function", _test_regression_function<linear_kernel<sample_type> >,
        py::arg("function"), py::arg("samples"), py::arg("targets"));
    m.def("test_regression_function", _test_regression_function<sparse_linear_kernel<sparse_vect> >,
        py::arg("function"), py::arg("samples"), py::arg("targets"));
    m.def("test_regression_function", _test_regression_function<radial_basis_kernel<sample_type> >,
        py::arg("function"), py::arg("samples"), py::arg("targets"));
    m.def("test_regression_function", _test_regression_function<sparse_radial_basis_kernel<sparse_vect> >,
        py::arg("function"), py::arg("samples"), py::arg("targets"));
    m.def("test_regression_function", _test_regression_function<histogram_intersection_kernel<sample_type> >,
        py::arg("function"), py::arg("samples"), py::arg("targets"));
    m.def("test_regression_function", _test_regression_function<sparse_histogram_intersection_kernel<sparse_vect> >,
        py::arg("function"), py::arg("samples"), py::arg("targets"));
    m.def("test_regression_function", _test_regression_function<sigmoid_kernel<sample_type> >,
        py::arg("function"), py::arg("samples"), py::arg("targets"));
    m.def("test_regression_function", _test_regression_function<sparse_sigmoid_kernel<sparse_vect> >,
        py::arg("function"), py::arg("samples"), py::arg("targets"));
    m.def("test_regression_function", _test_regression_function<polynomial_kernel<sample_type> >,
        py::arg("function"), py::arg("samples"), py::arg("targets"));
    m.def("test_regression_function", _test_regression_function<sparse_polynomial_kernel<sparse_vect> >,
        py::arg("function"), py::arg("samples"), py::arg("targets"));

    m.def("test_ranking_function", _test_ranking_function1<linear_kernel<sample_type> >,
        py::arg("function"), py::arg("samples"));
    m.def("test_ranking_function", _test_ranking_function1<sparse_linear_kernel<sparse_vect> >,
        py::arg("function"), py::arg("samples"));
    m.def("test_ranking_function", _test_ranking_function2<linear_kernel<sample_type> >,
        py::arg("function"), py::arg("sample"));
    m.def("test_ranking_function", _test_ranking_function2<sparse_linear_kernel<sparse_vect> >,
        py::arg("function"), py::arg("sample"));


    py::class_<binary_test>(m, "_binary_test")
266
267
        .def("__str__", binary_test__str__)
        .def("__repr__", binary_test__repr__)
268
        .def_readwrite("class1_accuracy", &binary_test::class1_accuracy,
Davis King's avatar
Davis King committed
269
            "A value between 0 and 1, measures accuracy on the +1 class.")
270
        .def_readwrite("class2_accuracy", &binary_test::class2_accuracy,
Davis King's avatar
Davis King committed
271
            "A value between 0 and 1, measures accuracy on the -1 class.");
272

273
    py::class_<ranking_test>(m, "_ranking_test")
274
275
        .def("__str__", ranking_test__str__)
        .def("__repr__", ranking_test__repr__)
276
        .def_readwrite("ranking_accuracy", &ranking_test::ranking_accuracy,
Davis King's avatar
Davis King committed
277
            "A value between 0 and 1, measures the fraction of times a relevant sample was ordered before a non-relevant sample.")
278
        .def_readwrite("mean_ap", &ranking_test::mean_ap,
Davis King's avatar
Davis King committed
279
            "A value between 0 and 1, measures the mean average precision of the ranking.");
280

281
    py::class_<regression_test>(m, "_regression_test")
282
283
        .def("__str__", regression_test__str__)
        .def("__repr__", regression_test__repr__)
284
        .def_readwrite("mean_average_error", &regression_test::mean_average_error,
285
            "The mean average error of a regression function on a dataset.")
286
        .def_readwrite("mean_error_stddev", &regression_test::mean_error_stddev,
287
            "The standard deviation of the absolute value of the error of a regression function on a dataset.")
288
        .def_readwrite("mean_squared_error", &regression_test::mean_squared_error,
Davis King's avatar
Davis King committed
289
            "The mean squared error of a regression function on a dataset.")
290
        .def_readwrite("R_squared", &regression_test::R_squared,
Davis King's avatar
Davis King committed
291
292
            "A value between 0 and 1, measures the squared correlation between the output of a \n"
            "regression function and the target values.");
293
294
295
296
}