day52

这段代码实现了一个K近邻(KNN)算法的简化版本,通过插入排序找到训练集中距离输入点最近的n个点。首先计算所有点与输入点的距离,然后对距离进行排序,最后返回前n个最近的点的索引。此外,还提供了设置距离度量和邻居数量的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值