在代码中,KNN 算法补充的数值都是一样的是因为在计算 KNN 邻近算法填充的值时,只考虑了与缺失值最近的 k 个邻居的平均值,而没有考虑邻居的权重。解决办法是引入权重,根据邻居与缺失值的距离来分配权重,再计算加权平均值。

修改 calculateKNN 方法如下:

private static double calculateKNN(Sheet sheet, int rowIndex, int columnIndex) {
    Row row;
    double missingValue = 0; // 缺失值
    row = sheet.getRow(rowIndex); // 获取当前行对象
    if (row != null) {
        Cell cell = row.getCell(columnIndex); // 获取指定列的单元格
        if (cell != null && cell.getCellType() == CellType.NUMERIC) {
            missingValue = cell.getNumericCellValue(); // 缺失值为单元格中的值
        } else if (cell != null && cell.getCellType() == CellType.STRING) {
            try {
                missingValue = Double.parseDouble(cell.getStringCellValue()); // 转换为数字类型
            } catch (NumberFormatException e) {
                missingValue = 0; // 转换失败则缺失值为 0
            }
        }
    }

    List<Double> data = new ArrayList<>(); // 存储数据
    for (int i = 0; i <= sheet.getLastRowNum(); i++) { // 对每一行进行处理
        row = sheet.getRow(i); // 获取行对象
        if (row != null) {
            Cell cell = row.getCell(columnIndex); // 获取指定列的单元格
            if (cell != null && cell.getCellType() == CellType.NUMERIC) {
                data.add(cell.getNumericCellValue()); // 将数据添加到列表中
            } else if (cell != null && cell.getCellType() == CellType.STRING) {
                try {
                    double value = Double.parseDouble(cell.getStringCellValue()); // 转换为数字类型
                    data.add(value); // 将数据添加到列表中
                } catch (NumberFormatException e) {
                    // 转换失败,忽略该值
                }
            }
        }
    }

    if (data.size() > 0 && missingValue >= 0) { // 如果存在数据且缺失值大于 0
        List<Double> distances = new ArrayList<>(); // 存储距离
        for (double value : data) { // 遍历数据
            double distance = Math.abs(value - missingValue); // 计算距离
            distances.add(distance); // 将距离添加到列表中
        }
        // 对距离进行排序
        distances.sort(Comparator.comparingDouble(o -> o));
        int k = 3; // 取前三个最近的邻居
        double sum = 0; // 总和
        double weightSum = 0; // 权重总和
        for (int i = 0; i < k && i < distances.size(); i++) { // 对前 k 个最近的邻居进行处理
            double value = data.get(distances.indexOf(distances.get(i))); // 获取对应的值
            double weight = 1 / distances.get(i); // 计算权重,距离越近权重越大
            sum += value * weight; // 加权累加值
            weightSum += weight; // 权重累加值
        }
        if (weightSum > 0) { // 如果权重总和大于 0
            return sum / weightSum; // 返回加权平均值
        }
    }
    return 0; // 如果不存在数据或缺失值小于等于0,返回 0
}

通过引入权重,可以更准确地补充缺失值。


原文地址: https://www.cveoy.top/t/topic/fB5j 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录