Excel 数据修复:使用 KNN 算法填充缺失值
Excel 数据修复:使用 KNN 算法填充缺失值
本文将介绍如何使用 Apache POI 库和 KNN 算法来修复 Excel 数据中的缺失值。
问题描述
在处理 Excel 数据时,经常会遇到数据缺失的情况。例如,某个单元格中可能没有数据,或者数据格式错误。为了使数据完整,需要对缺失值进行修复。
KNN 算法简介
KNN(K-Nearest Neighbors)算法是一种常用的机器学习算法,它可以根据样本的特征来预测新的样本的类别或属性。在数据修复中,我们可以利用 KNN 算法来预测缺失值。
代码示例
以下代码示例展示了如何使用 KNN 算法来修复 Excel 数据中的缺失值。代码使用 Apache POI 库来读取和写入 Excel 文件。
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 missingValue = 0;
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;
}
}
double avg = calculateKNN(newDataSheet, i, 1, missingValue); // 计算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, double missingValue) {
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 算法填充数值重复问题
在 calculateKNN 方法中,对于每个缺失值,都会计算与其他所有值的距离,并选择前 k 个最近的邻居来计算平均值。然而,在这个方法中,缺失值是固定的,不会随着行的变化而变化。
解决办法是修改 calculateKNN 方法,将缺失值作为参数传递进来,而不是固定的值。具体的修改如下:
- 修改 calculateKNN 方法的参数列表,添加一个 double 类型的 missingValue 参数。
- 在方法中,将缺失值的获取改为使用传入的 missingValue 参数,而不是固定的值。
- 在 main 方法中调用 calculateKNN 方法时,将缺失值作为参数传递进去。
修改后的代码如下:
// 计算KNN邻近算法填充的值
private static double calculateKNN(Sheet sheet, int rowIndex, int columnIndex, double missingValue) {
// 省略部分代码...
}
// 在main方法中调用calculateKNN方法时,传入缺失值作为参数
double avg = calculateKNN(newDataSheet, i, 1, missingValue);
这样修改后,每个缺失值都会根据当前行的情况进行计算,而不是使用固定的值。
总结
本文介绍了如何使用 Apache POI 库和 KNN 算法来修复 Excel 数据中的缺失值。文章详细阐述了 KNN 算法的实现原理和代码示例,并提供了解决 KNN 算法填充数值重复问题的方案。希望本文能帮助您更好地理解和应用 KNN 算法。
注意
本文提供的代码示例仅供参考,实际应用中可能需要根据具体情况进行调整。
原文地址: https://www.cveoy.top/t/topic/fB5C 著作权归作者所有。请勿转载和采集!