| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package android.gesture; |
| 18 |
|
| 19 |
import java.util.ArrayList; |
| 20 |
import java.util.Collections; |
| 21 |
import java.util.Comparator; |
| 22 |
import java.util.TreeMap; |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
class InstanceLearner extends Learner { |
| 29 |
private static final Comparator<Prediction> sComparator = new Comparator<Prediction>() { |
| 30 |
public int compare(Prediction object1, Prediction object2) { |
| 31 |
double score1 = object1.score; |
| 32 |
double score2 = object2.score; |
| 33 |
if (score1 > score2) { |
| 34 |
return -1; |
| 35 |
} else if (score1 < score2) { |
| 36 |
return 1; |
| 37 |
} else { |
| 38 |
return 0; |
| 39 |
} |
| 40 |
} |
| 41 |
}; |
| 42 |
|
| 43 |
@Override |
| 44 |
ArrayList<Prediction> classify(int sequenceType, int orientationType, float[] vector) { |
| 45 |
ArrayList<Prediction> predictions = new ArrayList<Prediction>(); |
| 46 |
ArrayList<Instance> instances = getInstances(); |
| 47 |
int count = instances.size(); |
| 48 |
TreeMap<String, Double> label2score = new TreeMap<String, Double>(); |
| 49 |
for (int i = 0; i < count; i++) { |
| 50 |
Instance sample = instances.get(i); |
| 51 |
if (sample.vector.length != vector.length) { |
| 52 |
continue; |
| 53 |
} |
| 54 |
double distance; |
| 55 |
if (sequenceType == GestureStore.SEQUENCE_SENSITIVE) { |
| 56 |
distance = GestureUtils.minimumCosineDistance(sample.vector, vector, orientationType); |
| 57 |
} else { |
| 58 |
distance = GestureUtils.squaredEuclideanDistance(sample.vector, vector); |
| 59 |
} |
| 60 |
double weight; |
| 61 |
if (distance == 0) { |
| 62 |
weight = Double.MAX_VALUE; |
| 63 |
} else { |
| 64 |
weight = 1 / distance; |
| 65 |
} |
| 66 |
Double score = label2score.get(sample.label); |
| 67 |
if (score == null || weight > score) { |
| 68 |
label2score.put(sample.label, weight); |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
|
| 73 |
for (String name : label2score.keySet()) { |
| 74 |
double score = label2score.get(name); |
| 75 |
|
| 76 |
predictions.add(new Prediction(name, score)); |
| 77 |
} |
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
Collections.sort(predictions, sComparator); |
| 85 |
|
| 86 |
return predictions; |
| 87 |
} |
| 88 |
} |