Created
May 6, 2019 21:45
-
-
Save Micrified/daedbe1854858d84d86bd63d1614e231 to your computer and use it in GitHub Desktop.
KNN Classifier in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private String classify_accelerometer_sample (ArrayList<AccelerometerDataPoint> sample) { | |
double mean = 0.0, variance = 0.0; | |
int index_nearest_neighbour; | |
// Compute the mean Z-axis value for the sample | |
for (AccelerometerDataPoint d : sample) { | |
mean = mean + d.getAz(); | |
} | |
mean = mean / (double)acc_sample_window; | |
// Compute the variance across the Z-axis values | |
for (AccelerometerDataPoint d : sample) { | |
variance = variance + ((d.getAz() - mean) * (d.getAz() - mean)); | |
} | |
variance = variance / ((double)acc_sample_window - 1); | |
// Create a sorted list of training points based on difference in variance | |
ArrayList<AccelerometerTrainingPoint> sorted = new ArrayList<AccelerometerTrainingPoint>(); | |
// For all elements in the training points | |
for (AccelerometerTrainingPoint p : this.acc_train_data) { | |
// Find the smallest one | |
index_nearest_neighbour = 0; | |
for (int i = 0; i < this.acc_train_data.size(); ++i) { | |
double candidate_variance = this.acc_train_data.get(i).getZ_var(); | |
double current_variance = this.acc_train_data.get(index_nearest_neighbour).getZ_var(); | |
double candidate_difference = Math.abs(candidate_variance - variance); | |
double current_difference = Math.abs(current_variance - variance); | |
if (candidate_difference < current_difference) { | |
index_nearest_neighbour = i; | |
} | |
} | |
// Append it to the arraylist | |
sorted.add(this.acc_train_data.get(index_nearest_neighbour)); | |
} | |
// For the first K items training data points in the arraylist, count the number of walk/standing | |
int walking = 0; | |
int standing = 0; | |
for (int i = 0; i < this.acc_k_size; ++i) { | |
AccelerometerTrainingPoint p = sorted.get(i); | |
if (p.getLabel() == 0) { | |
walking++; | |
} else { | |
standing++; | |
} | |
} | |
if (walking > standing) { | |
return "walking"; | |
} else { | |
return "standing"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment