Skip to content

Commit

Permalink
knn error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
ronan18 committed Feb 14, 2020
1 parent 62d5729 commit d9ec8e9
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 17 deletions.
24 changes: 16 additions & 8 deletions Arrival-iOS2/AppData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import JavaScriptCore
import FirebasePerformance
import FirebaseAnalytics
import FirebaseRemoteConfig
import FirebaseCrashlytics

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
Expand Down Expand Up @@ -291,15 +292,22 @@ class AppData: NSObject, ObservableObject,CLLocationManagerDelegate {
nNeighbors = 1

print(nNeighbors, "knn neighbors")
let knn = KNearestNeighborsClassifier(data: trainingData, labels: labels, nNeighbors: nNeighbors)
if (self.fromStation.abbr != "load") {
print("knn predicting", self.fromStation.abbr)
let predictionLabels = knn.predict([tripToDouble(day: day, hour: hour, fromStation: self.fromStation.abbr)])
print(predictionLabels, "knn prediction labels")
predictionType = predictionLabels.map({ self.stationFromInt(label: $0) })
print(predictionType, "knn prediction type")
priorities[predictionType[0]] = (JSON(priorities)[predictionType[0]].intValue + 100) * 10
do {
let knn = try KNearestNeighborsClassifier(data: trainingData, labels: labels, nNeighbors: nNeighbors)
if (self.fromStation.abbr != "load") {
print("knn predicting", self.fromStation.abbr)
let predictionLabels = try knn.predict([tripToDouble(day: day, hour: hour, fromStation: self.fromStation.abbr)])
print(predictionLabels, "knn prediction labels")
predictionType = predictionLabels.map({ self.stationFromInt(label: $0) })
print(predictionType, "knn prediction type")
priorities[predictionType[0]] = (JSON(priorities)[predictionType[0]].intValue + 100) * 10
}
} catch {
print("crash", error)
Crashlytics.crashlytics().record(error: error)

}

}
do {
try context.save()
Expand Down
33 changes: 24 additions & 9 deletions Arrival-iOS2/KNearestNeighborsClassifier.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,47 @@

import Darwin
import Foundation

enum knnError: Error {
case cantFindMajority
case expectedNN(nNeighbors: Int, dataCount: Int)
case expectedDataCount(dataCount: Int, labelsCount: Int)

}
public class KNearestNeighborsClassifier {

private let data: [[Double]]
private let labels: [Int]
private let nNeighbors: Int

public init(data: [[Double]], labels: [Int], nNeighbors: Int = 3) {
public init(data: [[Double]], labels: [Int], nNeighbors: Int = 3) throws {
self.data = data
self.labels = labels
self.nNeighbors = nNeighbors

guard nNeighbors <= data.count else {
fatalError("Expected `nNeighbors` (\(nNeighbors)) <= `data.count` (\(data.count))")
throw(knnError.expectedNN(nNeighbors: nNeighbors, dataCount: data.count))
}

guard data.count == labels.count else {
fatalError("Expected `data.count` (\(data.count)) == `labels.count` (\(labels.count))")
throw(knnError.expectedDataCount(dataCount: data.count, labelsCount: labels.count))
}
}

public func predict(_ xTests: [[Double]]) -> [Int] {
return xTests.map({
public func predict(_ xTests: [[Double]]) throws -> [Int] {
do {
return try xTests.map({
let knn = kNearestNeighbors($0)
return kNearestNeighborsMajority(knn)
do {
let result = try kNearestNeighborsMajority(knn)
return result
} catch {
throw(error)
}

})
} catch {
throw(error)
}
}

private func distance(_ xTrain: [Double], _ xTest: [Double]) -> Double {
Expand All @@ -56,7 +71,7 @@ public class KNearestNeighborsClassifier {
return Array(kNearestNeighborsSorted)
}

private func kNearestNeighborsMajority(_ knn: [(key: Double, value: Int)]) -> Int {
private func kNearestNeighborsMajority(_ knn: [(key: Double, value: Int)]) throws -> Int {
var labels = [Int : Int]()

for neighbor in knn {
Expand All @@ -69,6 +84,6 @@ public class KNearestNeighborsClassifier {
}
}

fatalError("Cannot find the majority.")
throw(knnError.cantFindMajority)
}
}

0 comments on commit d9ec8e9

Please sign in to comment.