-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathclasses.ts
More file actions
324 lines (308 loc) · 7.91 KB
/
Copy pathclasses.ts
File metadata and controls
324 lines (308 loc) · 7.91 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import { SVM } from 'libsvm-ts';
import * as _ from 'lodash';
import { IMlModel, Type1DMatrix, Type2DMatrix } from '../types';
import { validateFitInputs, validateMatrix1D, validateMatrix2D } from '../utils/validation';
/**
* Options used by sub classes
* Notice type is disabled as they are set statically from children classes.
*/
export interface SVMOptions {
/**
* Degree of polynomial, test for polynomial kernel
*/
degree?: number;
/**
* Type of Kernel
*/
kernel?: string;
/**
* Type of SVM
*/
type?: string;
/**
* Gamma parameter of the RBF, Polynomial and Sigmoid kernels. Default value is 1/num_features
*/
gamma?: number | null;
/**
* coef0 parameter for Polynomial and Sigmoid kernels
*/
coef0?: number;
/**
* Cost parameter, for C SVC, Epsilon SVR and NU SVR
*/
cost?: number;
/**
* For NU SVC and NU SVR
*/
nu?: number;
/**
* For epsilon SVR
*/
epsilon?: number;
/**
* Cache size in MB
*/
cacheSize?: number;
/**
* Tolerance
*/
tolerance?: number;
/**
* Use shrinking euristics (faster)
*/
shrinking?: boolean;
/**
* weather to train SVC/SVR model for probability estimates,
*/
probabilityEstimates?: boolean;
/**
* Set weight for each possible class
*/
weight?: {
[n: number]: number;
};
/**
* Print info during training if false (aka verbose)
*/
quiet?: boolean;
}
/**
* BaseSVM class used by all parent SVM classes that are based on libsvm.
* You may still use this to use the underlying libsvm-ts more flexibly.
*
* Note: This API is not available on the browsers
*/
export class BaseSVM implements IMlModel<number> {
protected svm: SVM;
protected options: SVMOptions;
constructor(options?: SVMOptions) {
this.options = {
cacheSize: _.get(options, 'cacheSize', 100),
coef0: _.get(options, 'coef0', 0),
cost: _.get(options, 'cost', 1),
degree: _.get(options, 'degree', 3),
epsilon: _.get(options, 'epsilon', 0.1),
gamma: _.get(options, 'gamma', null),
kernel: _.get(options, 'kernel', 'RBF'),
type: _.get(options, 'type', 'C_SVC'),
nu: _.get(options, 'nu', 0.5),
probabilityEstimates: _.get(options, 'probabilityEstimates', false),
quiet: _.get(options, 'quiet', true),
shrinking: _.get(options, 'shrinking', true),
tolerance: _.get(options, 'tolerance', 0.001),
weight: _.get(options, 'weight', undefined),
};
this.svm = new SVM(this.options);
}
/**
* Loads a WASM version of SVM. The method returns the instance of itself as a promise result.
*/
public loadWASM(): Promise<BaseSVM> {
return this.svm.loadWASM().then((wasmSVM) => {
this.svm = wasmSVM;
return Promise.resolve(this);
});
}
/**
* Loads a ASM version of SVM. The method returns the instance of itself as a promise result.
*/
public loadASM(): Promise<BaseSVM> {
return this.svm.loadASM().then((asmSVM) => {
this.svm = asmSVM;
return Promise.resolve(this);
});
}
/**
* Fit the model according to the given training data.
* @param {number[][]} X
* @param {number[]} y
* @returns {Promise<void>}
*/
public fit(X: Type2DMatrix<number>, y: Type1DMatrix<number>): void {
validateFitInputs(X, y);
this.svm.train({
samples: X,
labels: y,
});
}
/**
* Predict using the linear model
* @param {number[][]} X
* @returns {number[]}
*/
public predict(X: Type2DMatrix<number>): number[] {
validateMatrix2D(X);
return this.svm.predict({ samples: X });
}
/**
* Predict the label of one sample.
* @param {number[]} X
* @returns {number}
*/
public predictOne(X: Type1DMatrix<number>): number {
validateMatrix1D(X);
return this.svm.predictOne({ sample: X });
}
/**
* Saves the current SVM as a JSON object
* @returns {{svm: SVM; options: SVMOptions}}
*/
public toJSON(): { svm: SVM; options: SVMOptions } {
return {
svm: this.svm,
options: this.options,
};
}
/**
* Restores the model from a JSON checkpoint
* @param {SVM} svm
* @param {any} options
*/
public fromJSON({ svm = null, options = null }): void {
if (!svm || !options) {
throw new Error('You must provide svm, type and options to restore the model');
}
this.svm = svm;
this.options = options;
}
}
/**
* C-Support Vector Classification.
*
* The implementation is based on libsvm. The fit time complexity is more than
* quadratic with the number of samples which makes it hard to scale to dataset
* with more than a couple of 10000 samples.
*
* The multiclass support is handled according to a one-vs-one scheme.
*
* For details on the precise mathematical formulation of the provided kernel
* functions and how gamma, coef0 and degree affect each other, see the corresponding
* section in the narrative documentation: Kernel functions.
*
* Note: This API is not available on the browsers
*
* @example
* import { SVC } from 'machinelearn/svm';
*
* const svm = new SVC();
* svm.loadASM().then((loadedSVM) => {
* loadedSVM.fit([[0, 0], [1, 1]], [0, 1]);
* loadedSVM.predict([[1, 1]]); // [1]
* });
*/
export class SVC extends BaseSVM {
constructor(options?: SVMOptions) {
super({
...options,
type: 'C_SVC',
});
}
}
/**
* Linear Support Vector Regression.
*
* Similar to SVR with parameter kernel=’linear’, but implemented in terms of
* liblinear rather than libsvm, so it has more flexibility in the choice of
* penalties and loss functions and should scale better to large numbers of samples.
*
* This class supports both dense and sparse input.
*
* Note: This API is not available on the browsers
*
* @example
* import { SVR } from 'machinelearn/svm';
*
* const svm = new SVR();
* svm.loadASM().then((loadedSVM) => {
* loadedSVM.fit([[0, 0], [1, 1]], [0, 1]);
* loadedSVM.predict([[1, 1]]); // [0.9000000057898799]
* });
*/
export class SVR extends BaseSVM {
constructor(options?: SVMOptions) {
super({
...options,
type: 'EPSILON_SVR',
});
}
}
/**
* Unsupervised Outlier Detection.
*
* Estimate the support of a high-dimensional distribution.
*
* The implementation is based on libsvm.
*
* Note: This API is not available on the browsers
*
* @example
* import { OneClassSVM } from 'machinelearn/svm';
*
* const svm = new OneClassSVM();
* svm.loadASM().then((loadedSVM) => {
* loadedSVM.fit([[0, 0], [1, 1]], [0, 1]);
* loadedSVM.predict([[1, 1]]); // [-1]
* });
*/
export class OneClassSVM extends BaseSVM {
constructor(options?: SVMOptions) {
super({
...options,
type: 'ONE_CLASS',
});
}
}
/**
* Nu-Support Vector Classification.
*
* Similar to SVC but uses a parameter to control the number of support vectors.
*
* The implementation is based on libsvm.
*
* Note: This API is not available on the browsers
*
* @example
* import { NuSVC } from 'machinelearn/svm';
*
* const svm = new NuSVC();
* svm.loadASM().then((loadedSVM) => {
* loadedSVM.fit([[0, 0], [1, 1]], [0, 1]);
* loadedSVM.predict([[1, 1]]); // [1]
* });
*/
export class NuSVC extends BaseSVM {
constructor(options?: SVMOptions) {
super({
...options,
type: 'NU_SVC',
});
}
}
/**
* Nu Support Vector Regression.
*
* Similar to NuSVC, for regression, uses a parameter nu to control the number
* of support vectors. However, unlike NuSVC, where nu replaces C, here nu
* replaces the parameter epsilon of epsilon-SVR.
*
* The implementation is based on libsvm.
*
* Note: This API is not available on the browsers
*
* @example
* import { NuSVR } from 'machinelearn/svm';
*
* const svm = new NuSVR();
* svm.loadASM().then((loadedSVM) => {
* loadedSVM.fit([[0, 0], [1, 1]], [0, 1]);
* loadedSVM.predict([[1, 1]]); // [0.9000000057898799]
* });
*/
export class NuSVR extends BaseSVM {
constructor(options?: SVMOptions) {
super({
...options,
type: 'NU_SVR',
});
}
}