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
use simd_aligned::{f32s, f64s, RowOptimized, SimdMatrix, SimdVector};
use std::{convert::TryFrom};
use crate::{
errors::Error,
parser::ModelFile,
svm::{
class::Class,
kernel::{KernelDense, Linear, Poly, Rbf, Sigmoid},
predict::Predict,
problem::{Problem, Solution},
Probabilities, SVMType,
},
util::{find_max_index, set_all, sigmoid_predict},
vectors::Triangular,
};
pub struct DenseSVM {
pub(crate) num_total_sv: usize,
pub(crate) num_attributes: usize,
pub(crate) rho: Triangular<f64>,
pub(crate) probabilities: Option<Probabilities>,
pub(crate) svm_type: SVMType,
pub(crate) kernel: Box<dyn KernelDense>,
pub(crate) classes: Vec<Class<SimdMatrix<f32s, RowOptimized>>>,
}
impl DenseSVM {
pub fn class_index_for_label(&self, label: i32) -> Option<usize> {
for (i, class) in self.classes.iter().enumerate() {
if class.label != label {
continue;
}
return Some(i);
}
None
}
pub fn class_label_for_index(&self, index: usize) -> Option<i32> {
if index >= self.classes.len() {
None
} else {
Some(self.classes[index].label)
}
}
pub(crate) fn compute_kernel_values(&self, problem: &mut Problem<SimdVector<f32s>>) {
let features = &problem.features;
let kernel_values = &mut problem.kernel_values;
for (i, class) in self.classes.iter().enumerate() {
let kvalues = kernel_values.row_as_flat_mut(i);
self.kernel.compute(&class.support_vectors, features.as_raw(), kvalues);
}
}
pub(crate) fn compute_multiclass_probabilities(
&self,
problem: &mut Problem<SimdVector<f32s>>,
) -> Result<(), Error> {
compute_multiclass_probabilities_impl!(self, problem)
}
pub(crate) fn compute_classification_values(&self, problem: &mut Problem<SimdVector<f32s>>) {
compute_classification_values_impl!(self, problem)
}
pub(crate) fn compute_regression_values(&self, problem: &mut Problem<SimdVector<f32s>>) {
let class = &self.classes[0];
let coef = class.coefficients.row(0);
let kvalues = problem.kernel_values.row(0);
let mut sum = coef.iter().zip(kvalues).map(|(a, b)| (*a * *b).sum()).sum::<f64>();
sum -= self.rho[0];
problem.result = Solution::Value(sum as f32);
}
pub fn attributes(&self) -> usize { self.num_attributes }
pub fn classes(&self) -> usize { self.classes.len() }
}
impl Predict<SimdVector<f32s>, SimdVector<f64s>> for DenseSVM {
fn predict_probability(&self, problem: &mut Problem<SimdVector<f32s>>) -> Result<(), Error> {
predict_probability_impl!(self, problem)
}
fn predict_value(&self, problem: &mut Problem<SimdVector<f32s>>) -> Result<(), Error> {
match self.svm_type {
SVMType::CSvc | SVMType::NuSvc => {
self.compute_kernel_values(problem);
self.compute_classification_values(problem);
let highest_vote = find_max_index(&problem.vote);
problem.result = Solution::Label(self.classes[highest_vote].label);
Ok(())
}
SVMType::ESvr | SVMType::NuSvr => {
self.compute_kernel_values(problem);
self.compute_regression_values(problem);
Ok(())
}
}
}
}
impl<'a, 'b> TryFrom<&'a str> for DenseSVM {
type Error = Error;
fn try_from(input: &'a str) -> Result<DenseSVM, Error> {
let raw_model = ModelFile::try_from(input)?;
Self::try_from(&raw_model)
}
}
impl<'a, 'b> TryFrom<&'a ModelFile<'b>> for DenseSVM {
type Error = Error;
fn try_from(raw_model: &'a ModelFile<'_>) -> Result<DenseSVM, Error> {
let (mut svm, nr_sv) = prepare_svm!(raw_model, dyn KernelDense, SimdMatrix<f32s, RowOptimized>, DenseSVM);
let vectors = &raw_model.vectors;
let mut start_offset = 0;
for (i, num_sv_per_class) in nr_sv.iter().enumerate() {
let stop_offset = start_offset + *num_sv_per_class as usize;
for (i_vector, vector) in vectors[start_offset .. stop_offset].iter().enumerate() {
let mut last_attribute = None;
for (i_attribute, attribute) in vector.features.iter().enumerate() {
if let Some(last) = last_attribute {
if attribute.index != last + 1 {
return Result::Err(Error::AttributesUnordered {
index: attribute.index,
value: attribute.value,
last_index: last,
});
}
};
let mut support_vectors = svm.classes[i].support_vectors.flat_mut();
support_vectors[(i_vector, i_attribute)] = attribute.value;
last_attribute = Some(attribute.index);
}
for (i_coefficient, coefficient) in vector.coefs.iter().enumerate() {
let mut coefficients = svm.classes[i].coefficients.flat_mut();
coefficients[(i_coefficient, i_vector)] = f64::from(*coefficient);
}
}
start_offset = stop_offset;
}
Result::Ok(svm)
}
}
#[cfg(test)]
mod tests {
use crate::*;
use std::convert::TryFrom;
#[test]
fn class_operations() -> Result<(), Error> {
let svm = DenseSVM::try_from(SAMPLE_MODEL)?;
assert_eq!(None, svm.class_index_for_label(0));
assert_eq!(Some(1), svm.class_index_for_label(42));
Ok(())
}
}