Skip to content

Instantly share code, notes, and snippets.

@Micrified
Created May 4, 2020 18:47
Show Gist options
  • Save Micrified/13378b75b45889beb450420eebcb8d8d to your computer and use it in GitHub Desktop.
Save Micrified/13378b75b45889beb450420eebcb8d8d to your computer and use it in GitHub Desktop.
// Classifier
public int classify (ArrayList<ScanResult> test_sample)
{
// Number of votes for each of the four cells
int[] cell_count = {0,0,0,0};
// Train if needed (new data may have been added to some cells)
if (training_required) {
train();
}
// Convert the test-sample to a binary hamming code
final ArrayList<Integer> test_code = Cell.makeCode(test_sample, unique_bssids);
// Sort by smallest hamming distance
Collections.sort(training_set, new Comparator() {
public int compare(Object a, Object b) {
TrainingSample x = (TrainingSample)a;
TrainingSample y = (TrainingSample)b;
int h_a = LocationManager.hamming(test_code, x.code);
int h_b = LocationManager.hamming(test_code, y.code);
if (h_a < h_b) {
return -1;
} else {
return 1;
}
}});
// [DEBUG] Comparison is shown
Log.i("CLASSIFY", "Sorted data (by increasing hamming distance)");
for (int i = 0; i < training_set.size(); ++i) {
String test_code_string = Cell.codeToString(test_code);
String compare_code_string = Cell.codeToString(training_set.get(i).code);
System.out.printf("%s vs %s: %d\n", test_code_string, compare_code_string,
hamming(test_code, training_set.get(i).code));
}
// Classify using K-NN (increment cell label if sample belonged to it)
for (int i = 0; i < k; ++i) {
cell_count[training_set.get(i).cell_id]++;
}
// Return the majority vote
if (cell_count[0] > cell_count[1]) {
if (cell_count[2] > cell_count[3]) {
return (cell_count[0] > cell_count[2]) ? 0 : 2;
} else {
return (cell_count[0] > cell_count[3]) ? 0 : 3;
}
} else {
if (cell_count[2] > cell_count[3]) {
return (cell_count[1] > cell_count[2]) ? 1 : 2;
} else {
return (cell_count[1] > cell_count[3]) ? 1 : 3;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment