数据修复:使用 KNN 算法填充缺失值

本文介绍了使用 KNN 算法修复 Excel 数据缺失值的方法。代码示例演示了如何读取 Excel 文件、识别缺失值并利用 KNN 算法进行填充。

数据示例

日期 | 数据 ------- | -------- 2021/05/09 10:00 | 26.14 2022/09/02 10:00 | 24.11 2022/09/03 10:00 | 26.62 2022/09/03 10:00 | 25.56 2022/09/04 08:00 | 25.56 2022/09/05 08:00 | 25.37 2022/09/06 08:00 | 2022/09/08 08:00 | 29.01 2022/09/15 08:00 | 29.04 2022/09/22 08:00 | 29.03 2022/10/02 08:00 | 28.96 2022/10/09 08:00 | 28.98 2022/10/15 08:00 | 2022/10/20 08:00 | 29.07 2022/10/28 08:00 | 28.98 2022/11/08 08:00 | 28.95 2022/11/16 08:00 | 29.07 2022/11/24 08:00 | 29.02 2022/12/02 08:00 | 29.26 2022/12/10 08:00 | 2022/12/18 08:00 | 2022/12/26 08:00 | 2023/01/06 08:00 | 29.16 2023/01/13 08:00 | 29.22 2023/01/19 08:00 | 29.29 2023/01/26 08:00 | 29.27 2023/02/04 08:00 | 29.27 2023/02/15 08:00 | 29.31 2023/02/22 08:00 | 29.00 2023/03/03 08:00 | 29.07 2023/03/12 08:00 | 29.74 2023/03/20 08:00 | 29.74 2023/03/26 08:00 | 29.55 2023/04/04 08:00 | 29.74 2023/04/15 08:00 | 29.74 2023/04/22 08:00 | 29.52 2023/04/23 08:00 | 29.50 2023/04/24 08:00 | 29.51 2023/04/25 08:00 | 2023/04/26 08:00 | 29.54 2023/04/27 08:00 | 29.50 2023/04/28 08:00 | 29.48 2023/04/29 08:00 | 29.50 2023/04/30 08:00 | 29.49 2023/05/01 08:00 | 2023/05/02 08:00 | 29.46 2023/05/03 08:00 | 29.50 2023/05/04 08:00 | 29.49 2023/05/05 08:00 | 29.51 2023/05/06 08:00 | 29.47 2023/05/07 08:00 | 29.50 2023/05/09 08:00 | 29.51 2023/05/10 08:00 | 29.49 2023/05/11 08:00 | 29.51 2023/05/12 08:00 | 2023/05/13 08:00 | 29.48 2023/05/14 08:00 | 29.55 2023/05/15 08:00 | 29.48 2023/05/16 08:00 | 29.54 2023/05/17 08:00 | 29.51 2023/05/18 08:00 | 29.56 2023/05/19 08:00 | 29.51 2023/05/20 08:00 | 29.49 2023/05/21 08:00 | 29.52 2023/05/22 08:00 | 29.56 2023/05/24 08:00 | 29.59 2023/05/25 08:00 | 29.51 2023/05/26 08:00 | 29.48 2023/05/27 08:00 | 29.54 2023/05/28 08:00 | 29.51 2023/05/29 08:00 | 29.54 2023/05/30 08:00 | 29.50 2023/05/31 08:00 | 29.50

代码示例

package 数据修复;

import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class knn01 {

    public static void main(String[] args) {
        // 定义输入文件和输出文件的路径
        String inputFile = "input.xlsx";
        try (Workbook workbook = WorkbookFactory.create(new FileInputStream(inputFile))) { // 使用工作簿工厂创建 Excel 工作簿
            Sheet sheet = workbook.getSheet("P1"); // 获取 P1 工作表
            DecimalFormat df = new DecimalFormat("#.##"); // 创建 Decimal 格式化器,用于保留两位小数
            // 创建新的工作表
            String newSheetName = "P1-1";
            int sheetIndex = workbook.getSheetIndex(newSheetName);
            Sheet newDataSheet;
            if (sheetIndex >= 0) {
                workbook.removeSheetAt(sheetIndex);
            }
            newDataSheet = workbook.createSheet(newSheetName);
            // 复制原工作表的数据到新的工作表
            for (int i = 0; i <= sheet.getLastRowNum(); i++) {
                Row oldRow = sheet.getRow(i);
                Row newRow = newDataSheet.createRow(i);
                if (oldRow != null) {
                    for (int j = 0; j < oldRow.getLastCellNum(); j++) {
                        Cell oldCell = oldRow.getCell(j);
                        Cell newCell = newRow.createCell(j);
                        if (oldCell != null) {
                            if(oldCell.getCellType() == CellType.STRING){
                                newCell.setCellValue(oldCell.getStringCellValue());
                            } else if(oldCell.getCellType() == CellType.NUMERIC){
                                newCell.setCellValue(oldCell.getNumericCellValue());
                            } else if(oldCell.getCellType() == CellType.BOOLEAN){
                                newCell.setCellValue(oldCell.getBooleanCellValue());
                            } else if(oldCell.getCellType() == CellType.FORMULA){
                                newCell.setCellValue(oldCell.getCellFormula());
                            } else if(oldCell.getCellType() == CellType.ERROR){
                                newCell.setCellValue(oldCell.getErrorCellValue());
                            }
                            // 复制原单元格的样式到新单元格
                            CellStyle oldCellStyle = oldCell.getCellStyle();
                            CellStyle newCellStyle = workbook.createCellStyle();
                            newCellStyle.cloneStyleFrom(oldCellStyle);
                            newCell.setCellStyle(newCellStyle);
                        }
                    }
                }
            }
            // 对每一行进行处理
            for (int i = 1; i <= newDataSheet.getLastRowNum(); i++) {
                Row row = newDataSheet.getRow(i); // 获取行对象
                if (row != null) {
                    Cell cell = row.getCell(1); // 获取第二列单元格
                    if (cell == null || cell.getCellType() == CellType.BLANK) { // 判断单元格是否为空或者空白
                        double avg = calculateKNN(newDataSheet, i, 1); // 计算KNN邻近算法填充的值
                        if (avg > 0) { // 如果填充的值大于 0
                            cell = row.createCell(1); // 创建新的单元格
                            cell.setCellValue(Double.parseDouble(df.format(avg))); // 将填充的值填入单元格
                            // 设置单元格的数据类型为数值类型
                            CellStyle cellStyle = workbook.createCellStyle();
                            DataFormat dataFormat = workbook.createDataFormat();
                            cellStyle.setDataFormat(dataFormat.getFormat("0.00"));
                            cell.setCellStyle(cellStyle);
                        }
                    }
                }
            }
            // 将工作簿写入输入文件
            FileOutputStream outputStream = new FileOutputStream(inputFile);
            workbook.write(outputStream);
            outputStream.close();
            System.out.println("Data filling completed."); // 输出信息
        } catch (Exception e) { // 捕获异常
            e.printStackTrace();
        }
    }

    // 计算KNN邻近算法填充的值
    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; // 总和
            int count = 0; // 计数器
            for (int i = 0; i < k && i < distances.size(); i++) { // 对前 k 个最近的邻居进行处理
                double value = data.get(distances.indexOf(distances.get(i))); // 获取对应的值
                sum += value; // 累加值
                count++; // 计数器加 1
            }
            if (count > 0) { // 如果计数器大于 0
                return sum / count; // 返回平均值
            }
        }
        return 0; // 如果不存在数据或缺失值小于等于0,返回 0
    }

    // 解析日期
    private static Date parseDate(String dateString) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); // 创建日期格式化器
        try {
            return dateFormat.parse(dateString); // 解析日期
        } catch (ParseException e) { // 捕获异常
            e.printStackTrace();
            return null; // 返回 null
        }
    }

}

运行结果

运行代码后,Excel 文件中缺失值的单元格将被填充为 KNN 算法计算出的值。

可能出现的问题

如果 KNN 算法填充的地方仍然是空白,可能是因为以下原因:

  1. 数据不满足 KNN 算法的条件:KNN 算法需要有足够的数据点来计算邻居的距离和填充缺失值。如果数据点太少,或者缺失值周围没有足够的邻居数据点,KNN 算法可能无法填充缺失值。

  2. 数据的格式不正确:KNN 算法需要的数据格式可能与实际数据的格式不匹配。请确保数据的格式正确,例如缺失值应该是数值型的。

解决办法

为了解决这个问题,您可以尝试以下方法:

  1. 检查数据的完整性:确保数据集中有足够的数据点,并且缺失值周围有足够的邻居数据点。

  2. 检查数据的格式:确保数据的格式正确,例如缺失值应该是数值型的。

  3. 调整 k 值:尝试调整 k 值,增加或减少最近邻居的数量,看看是否能够填充缺失值。

  4. 检查数据的范围:确保数据的范围合理,不要存在异常值或者极端值,这可能会影响 KNN 算法的结果。

如果上述方法仍然无法解决问题,可能需要进一步检查代码逻辑或者数据本身的问题。

希望本文能够帮助您理解如何使用 KNN 算法修复 Excel 数据缺失值。如果您有任何问题,请随时在评论区提问。

数据修复:使用 KNN 算法填充缺失值

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

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