-
Notifications
You must be signed in to change notification settings - Fork 87
/
Validation.swift
249 lines (219 loc) · 10.7 KB
/
Validation.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
//
// Validation.swift
// AIToolbox
//
// Created by Kevin Coble on 4/24/16.
// Copyright © 2016 Kevin Coble. All rights reserved.
//
import Foundation
public enum ValidationError: Error {
case computationError
}
/// Class for using validation techniques for model/parameter selection
open class Validation
{
let validationType : DataSetType
var classifiers : [Classifier] = []
var regressors : [Regressor] = []
var validationTestResults : [Double] = [] // Array of average scores on tests for each model
var timeout: Int64 = 1000000000 * 60 * 60 // In nanoseconds, default of 1 hour
public init(type: DataSetType)
{
validationType = type
}
open func addModel(_ model: Classifier) throws
{
if (validationType == .regression) { throw MachineLearningError.modelNotRegression }
classifiers.append(model)
}
open func addModel(_ model: Regressor) throws
{
if (validationType == .classification) { throw MachineLearningError.modelNotClassification }
regressors.append(model)
}
/// Method to split data into train and test sets, then do basic validation
/// Returns model index that did the best. Scores in validationTestResults
/// Model should probably be re-trained on all data afterwards
/// Uses Grand-Central-Dispatch to run in parallel
open func simpleValidation(_ data: DataSet, fractionForTest: Double) throws -> Int
{
// Get the size of the training and testing sets
let testSize = Int(fractionForTest * Double(data.size))
if (testSize < 1) { throw MachineLearningError.notEnoughData }
if (testSize == data.size) { throw MachineLearningError.notEnoughData }
// Split the data into a training and a testing set
let indices = data.getRandomIndexSet()
let testData = DataSet(fromDataSet: data, withEntries: indices[0..<testSize])!
let trainData = DataSet(fromDataSet: data, withEntries: indices[testSize..<data.size])!
// Get a concurrent GCD queue to run this all in
let queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default)
// Get a GCD group so we can know when all models are done
let group = DispatchGroup();
// Train and test each model
if (validationType == .regression) {
validationTestResults = [Double](repeating: 0.0, count: regressors.count)
for modelIndex in 0..<regressors.count {
queue.async(group: group) {
do {
try self.regressors[modelIndex].trainRegressor(trainData)
self.validationTestResults[modelIndex] = try self.regressors[modelIndex].getTotalAbsError(testData)
}
catch {
self.validationTestResults[modelIndex] = Double.infinity // failure needs to be checked later
}
}
}
// Wait for the models to finish calculating
let timeoutTime = DispatchTime.now() + Double(timeout) / Double(NSEC_PER_SEC)
if (group.wait(timeout: timeoutTime) != DispatchTimeoutResult.success) {
throw MachineLearningError.operationTimeout
}
// Rescale errors to have minimum error = 1.0
var minError = Double.infinity
for error in validationTestResults {
if (error == Double.infinity) { throw ValidationError.computationError }
if (error < minError) { minError = error }
}
for modelIndex in 0..<regressors.count {
if (validationTestResults[modelIndex] == 0.0) {
validationTestResults[modelIndex] = 1.0
}
else {
validationTestResults[modelIndex] = 1.0 - ((validationTestResults[modelIndex] - minError) / validationTestResults[modelIndex])
}
}
}
else {
validationTestResults = [Double](repeating: 0.0, count: classifiers.count)
for modelIndex in 0..<classifiers.count {
queue.async(group: group) {
do {
try self.classifiers[modelIndex].trainClassifier(trainData)
self.validationTestResults[modelIndex] = try self.classifiers[modelIndex].getClassificationPercentage(testData)
}
catch {
self.validationTestResults[modelIndex] = Double.infinity // failure needs to be checked later
}
}
}
// Wait for the models to finish calculating
let timeoutTime = DispatchTime.now() + Double(timeout) / Double(NSEC_PER_SEC)
if (group.wait(timeout: timeoutTime) != DispatchTimeoutResult.success) {
throw MachineLearningError.operationTimeout
}
// Check for an error during multithreading
for error in validationTestResults {
if (error == Double.infinity) { throw ValidationError.computationError }
}
}
// Find the model that did best
var bestResult = -Double.infinity
var bestIndex = -1
for modelIndex in 0..<validationTestResults.count {
if (validationTestResults[modelIndex] > bestResult) {
bestResult = validationTestResults[modelIndex]
bestIndex = modelIndex
}
}
return bestIndex
}
/// Method to split data into N parcels, then train on N-1 parcels, test on last parcel, then repeat for all permutations
/// If N is set to dataset size, this turns into 'leave-one-out' cross validation
/// Returns model that did the best. Model should probably be re-trained on all data afterwards
/// Uses Grand-Central-Dispatch to run in parallel
open func NFoldCrossValidation(_ data: DataSet, numberOfFolds: Int) throws -> Int
{
if (numberOfFolds > data.size) { throw MachineLearningError.notEnoughData }
// Get a concurrent GCD queue to run this all in
let queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default)
// Get a GCD group so we can know when all models are done
let group = DispatchGroup();
// Randomize the points into the different folds
let indices = data.getRandomIndexSet()
var startIndex = 0
// Initialize the results to 0
validationTestResults = [Double](repeating: 0.0, count: regressors.count)
// Do for each fold
for fold in 0..<numberOfFolds {
// Get the number of points in this fold
let foldSize = (data.size - startIndex) / (numberOfFolds - fold)
// Split the data into a training and a testing set
let trainData = DataSet(dataType : data.dataType, inputDimension : data.inputDimension, outputDimension : data.outputDimension)
if (fold != 0) {
try trainData.includeEntries(fromDataSet: data, withEntries: indices[0..<startIndex])
}
let testData = DataSet(fromDataSet: data, withEntries: indices[startIndex..<startIndex+foldSize])!
if (fold != numberOfFolds-1) {
try trainData.includeEntries(fromDataSet: data, withEntries: indices[startIndex+foldSize..<data.size])
}
startIndex += foldSize
// Train and test each model with this fold
if (validationType == .regression) {
for modelIndex in 0..<regressors.count {
queue.async(group: group) {
do {
try self.regressors[modelIndex].trainRegressor(trainData)
self.validationTestResults[modelIndex] += try self.regressors[modelIndex].getTotalAbsError(testData)
}
catch {
self.validationTestResults[modelIndex] = Double.infinity // failure needs to be checked later
}
}
}
}
else {
for modelIndex in 0..<classifiers.count {
queue.async(group: group) {
do {
try self.classifiers[modelIndex].trainClassifier(trainData)
self.validationTestResults[modelIndex] += try self.classifiers[modelIndex].getClassificationPercentage(testData)
}
catch {
self.validationTestResults[modelIndex] = Double.infinity // failure needs to be checked later
}
}
}
}
// Wait for the models to finish calculating before the next fold
let timeoutTime = DispatchTime.now() + Double(timeout) / Double(NSEC_PER_SEC)
if (group.wait(timeout: timeoutTime) != DispatchTimeoutResult.success) {
throw MachineLearningError.operationTimeout
}
}
// Check for an error during multithreading
for error in validationTestResults {
if (error == Double.infinity) { throw ValidationError.computationError }
}
// Scale the validation results
if (validationType == .regression) {
var minError = Double.infinity
for error in validationTestResults {
if (error == Double.infinity) { throw ValidationError.computationError }
if (error < minError) { minError = error }
}
for modelIndex in 0..<regressors.count {
if (validationTestResults[modelIndex] == 0.0) {
validationTestResults[modelIndex] = 1.0
}
else {
validationTestResults[modelIndex] = 1.0 - ((validationTestResults[modelIndex] - minError) / validationTestResults[modelIndex])
}
}
}
else {
for modelIndex in 0..<classifiers.count {
validationTestResults[modelIndex] /= Double(numberOfFolds)
}
}
// Find the model that did best
var bestResult = -Double.infinity
var bestIndex = -1
for modelIndex in 0..<validationTestResults.count {
if (validationTestResults[modelIndex] > bestResult) {
bestResult = validationTestResults[modelIndex]
bestIndex = modelIndex
}
}
return bestIndex
}
}