@Override public double distance(NumericVectorFeature x, NumericVectorFeature y) { double[] vector1 = x.getValue(); double[] vector2 = y.getValue(); double d = 0; for (int i = 0; i < vector1.length; i++) { d += Math.pow(vector1[i] - vector2[i], 2); } // return euclidean distance return Math.sqrt( d / (double)vector1.length ); } }
@Override public void add(NumericVectorFeature feature) { double addedWeight = feature.getWeight(); double newWeight = weight + addedWeight; if (meanVector == null) { if (feature.getValue() != null) { meanVector = feature.getValue().clone(); weight = addedWeight; } } else { if (feature.getValue() != null) { // incrementally revise the centroid vector for (int i=0; i < meanVector.length; i++) { meanVector[i] = (meanVector[i] * weight + feature.getValue()[i] * addedWeight) / newWeight; } weight = newWeight; } } }
@Override public void remove(NumericVectorFeature feature) { double removedWeight = feature.getWeight(); double newWeight = weight - removedWeight; if (0.0 == weight) return; // decrement centroid vector for (int i=0; i < meanVector.length; i++) { meanVector[i] = (meanVector[i] * weight - feature.getValue()[i] * removedWeight) / newWeight; } weight = newWeight; }