This repository has been archived by the owner on Apr 24, 2020. It is now read-only.
forked from scikit-learn/scikit-learn
/
base.py
197 lines (157 loc) · 7.55 KB
/
base.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
import numpy as np
import scipy.sparse
from ..base import BaseLibSVM, LIBSVM_IMPL, _get_class_weight
from . import libsvm
class SparseBaseLibSVM(BaseLibSVM):
_kernel_types = ['linear', 'poly', 'rbf', 'sigmoid', 'precomputed']
def __init__(self, impl, kernel, degree, gamma, coef0,
tol, C, nu, epsilon, shrinking, probability, cache_size,
scale_C):
assert kernel in self._kernel_types, \
"kernel should be one of %s, "\
"%s was given." % (self._kernel_types, kernel)
super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma,
coef0, tol, C, nu, epsilon, shrinking, probability, cache_size,
scale_C)
def fit(self, X, y, class_weight=None, sample_weight=None):
"""
Fit the SVM model according to the given training data and parameters.
Parameters
----------
X : sparse matrix, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples]
Target values (integers in classification, real numbers in
regression)
class_weight : {dict, 'auto'}, optional
Weights associated with classes in the form
{class_label : weight}. If not given, all classes are
supposed to have weight one.
The 'auto' mode uses the values of y to automatically adjust
weights inversely proportional to class frequencies.
sample_weight : array-like, shape = [n_samples], optional
Weights applied to individual samples (1. for unweighted).
Returns
-------
self : object
Returns an instance of self.
Notes
-----
For maximum effiency, use a sparse matrix in csr format
(scipy.sparse.csr_matrix)
"""
X = scipy.sparse.csr_matrix(X)
X.data = np.asarray(X.data, dtype=np.float64, order='C')
y = np.asarray(y, dtype=np.float64, order='C')
sample_weight = np.asarray([] if sample_weight is None
else sample_weight, dtype=np.float64)
if X.shape[0] != y.shape[0]:
raise ValueError("X and y have incompatible shapes: %r vs %r\n"
"Note: Sparse matrices cannot be indexed w/"
"boolean masks (use `indices=True` in CV)."
% (X.shape, y.shape))
if sample_weight.shape[0] > 0 and sample_weight.shape[0] != X.shape[0]:
raise ValueError("sample_weight and X have incompatible shapes:"
"%r vs %r\n"
"Note: Sparse matrices cannot be indexed w/"
"boolean masks (use `indices=True` in CV)."
% (sample_weight.shape, X.shape))
solver_type = LIBSVM_IMPL.index(self.impl)
kernel_type = self._kernel_types.index(self.kernel)
self.class_weight, self.class_weight_label = \
_get_class_weight(class_weight, y)
if (kernel_type in [1, 2]) and (self.gamma == 0):
# if custom gamma is not provided ...
self.gamma = 1.0 / X.shape[1]
C = self.C
if self.scale_C:
C = C / float(X.shape[0])
self.support_vectors_, dual_coef_data, self.intercept_, self.label_, \
self.n_support_, self.probA_, self.probB_ = \
libsvm.libsvm_sparse_train(
X.shape[1], X.data, X.indices, X.indptr, y, solver_type,\
kernel_type, self.degree, self.gamma, self.coef0, self.tol,\
C, self.class_weight_label, self.class_weight,\
sample_weight, self.nu, self.cache_size, self.epsilon,\
int(self.shrinking), int(self.probability))
n_class = len(self.label_) - 1
n_SV = self.support_vectors_.shape[0]
dual_coef_indices = np.tile(np.arange(n_SV), n_class)
dual_coef_indptr = np.arange(0, dual_coef_indices.size + 1,
dual_coef_indices.size / n_class)
self.dual_coef_ = scipy.sparse.csr_matrix(
(dual_coef_data, dual_coef_indices, dual_coef_indptr),
(n_class, n_SV))
return self
def predict(self, T):
"""
This function does classification or regression on an array of
test vectors T.
For a classification model, the predicted class for each
sample in T is returned. For a regression model, the function
value of T calculated is returned.
For an one-class model, +1 or -1 is returned.
Parameters
----------
T : scipy.sparse.csr, shape = [n_samples, n_features]
Returns
-------
C : array, shape = [n_samples]
"""
T = scipy.sparse.csr_matrix(T)
T.data = np.asarray(T.data, dtype=np.float64, order='C')
kernel_type = self._kernel_types.index(self.kernel)
return libsvm.libsvm_sparse_predict(T.data, T.indices, T.indptr,
self.support_vectors_.data,
self.support_vectors_.indices,
self.support_vectors_.indptr,
self.dual_coef_.data, self.intercept_,
LIBSVM_IMPL.index(self.impl), kernel_type,
self.degree, self.gamma, self.coef0, self.tol,
self.C, self.class_weight_label, self.class_weight,
self.nu, self.epsilon, self.shrinking,
self.probability, self.n_support_, self.label_,
self.probA_, self.probB_)
def predict_proba(self, X):
"""
This function does classification or regression on a test vector X
given a model with probability information.
Parameters
----------
X : scipy.sparse.csr, shape = [n_samples, n_features]
Returns
-------
X : array-like, shape = [n_samples, n_classes]
Returns the probability of the sample for each class in
the model, where classes are ordered by arithmetical
order.
Notes
-----
The probability model is created using cross validation, so
the results can be slightly different than those obtained by
predict. Also, it will meaningless results on very small
datasets.
"""
if not self.probability:
raise ValueError(
"probability estimates must be enabled to use this method")
if self.impl not in ('c_svc', 'nu_svc'):
raise NotImplementedError("predict_proba only implemented for " +
"SVC and NuSVC")
X = scipy.sparse.csr_matrix(X)
X.data = np.asarray(X.data, dtype=np.float64, order='C')
kernel_type = self._kernel_types.index(self.kernel)
return libsvm.libsvm_sparse_predict_proba(
X.data, X.indices, X.indptr,
self.support_vectors_.data,
self.support_vectors_.indices,
self.support_vectors_.indptr,
self.dual_coef_.data, self.intercept_,
LIBSVM_IMPL.index(self.impl), kernel_type,
self.degree, self.gamma, self.coef0, self.tol,
self.C, self.class_weight_label, self.class_weight,
self.nu, self.epsilon, self.shrinking,
self.probability, self.n_support_, self.label_,
self.probA_, self.probB_)
libsvm.set_verbosity_wrap(0)