forked from RubixML/ML
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOneClassSVM.php
More file actions
267 lines (233 loc) · 6.19 KB
/
Copy pathOneClassSVM.php
File metadata and controls
267 lines (233 loc) · 6.19 KB
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
258
259
260
261
262
263
264
265
266
267
<?php
namespace Rubix\ML\AnomalyDetectors;
use Rubix\ML\Learner;
use Rubix\ML\DataType;
use Rubix\ML\Estimator;
use Rubix\ML\EstimatorType;
use Rubix\ML\Helpers\Params;
use Rubix\ML\Kernels\SVM\RBF;
use Rubix\ML\Datasets\Dataset;
use Rubix\ML\Kernels\SVM\Kernel;
use Rubix\ML\Specifications\ExtensionIsLoaded;
use Rubix\ML\Specifications\DatasetIsNotEmpty;
use Rubix\ML\Specifications\SpecificationChain;
use Rubix\ML\Specifications\ExtensionMinimumVersion;
use Rubix\ML\Specifications\SamplesAreCompatibleWithEstimator;
use Rubix\ML\Exceptions\InvalidArgumentException;
use Rubix\ML\Exceptions\RuntimeException;
use svmmodel;
use svm;
/**
* One Class SVM
*
* An unsupervised Support Vector Machine (SVM) used for anomaly detection. The One
* Class SVM aims to find a maximum margin between a set of data points and the
* *origin*, rather than between classes such as with SVC.
*
* > **Note:** This estimator requires the SVM extension which uses the libsvm engine
* under the hood.
*
* References:
* [1] C. Chang et al. (2011). LIBSVM: A library for support vector machines.
*
* @category Machine Learning
* @package Rubix/ML
* @author Andrew DalPino
*/
class OneClassSVM implements Estimator, Learner
{
/**
* The support vector machine instance.
*
* @var svm
*/
protected svm $svm;
/**
* The hyper-parameters of the model.
*
* @var mixed[]
*/
protected array $params;
/**
* The trained model instance.
*
* @var svmmodel|null
*/
protected ?svmmodel $model = null;
/**
* @param float $nu
* @param Kernel|null $kernel
* @param bool $shrinking
* @param float $tolerance
* @param float $cacheSize
* @throws InvalidArgumentException
*/
public function __construct(
float $nu = 0.5,
?Kernel $kernel = null,
bool $shrinking = true,
float $tolerance = 1e-3,
float $cacheSize = 100.0
) {
SpecificationChain::with([
new ExtensionIsLoaded('svm'),
new ExtensionMinimumVersion('svm', '0.2.0'),
])->check();
if ($nu < 0.0 or $nu > 1.0) {
throw new InvalidArgumentException('Nu must be between'
. "0 and 1, $nu given.");
}
$kernel = $kernel ?? new RBF();
if ($tolerance < 0.0) {
throw new InvalidArgumentException('Tolerance must be,'
. " greater than 0, $tolerance given.");
}
if ($cacheSize <= 0.0) {
throw new InvalidArgumentException('Cache size must be'
. " greater than 0M, {$cacheSize}M given.");
}
$options = [
svm::OPT_TYPE => svm::ONE_CLASS,
svm::OPT_NU => $nu,
svm::OPT_SHRINKING => $shrinking,
svm::OPT_EPS => $tolerance,
svm::OPT_CACHE_SIZE => $cacheSize,
];
$options += $kernel->options();
$svm = new svm();
$svm->setOptions($options);
$this->svm = $svm;
$this->params = [
'nu' => $nu,
'kernel' => $kernel,
'shrinking' => $shrinking,
'tolerance' => $tolerance,
'cache size' => $cacheSize,
];
}
/**
* Return the estimator type.
*
* @internal
*
* @return EstimatorType
*/
public function type() : EstimatorType
{
return EstimatorType::anomalyDetector();
}
/**
* Return the data types that the estimator is compatible with.
*
* @internal
*
* @return list<\Rubix\ML\DataType>
*/
public function compatibility() : array
{
return [
DataType::continuous(),
];
}
/**
* Return the settings of the hyper-parameters in an associative array.
*
* @internal
*
* @return mixed[]
*/
public function params() : array
{
return $this->params;
}
/**
* Has the learner been trained?
*
* @return bool
*/
public function trained() : bool
{
return isset($this->model);
}
/**
* Train the learner with a dataset.
*
* @param Dataset $dataset
*/
public function train(Dataset $dataset) : void
{
SpecificationChain::with([
new DatasetIsNotEmpty($dataset),
new SamplesAreCompatibleWithEstimator($dataset, $this),
])->check();
$data = [];
foreach ($dataset->samples() as $sample) {
array_unshift($sample, 1);
$data[] = $sample;
}
$this->model = $this->svm->train($data);
}
/**
* Make predictions from a dataset.
*
* @param Dataset $dataset
* @return list<int>
*/
public function predict(Dataset $dataset) : array
{
return array_map([$this, 'predictSample'], $dataset->samples());
}
/**
* Predict a single sample and return the result.
*
* @internal
*
* @param list<int|float> $sample
* @throws RuntimeException
* @return int
*/
public function predictSample(array $sample) : int
{
if (!$this->model) {
throw new RuntimeException('Estimator has not been trained.');
}
$sampleWithOffset = [];
foreach ($sample as $key => $value) {
$sampleWithOffset[$key + 1] = $value;
}
return $this->model->predict($sampleWithOffset) == 1 ? 0 : 1;
}
/**
* Save the model data to the filesystem.
*
* @param string $path
* @throws RuntimeException
*/
public function save(string $path) : void
{
if (!$this->model) {
throw new RuntimeException('Learner must be trained before saving.');
}
$this->model->save($path);
}
/**
* Load model data from the filesystem.
*
* @param string $path
*/
public function load(string $path) : void
{
$this->model = new svmmodel($path);
}
/**
* Return the string representation of the object.
*
* @internal
*
* @return string
*/
public function __toString() : string
{
return 'One Class SVM (' . Params::stringify($this->params()) . ')';
}
}