forked from KevinCoble/AIToolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSVM.swift
1865 lines (1661 loc) · 67.5 KB
/
SVM.swift
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// SVM.swift
// AIToolbox
//
// Created by Kevin Coble on 10/6/15.
//
// Based on LIBSVM
// Copyright (c) 2000-2014 Chih-Chung Chang and Chih-Jen Lin
// All rights reserved
// See LIBSVM copyright notice for details
//
import Foundation
public enum SVMType: Int // SVM problem type
{
case c_SVM_Classification = 0
case ν_SVM_Classification
case oneClassSVM
case ϵSVMRegression
case νSVMRegression
}
struct DecisionFunction {
var ρ : Double
var α : [Double]
}
open class SVMModel
{
/// Parameters to be set by the caller
let type : SVMType // Type of SVM problem we are trying to solve
open var Cost : Double = 1.0 // Cost parameter for for C_SVM_Classification, ϵSVMRegression and νSVMRegression
open var weightModifiers : [(classLabel: Int, multiplier: Double)]? // Cost modifiers for each class
open var probability = false // Flag indicating probabilities should be calculated
open var kernelParams: KernelParameters
open var ϵ = 1e-3 // stopping criteria
open var ν = 0.5 // For ν classification and regression
open var p = 0.1 // for ϵ regression
// Internal storage
// Solution results
var numClasses = 0
var labels: [Int] = []
var ρ : [Double] = []
var totalSupportVectors = 0
var supportVectorCount: [Int] = []
var supportVector: [[Double]] = []
var coefficients: [[Double]] = [] // Array for each class, element for each support vector, ordered by opposing class index
var probabilityA: [Double] = []
var probabilityB: [Double] = []
/// Create an SVM model
public init(problemType : SVMType, kernelSettings: KernelParameters)
{
type = problemType
// Initialize the kernel parameters to a linear kernel
kernelParams = kernelSettings
}
public init(copyFrom: SVMModel)
{
type = copyFrom.type
kernelParams = copyFrom.kernelParams
Cost = copyFrom.Cost
weightModifiers = copyFrom.weightModifiers
probability = copyFrom.probability
}
#if os(Linux)
#else
public init?(loadFromFile path: String)
{
// Initialize all the stored properties (Swift requires this, even when returning nil [supposedly fixed in Swift 2.2)
numClasses = 0
labels = []
ρ = []
totalSupportVectors = 0
supportVectorCount = []
supportVector = []
coefficients = []
probabilityA = []
probabilityB = []
kernelParams = KernelParameters(type: .radialBasisFunction, degree: 0, gamma: 0.5, coef0: 0.0)
// Read the property list
let pList = NSDictionary(contentsOfFile: path)
if pList == nil {type = .c_SVM_Classification; return nil }
let dictionary : Dictionary = pList! as! Dictionary<String, AnyObject>
// Get the training results from the dictionary
let typeValue = dictionary["type"] as? NSInteger
if typeValue == nil {type = .c_SVM_Classification; return nil }
let testType = SVMType(rawValue: typeValue!)
if testType == nil {type = .c_SVM_Classification; return nil }
type = testType!
let numClassValue = dictionary["numClasses"] as? NSInteger
if numClassValue == nil { return nil }
numClasses = numClassValue!
let labelArray = dictionary["labels"] as? NSArray
if labelArray == nil { return nil }
labels = labelArray! as! [Int]
let rhoArray = dictionary["ρ"] as? NSArray
if rhoArray == nil { return nil }
ρ = rhoArray! as! [Double]
let totalSVValue = dictionary["totalSupportVectors"] as? NSInteger
if totalSVValue == nil { return nil }
totalSupportVectors = totalSVValue!
let svCountArray = dictionary["supportVectorCount"] as? NSArray
if svCountArray == nil { return nil }
supportVectorCount = svCountArray! as! [Int]
let svArray = dictionary["supportVector"] as? NSArray
if svArray == nil { return nil }
supportVector = svArray! as! [[Double]]
let coeffArray = dictionary["coefficients"] as? NSArray
if coeffArray == nil { return nil }
coefficients = coeffArray! as! [[Double]]
let probAArray = dictionary["probabilityA"] as? NSArray
if probAArray == nil { return nil }
probabilityA = probAArray! as! [Double]
let probBArray = dictionary["probabilityB"] as? NSArray
if probBArray == nil { return nil }
probabilityB = probBArray! as! [Double]
}
#endif
open func isνFeasableForData(_ data: MLClassificationDataSet) -> Bool
{
if (type != .ν_SVM_Classification) { return true }
var label : [Int] = []
var count : [Int] = []
for i in 0..<data.size {
do {
let pointLabel = try data.getClass(i)
if let index = label.index(of: pointLabel) {
// label already found
count[index] += 1
}
else {
// new label - add to list
label.append(pointLabel)
count.append(1)
}
}
catch {
// Error getting class
}
}
for i in 0..<label.count {
for j in (i+1)..<label.count {
if (ν * Double(count[i] + count[j]) * 0.5 > Double(min(count[i], count[j]))) {
return false
}
}
}
return true
}
/// Method to 'train' the SVM
open func train(_ data: MLCombinedDataSet)
{
// Training depends on the problem type
switch (type) {
// Training for one-class classification or regression
case .oneClassSVM, .ϵSVMRegression, .νSVMRegression:
// Initialize the model parameters for single-class
numClasses = 1
labels = []
supportVector = []
coefficients = [[]]
// If probability flag on, calculate the probabilities
if (probability && (type == .ϵSVMRegression || type == .νSVMRegression)) {
probabilityA = [svrProbability(data)]
}
// Train one set of support vectors
let f = trainOne(data, costPositive: 0.0, costNegative: 0.0, display: true)
ρ = [f.ρ]
// Build the output
totalSupportVectors = 0
supportVector = []
coefficients = [[]]
for index in 0..<data.size { // Get the support vector points and save them
if (fabs(f.α[index]) > 0.0) {
do {
let inputs = try data.getInput(index)
totalSupportVectors += 1
supportVector.append(inputs)
coefficients[0].append(f.α[index])
}
catch {
// Error getting inputs
}
}
}
break
// Training for classification
case .c_SVM_Classification, .ν_SVM_Classification:
// Group training data of the same class
do {
// Group the data into classes
let classificationData = try data.groupClasses()
data.optionalData = classificationData
if (classificationData.numClasses <= 1) {
print("Invalid number of classes in data")
return
}
// Calculate weighted Cost for each class label
var weightedCost = [Double](repeating: Cost, count: classificationData.numClasses)
if let weightMods = weightModifiers {
for mod in weightMods {
let index = classificationData.foundLabels.index(of: mod.classLabel)
if (index == nil) {
print("weight modifier label \(mod.classLabel) not found in data set")
continue
}
else {
weightedCost[index!] *= mod.multiplier
}
}
}
// Train numClasses * (numClasses - 1) / 2 models
var nonZero = [Bool](repeating: false, count: data.size)
var functions: [DecisionFunction] = []
probabilityA = []
probabilityB = []
for i in 0..<classificationData.numClasses-1 {
for j in i+1..<classificationData.numClasses {
// Create a sub-problem data set with just the i and j class data
if let subProblem = DataSet(fromDataSet: data, withEntries: classificationData.classOffsets[i]) {
do {
try subProblem.includeEntries(fromDataSet: data, withEntries: classificationData.classOffsets[j])
// Set the sub-problem class labels to 1 and -1
for index in 0..<classificationData.classCount[i] {
try subProblem.setClass(index, newClass: 1)
}
for index in classificationData.classCount[i]..<subProblem.size {
try subProblem.setClass(index, newClass: -1)
}
// If the probability flag is set, calculate the probabilities
if (probability) {
let result = binarySVCProbability(subProblem, positiveLabel: classificationData.foundLabels[i], costPositive: weightedCost[i], costNegative: weightedCost[j])
probabilityA.append(result.A)
probabilityB.append(result.B)
}
// Train on this sub-problem
let f = trainOne(subProblem, costPositive: weightedCost[i], costNegative: weightedCost[j], display: true)
functions.append(f)
// Mark the non-zero α's
for index in 0..<classificationData.classCount[i] {
if (fabs(f.α[index]) > 0.0) { nonZero[classificationData.classOffsets[i][index]] = true}
}
for index in 0..<classificationData.classCount[j] {
if (fabs(f.α[index+classificationData.classCount[i]]) > 0.0) { nonZero[classificationData.classOffsets[j][index]] = true}
}
}
}
}
}
// Build output
numClasses = classificationData.numClasses
labels = classificationData.foundLabels
ρ = []
for df in functions {
ρ.append(df.ρ)
}
totalSupportVectors = 0
supportVectorCount = [Int](repeating: 0, count: classificationData.numClasses)
for i in 0..<classificationData.numClasses {
for j in 0..<classificationData.classCount[i] {
if(nonZero[classificationData.classOffsets[i][j]]) {
supportVectorCount[i] += 1
totalSupportVectors += 1
}
}
}
print("Total nSV = \(totalSupportVectors)")
supportVector = []
for index in 0..<data.size { // Get the support vector points and save them
if (nonZero[index]) {
do {
let inputs = try data.getInput(index)
supportVector.append(inputs)
}
catch {
// Error getting inputs
}
}
}
// Get the start locations in the coefficient array for each class's coeffiecient
var coeffStart: [Int] = [0]
for index in 0..<classificationData.numClasses-1 {
coeffStart.append(coeffStart[index] + supportVectorCount[index])
}
// Save the α's for each class permutation as a set of coefficients of the support vectors
coefficients = []
for _ in 0..<classificationData.numClasses-1 {
coefficients.append([Double](repeating: 0.0, count: totalSupportVectors))
}
var permutation = 0
for i in 0..<classificationData.numClasses-1 {
for j in i+1..<classificationData.numClasses {
var q = coeffStart[i]
for index in 0..<classificationData.classCount[i] {
if (nonZero[classificationData.classOffsets[i][index]]) {
coefficients[j-1][q] = functions[permutation].α[index]
q += 1
}
}
q = coeffStart[j]
for index in 0..<classificationData.classCount[j] {
if (nonZero[classificationData.classOffsets[j][index]]) {
coefficients[i][q] = functions[permutation].α[index + classificationData.classCount[i]]
q += 1
}
}
permutation += 1
}
}
}
catch {
// Handle error
}
break
}
}
fileprivate func trainOne(_ data: MLCombinedDataSet, costPositive : Double, costNegative : Double, display : Bool = false) -> DecisionFunction
{
var solver : Solver?
// Use the solver to determine the support vectors
switch (type) {
case .c_SVM_Classification:
// Instantiate a solver class
solver = Solver(kernelParams: kernelParams, ϵ: ϵ)
solver!.costPositive = costPositive
solver!.costNegative = costNegative
solver!.solveClassification(data, display: display)
break
case .ν_SVM_Classification:
// Instantiate a solver class
solver = Solver_ν(kernelParams: kernelParams, ϵ: ϵ, ν: ν)
solver!.costPositive = 1.0
solver!.costNegative = 1.0
solver!.solveClassification(data, display: display)
break
case .oneClassSVM:
// Instantiate a solver class
solver = Solver(kernelParams: kernelParams, ϵ: ϵ)
solver!.costPositive = 1.0
solver!.costNegative = 1.0
solver!.solveOneClass(data, ν: ν, display: display)
break
case .ϵSVMRegression:
// Instantiate a solver class
solver = Solver(kernelParams: kernelParams, ϵ: ϵ)
solver!.costPositive = Cost
solver!.costNegative = Cost
solver!.solveRegression(data, p: p, display: display)
break
case .νSVMRegression:
// Instantiate a solver class
solver = Solver_ν(kernelParams: kernelParams, ϵ: ϵ, ν: ν)
solver!.costPositive = Cost
solver!.costNegative = Cost
solver!.solveRegression(data, p: p, display: display)
break
}
// If display flag is set, show the results
if (display) {
print("obj = \(solver!.obj), rho = \(solver!.ρ)")
// Count the number of support vectors
var numSupportVectors = 0
var numBaseSupportVectors = 0
for index in 0..<data.size {
let entry = solver!.α[index]
if(abs(entry) > 0.0)
{
numSupportVectors += 1
if let output = data.singleOutput(index) {
if(output > 0.0) {
if(abs(entry) >= solver!.positiveUpperBound) {numBaseSupportVectors += 1}
}
else {
if(abs(entry) >= solver!.negativeUpperBound) {numBaseSupportVectors += 1}
}
}
}
}
print("nSV = \(numSupportVectors), nBSV = \(numBaseSupportVectors)");
}
let f = DecisionFunction(ρ: solver!.ρ, α: solver!.α)
return f
}
open func crossValidation(_ data: MLCombinedDataSet, numberOfFolds: Int) -> [Double]
{
var target = [Double](repeating: 0.0, count: data.size)
// Limit check the number of folds
var nFolds = numberOfFolds
if (nFolds > data.size)
{
nFolds = data.size
print("WARNING: # folds > # data. Will use # folds = # data instead (i.e., leave-one-out cross validation)")
}
// Get the fold data set indices
var foldStart : [Int] = []
var perm : [Int] = []
if ((type == .c_SVM_Classification || type == .ν_SVM_Classification) && nFolds < data.size) {
// Group the classes
do {
// Group the data into classes
let classificationData = try data.groupClasses()
data.optionalData = classificationData
// Get a random shuffle of the data in each class
var shuffledIndices = classificationData.classOffsets
for c in 0..<classificationData.numClasses {
for i in 0..<classificationData.classCount[c] {
#if os(Linux)
let j = i + random() % (classificationData.classCount[c] - i)
#else
let j = i + Int(arc4random()) % (classificationData.classCount[c] - i)
#endif
swap(&shuffledIndices[c][i], &shuffledIndices[c][j])
}
}
// Get the count of items for each fold
var foldCount = [Int](repeating: 0, count: nFolds)
for i in 0..<nFolds {
for c in 0..<classificationData.numClasses {
foldCount[i] += (i+1) * classificationData.classCount[c] / nFolds - i * classificationData.classCount[c] / nFolds
}
}
// Get the start of each fold
foldStart.append(0)
for i in 1...nFolds {
foldStart.append(foldStart[i-1] + foldCount[i-1])
}
// Get the permutation index array
perm = []
for c in 0..<classificationData.numClasses {
for i in 0..<nFolds {
let begin = i * classificationData.classCount[c] / nFolds;
let end = (i+1) * classificationData.classCount[c] / nFolds;
for j in begin..<end {
perm.append(shuffledIndices[c][j])
}
}
}
}
catch {
// Handle error
}
}
else {
perm = data.getRandomIndexSet()
for i in 0...nFolds {
foldStart.append(i * data.size / nFolds)
}
}
// Calculate each fold
for i in 0..<nFolds {
// Create the sub-problem data set, all points except those in the fold
var subIndices : [Int] = []
if (i > 0) {
subIndices += Array(perm[0..<foldStart[i]])
}
if (i < nFolds) {
subIndices += Array(perm[foldStart[i]]..<data.size)
}
if let subProblem = DataSet(fromDataSet: data, withEntries: subIndices) {
let subModel = SVMModel(copyFrom:self)
subModel.train(subProblem)
do {
if (probability && (type == .c_SVM_Classification || type == .ν_SVM_Classification)) {
for j in foldStart[i]..<foldStart[i+1] {
let inputs = try data.getInput(perm[j])
target[perm[j]] = subModel.predictProbability(inputs)
}
}
else {
for j in foldStart[i]..<foldStart[i+1] {
let inputs = try data.getInput(perm[j])
target[perm[j]] = subModel.predictOne(inputs)
}
}
}
catch {
// Error getting inputs
}
}
}
return target
}
func binarySVCProbability(_ data: MLCombinedDataSet, positiveLabel: Int, costPositive: Double, costNegative: Double) -> (A: Double, B: Double)
{
// Get a shuffled index set
var perm = data.getRandomIndexSet()
// Create the array for the decision values
var decisionValues = [Double](repeating: 0.0, count: data.size)
// Do 5 cross-validations
let nr_fold = 5
for index in 0..<nr_fold {
// Create a sub-problem with the data without the cross validation set
let begin = index * data.size / nr_fold;
let end = (index+1) * data.size / nr_fold;
var subIndices = Array(perm[0..<begin])
subIndices += Array(perm[end..<data.size])
if let subProblem = DataSet(fromDataSet: data, withEntries: subIndices) {
// Count the number of positive and negative data points in the sub-problem
var countPositive = 0
var countNegative = 0
var positiveLabel = 0
var negativeLabel = 0
for index in 0..<subProblem.size {
do {
let itemClass = try subProblem.getClass(index)
if (itemClass == positiveLabel) {
countPositive += 1
positiveLabel = itemClass
}
else {
countNegative += 1
negativeLabel = itemClass
}
}
catch {
// Error getting class
}
}
// Set the decision values
if (countPositive==0 && countNegative==0) {
for index in begin..<end { decisionValues[perm[index]] = 0.0 }
}
else if(countPositive > 0 && countNegative == 0) {
for index in begin..<end { decisionValues[perm[index]] = 1.0 }
}
else if(countPositive == 0 && countNegative > 0) {
for index in begin..<end { decisionValues[perm[index]] = -1.0 }
}
else
{
// Train an SVM on the sub-problem
let subModel = SVMModel(problemType: type, kernelSettings: kernelParams)
subModel.weightModifiers = [(classLabel: positiveLabel, multiplier: costPositive), (classLabel: negativeLabel, multiplier: costNegative)]
subModel.train(subProblem)
// Set the decision values based on the predictions from the sub-model
for index in begin..<end {
do {
let inputs = try data.getInput(index)
decisionValues[perm[index]] = Double(subModel.predictOneFromBinaryClass(inputs))
}
catch {
// Error getting inputs
}
}
}
}
}
var labels : [Int] = []
do {
for index in 0..<data.size { labels.append(try data.getClass(index)) }
}
catch {
// Error getting labels
}
return sigmoidTrain(decisionValues, labels: labels)
}
func sigmoidTrain(_ decisionValues: [Double], labels: [Int]) -> (A: Double, B: Double)
{
// Count the prior labels
var prior0 = 0.0
var prior1 = 0.0
for label in labels {
if (label > 0) {
prior1 += 1.0
}
else {
prior0 += 1.0
}
}
// Set up iteration parameters
let max_iter = 100 // Maximal number of iterations
let min_step = 1e-10 // Minimal step taken in line search
let sigma = 1e-12 // For numerically strict PD of Hessian
let eps = 1e-5
let hiTarget = (prior1+1.0)/(prior1+2.0)
let loTarget = 1/(prior0+2.0)
// Initialize Point and Initial Fun Value
var A = 0.0
var B = log((prior0+1.0)/(prior1+1.0))
var fval = 0.0
var t : [Double] = []
for index in 0..<labels.count {
if (labels[index] > 0) {
t.append(hiTarget)
}
else {
t.append(loTarget)
}
let fApB = decisionValues[index] * A + B
if (fApB>=0) {
fval += t[index] * fApB + log(1+exp(-fApB))
}
else {
fval += (t[index] - 1.0) * fApB + log(1.0 + exp(fApB))
}
}
for iter in 0..<max_iter {
// Update Gradient and Hessian (use H' = H + sigma I)
var h11 = sigma // numerically ensures strict PD
var h22 = sigma
var h21 = 0.0
var g1 = 0.0
var g2 = 0.0
for index in 0..<labels.count {
let fApB = decisionValues[index] * A + B
var p, q : Double
if (fApB >= 0) {
p=exp(-fApB)/(1.0+exp(-fApB));
q=1.0/(1.0+exp(-fApB));
}
else {
p=1.0/(1.0+exp(fApB));
q=exp(fApB)/(1.0+exp(fApB));
}
let d2 = p * q
h11 += decisionValues[index] * decisionValues[index] * d2
h22 += d2
h21 += decisionValues[index] * d2
let d1 = t[index] - p
g1 += decisionValues[index] * d1
g2 += d1
}
// Stopping Criteria
if (fabs(g1)<eps && fabs(g2)<eps) { break }
// Finding Newton direction: -inv(H') * g
let det = h11 * h22 - h21 * h21;
let dA = -(h22 * g1 - h21 * g2) / det
let dB = -(-h21 * g1 + h11 * g2) / det
let gd = g1 * dA + g2 * dB
var stepsize = 1.0 // Line Search
while (stepsize >= min_step)
{
let newA = A + stepsize * dA
let newB = B + stepsize * dB
// New function value
var newf = 0.0
for index in 0..<labels.count {
let fApB = decisionValues[index] * newA + newB
if (fApB >= 0) {
newf += t[index]*fApB + log(1+exp(-fApB))
}
else {
newf += (t[index] - 1.0) * fApB + log(1.0 + exp(fApB))
}
}
// Check sufficient decrease
if (newf < fval+0.0001*stepsize*gd)
{
A = newA
B = newB
fval = newf
break
}
else {
stepsize = stepsize * 0.5
}
}
if (stepsize < min_step) { print("Line search fails in two-class probability estimates") }
if iter >= max_iter { print("Reaching maximal iterations in two-class probability estimates") }
}
return (A: A, B: B)
}
func svrProbability(_ data: MLCombinedDataSet) -> Double
{
// Run cross-validation without calculating probabilities
let oldProbabilityFlag = probability
probability = false
var ymv = crossValidation(data, numberOfFolds: 5)
probability = oldProbabilityFlag
// Calculate the final probability estimate
var mae = 0.0
for i in 0..<data.size {
do {
let outputs = try data.getOutput(i)
ymv[i] = outputs[0] - ymv[i]
}
catch {
ymv[i] = 0.0 // Error getting output from data set
}
mae += fabs(ymv[i])
}
mae /= Double(data.size)
let std = sqrt(2 * mae * mae)
var count=0
mae=0.0
for i in 0..<data.size {
if (fabs(ymv[i]) > 5*std) {
count += 1
}
else {
mae += fabs(ymv[i])
}
}
mae /= Double(data.size-count)
print("Prob. model for test data: target value = predicted value + z, z: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma= \(mae)")
return mae
}
open func predictValues(_ data: MLCombinedDataSet)
{
// Get the support vector start index for each class
var coeffStart = [0]
for index in 0..<numClasses-1 {
coeffStart.append(coeffStart[index] + supportVectorCount[index])
}
// Determine each value based on the input
for index in 0..<data.size {
do {
let inputs = try data.getInput(index)
switch (type) {
// Predict for one-class classification or regression
case .oneClassSVM, .ϵSVMRegression, .νSVMRegression:
var sum = 0.0
for i in 0..<totalSupportVectors {
let kernelValue = Kernel.calcKernelValue(kernelParams, x: inputs, y: supportVector[i])
sum += coefficients[0][i] * kernelValue
}
sum -= ρ[0]
do {
try data.setOutput(index, newOutput: [sum])
}
catch { break }
if (type == .oneClassSVM) {
try data.setClass(index, newClass: ((sum>0) ? 1: -1))
}
break
// Predict for classification
case .c_SVM_Classification, .ν_SVM_Classification:
// Get the kernel value for each support vector at the input value
var kernelValue: [Double] = []
for sv in 0..<totalSupportVectors {
kernelValue.append(Kernel.calcKernelValue(kernelParams, x: inputs, y: supportVector[sv]))
}
// Allocate vote space for the classification
var vote = [Int](repeating: 0, count: numClasses)
// Initialize the decision value storage in the data set
var decisionValues: [Double] = []
// Get the seperation info between each class pair
var permutation = 0
for i in 0..<numClasses {
for j in i+1..<numClasses {
var sum = 0.0
for k in 0..<supportVectorCount[i] {
sum += coefficients[j-1][coeffStart[i]+k] * kernelValue[coeffStart[i]+k]
}
for k in 0..<supportVectorCount[j] {
sum += coefficients[i][coeffStart[j]+k] * kernelValue[coeffStart[j]+k]
}
sum -= ρ[permutation]
decisionValues.append(sum)
permutation += 1
if (sum > 0) {
vote[i] += 1
}
else {
vote[j] += 1
}
}
}
do {
try data.setOutput(index, newOutput: decisionValues)
}
catch { break }
// Get the most likely class, and set it
var maxIndex = 0
for index in 1..<numClasses {
if (vote[index] > vote[maxIndex]) { maxIndex = index }
}
try data.setClass(index, newClass: labels[maxIndex])
break
}
}
catch {
// Error getting inputs
}
}
}
open func predictOne(_ inputs: [Double]) -> Double
{
// Get the support vector start index for each class
var coeffStart = [0]
for index in 0..<numClasses-1 {
coeffStart.append(coeffStart[index] + supportVectorCount[index])
}
switch (type) {
// Predict for one-class classification or regression
case .oneClassSVM, .ϵSVMRegression, .νSVMRegression:
var sum = 0.0
for i in 0..<totalSupportVectors {
let kernelValue = Kernel.calcKernelValue(kernelParams, x: inputs, y: supportVector[i])
sum += coefficients[0][i] * kernelValue
}
sum -= ρ[0]
if (type == .oneClassSVM) {
return (sum>0) ? 1.0: -1.0
}
return sum
// Predict for classification
case .c_SVM_Classification, .ν_SVM_Classification:
// Get the kernel value for each support vector at the input value
var kernelValue: [Double] = []
for sv in 0..<totalSupportVectors {
kernelValue.append(Kernel.calcKernelValue(kernelParams, x: inputs, y: supportVector[sv]))
}
// Allocate vote space for the classification
var vote = [Int](repeating: 0, count: numClasses)
// Initialize the decision value storage in the data set
var decisionValues: [Double] = []
// Get the seperation info between each class pair
var permutation = 0
for i in 0..<numClasses {
for j in i+1..<numClasses {
var sum = 0.0
for k in 0..<supportVectorCount[i] {
sum += coefficients[j-1][coeffStart[i]+k] * kernelValue[coeffStart[i]+k]
}
for k in 0..<supportVectorCount[j] {
sum += coefficients[i][coeffStart[j]+k] * kernelValue[coeffStart[j]+k]
}
sum -= ρ[permutation]
decisionValues.append(sum)
permutation += 1
if (sum > 0) {
vote[i] += 1
}
else {
vote[j] += 1
}
}
}
// Get the most likely class, and return it
var maxIndex = 0
for index in 1..<numClasses {
if (vote[index] > vote[maxIndex]) { maxIndex = index }
}
return Double(labels[maxIndex])
}
}
open func predictOneFromBinaryClass(_ inputs: [Double]) -> Int
{
let sum = predictOne(inputs)
if (sum > 0) {
return labels[0]
}
else {
return labels[1]
}
}
open func predictProbability(_ inputs: [Double]) -> Double
{
if ((type == .c_SVM_Classification || type == .ν_SVM_Classification) && probabilityA.count > 0 && probabilityB.count > 0) {
let data = DataSet(dataType: .classification, inputDimension: inputs.count, outputDimension: 1)
do {
try data.addDataPoint(input: inputs, output: [0.0])
}
catch {
print("dimension error on inputs")
}
predictValues(data)
let minProbability = 1e-7
var pairwiseProbability = [[Double]](repeating: [], count: numClasses)
for i in 0..<numClasses { pairwiseProbability[i] = [Double](repeating: 0.0, count: numClasses) }
var k = 0
for i in 0..<numClasses-1 {
for j in i+1..<numClasses {
do {
let outputs = try data.getOutput(k)
pairwiseProbability[i][j] = min(max(SVMModel.sigmoidPredict(outputs[0], probA: probabilityA[k], probB: probabilityB[k]), minProbability), 1.0-minProbability)
pairwiseProbability[j][i] = 1.0 - pairwiseProbability[i][j]
}
catch {
break // error in getting outputs
}
k += 1
}
}
let probabilityEstimates = multiclassProbability(pairwiseProbability)
var maxIndex = 0
for i in 1..<numClasses {
if (probabilityEstimates[i] > probabilityEstimates[maxIndex]) {
maxIndex = i
}
}
return Double(labels[maxIndex])
}
else {
return predictOne(inputs)
}
}
class func sigmoidPredict(_ decisionValue: Double, probA: Double, probB: Double) -> Double
{
let fApB = decisionValue * probA + probB
// 1-p used later; avoid catastrophic cancellation
if (fApB >= 0) {
return exp(-fApB) / (1.0 + exp(-fApB))
}
else {
return 1.0 / (1.0 + exp(fApB))
}
}
// Method 2 from the multiclass_prob paper by Wu, Lin, and Weng
func multiclassProbability(_ probabilityPairs: [[Double]]) -> [Double]
{