KNN算法实现Excel数据修复

本文介绍如何使用KNN算法对Excel数据进行修复,并提供Java代码示例。

代码示例javaimport 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        }    }

}

KNN算法填充值相同的问题

在代码中,计算KNN邻近算法填充的值时,对于缺失值,通过计算与其他数据的距离,选择最近的k个邻居,并计算其平均值作为填充值。如果填充的值都是一样的,可能是因为k个邻居的值都相同,或者数据中存在很多相同的值。

解决办法

  1. 调整k的值: 尝试选择更大或更小的k值,看是否能够得到不同的填充值。如果k值较小,可能会导致填充值受到局部数据的影响;如果k值较大,可能会导致填充值过于平均化。

  2. 考虑使用加权平均值: 在计算邻居的平均值时,可以考虑对每个邻居的值进行加权。可以根据距离远近给予不同的权重,距离越近的邻居权重越大,距离越远的邻居权重越小。

  3. 考虑使用其他的填充算法: 如果KNN算法无法得到满意的填充值,可以尝试其他的数据修复算法,如线性插值、多项式插值等。

  4. 检查数据是否存在问题: 检查数据中是否存在重复值或异常值,可能会导致填充值出现重复的情况。

通过尝试以上几个办法,可以帮助解决KNN补充的数值都一样的问题。

KNN算法实现Excel数据修复

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

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