package org1;

// 导入必要的库
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

// 定义类名
public class KNNAlgorithm {

    // 定义静态方法
    public static void fillMissingValues(String inputFile, String outputFile) {
        try (Workbook workbook = WorkbookFactory.create(new FileInputStream(inputFile)); // 使用工作簿工厂创建 Excel 工作簿
             FileOutputStream outputStream = new FileOutputStream(outputFile)) { // 创建输出文件
            Sheet sheet = workbook.getSheetAt(0); // 获取 Excel 工作表
            DecimalFormat df = new DecimalFormat('#.##'); // 创建 Decimal 格式化器,用于保留两位小数
            // 对每一行进行处理
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i); // 获取行对象
                if (row != null) {
                    Cell cell = row.getCell(1); // 获取第二列单元格
                    if (cell != null && cell.getCellType() != CellType.BLANK) {
                        // 如果单元格不为空,则跳过
                    } else {
                        double avg = calculateKNN(sheet, i, 1); // 计算KNN邻近算法填充的值
                        if (avg > 0) { // 如果填充的值大于 0
                            if(cell == null){ // 如果单元格为空,则创建新的单元格
                                cell = row.createCell(1);
                            }
                            cell.setCellValue(Double.parseDouble(df.format(avg))); // 将填充的值填入单元格
                        }
                    }
                }
            }
            workbook.write(outputStream); // 将工作簿写入输出文件
            System.out.println('Data filling completed.'); // 输出信息
        } catch (Exception e) { // 捕获异常
            e.printStackTrace();
        }
    }

    // 计算KNN邻近算法填充的值
    private static double calculateKNN(Sheet sheet, int rowIndex, int columnIndex) {
        List<Double> data = new ArrayList<Double>(); // 存储数据
        for (int i = 0; i <= sheet.getLastRowNum(); i++) { // 对每一行进行处理
            Row row = sheet.getRow(i); // 获取行对象
            if (row != null) {
                Cell cell = row.getCell(columnIndex); // 获取指定列的单元格
                if (cell != null && cell.getCellType() == CellType.NUMERIC) {
                    data.add(cell.getNumericCellValue()); // 将数据添加到列表中
                }
            }
        }
        if (data.size() > 0) { // 如果存在数据
            double missingValue = 0; // 缺失值
            Row row = sheet.getRow(rowIndex); // 获取当前行对象
            if (row != null) {
                Cell cell = row.getCell(columnIndex); // 获取指定列的单元格
                if (cell == null || cell.getCellType() == CellType.BLANK) { // 如果单元格为空
                    missingValue = 0; // 缺失值为 0
                } else if (cell.getCellType() == CellType.NUMERIC) {
                    missingValue = cell.getNumericCellValue(); // 缺失值为单元格中的值
                } else if (cell.getCellType() == CellType.STRING) {
                    try {
                        missingValue = Double.parseDouble(cell.getStringCellValue()); // 转换为数字类型
                    } catch (NumberFormatException e) {
                        missingValue = 0; // 转换失败则缺失值为 0
                    }
                }
            }
            if (missingValue > 0) { // 如果缺失值大于 0
                return missingValue; // 直接返回缺失值
            } else {
                List<Double> distances = new ArrayList<Double>(); // 存储距离
                for (double value : data) { // 遍历数据
                    double distance = Math.abs(value - missingValue); // 计算距离
                    distances.add(distance); // 将距离添加到列表中
                }
                Collections.sort(distances, new Comparator<Double>() { // 对距离进行排序
                    @Override
                    public int compare(Double o1, Double o2) {
                        return Double.compare(o1, o2);
                    }
                });
                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; // 返回平均值
                } else {
                    return 0; // 否则返回 0
                }
            }
        } else {
            return 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
        }
    }

    public double[][] fillMissingData(double[][] data) {
        return data;
    }
}

补充说明:

  • 针对 '补充出来的值全是0' 的问题,可能是因为计算 KNN 邻近算法填充的值的逻辑有问题,导致填充的值都是 0。可以尝试调整算法的参数,或者修改算法的实现方式,以提高填充值的准确性。另外,也可以检查数据源是否存在问题,例如数据量太小、数据分布不均匀等因素可能会影响填充值的准确性。
  • 可以考虑使用更复杂的算法,如基于模型的填充方法,例如线性回归、决策树等,来提高填充的精度。
  • 在实际应用中,需要根据具体的数据集和需求选择合适的算法和参数。

希望以上信息能够帮到您!

使用 KNN 算法填充 Excel 中的缺失值

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

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