1.原程序为重复n次,并将已经输出的点筛去,以筛选出最近的n个点
为了减小计算量,以插入排序将所有值排序,则可以直接在序列中选择最小的n个点
/**
* *******************************
* Compute the nearest k neighbors. Select one neighbor in each scan. In
* fact we can only once. You may implement it by yourself.
*
* @param paraCurrent current instance. We are comparing it with all others.
* @return the indices of the nearest instances.
* *******************************
*/
public int[] computeNearests(int paraCurrent) {
int[] resultNearests = new int[numNeighbors];
boolean[] tempSelected = new boolean[trainingSet.length];
double tempDistance;
double tempMinimalDistance;
int tempMinimalIndex = 0;
int j;
int[] searchTable = new int[trainingSet.length];
double[] distance = new double[trainingSet.length];
//计算所有点的distance
for (int i = 0; i < trainingSet.length; i++) {
searchTable[i] = i;
distance[i] = distance(paraCurrent, trainingSet[i]);
}//of for i
//对distance进行插入排序,同时设置searchTable跟踪该distance原位置
for (int i = 1; i < trainingSet.length; i++) {
tempDistance = distance[i];
for (j = i - 1; j >= 0 && distance[j] > tempDistance;j--) {
distance[j + 1] = distance[j];
searchTable[j + 1] = searchTable[j];
}//of for j
distance[j + 1] = tempDistance;
searchTable[j + 1] = i;
}//of for i
//输出n个最小值
for (int i = 0; i < numNeighbors; i++) {
resultNearests[i] = trainingSet[searchTable[i]];
}//of for i
System.out.println("The nearest of " + paraCurrent + " are: " + Arrays.toString(resultNearests));
return resultNearests;
}//of computeNearests
2.setDistanceMeasure
public void setDistanceMeasure(int distanceMeasure) {
this.distanceMeasure = distanceMeasure;
}//setDistanceMeasure
3.setNumNeighbors
public void setNumNeighbors(int numNeighbors) {
this.numNeighbors = numNeighbors;
}//setDistanceMeasure
|