KNN 算法填充缺失值并生成折线图
// 导入必要的库 package org.example;
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.HashMap; // 用于存储每个月的数据组数 import java.util.List; // 用于存储数据 import java.util.Map; // 用于存储每个月的数据组数
import org.apache.poi.ss.usermodel.Cell; // Excel 单元格 import org.apache.poi.ss.usermodel.CellType; // Excel 单元格类型 import org.apache.poi.ss.usermodel.Row; // Excel 行 import org.apache.poi.ss.usermodel.Sheet; // Excel 工作表 import org.apache.poi.ss.usermodel.Workbook; // Excel 工作簿 import org.apache.poi.ss.usermodel.WorkbookFactory; // Excel 工作簿工厂 import org.apache.poi.xssf.usermodel.XSSFChart; // Excel 折线图 import org.apache.poi.xssf.usermodel.XSSFDrawing; // Excel 图形 import org.apache.poi.xssf.usermodel.XSSFSheet; // Excel 工作表 import org.apache.poi.xssf.usermodel.XSSFWorkbook; // Excel 工作簿
public class knn {
public static void main(String[] args) {
// 定义输入文件和输出文件的路径
String inputFile = 'input.xlsx';
String outputFile = 'output1.xlsx';
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))); // 将填充的值填入单元格
}
}
}
}
// 创建新的工作簿
XSSFWorkbook newWorkbook = new XSSFWorkbook();
// 创建新的工作表
XSSFSheet newSheet = newWorkbook.createSheet();
// 存储每个月的数据组数
Map<String, Integer> monthDataCount = new HashMap<String, Integer>();
// 对每一行进行处理
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i); // 获取行对象
if (row != null) {
Cell cell = row.getCell(0); // 获取第一列单元格
if (cell != null && cell.getCellType() == CellType.STRING) {
// 解析日期
Date date = parseDate(cell.getStringCellValue());
if (date != null) {
// 获取月份
SimpleDateFormat monthFormat = new SimpleDateFormat('yyyy/MM');
String month = monthFormat.format(date);
// 计算每个月的数据组数
if (monthDataCount.containsKey(month)) {
monthDataCount.put(month, monthDataCount.get(month) + 1);
} else {
monthDataCount.put(month, 1);
}
// 获取第二列单元格
Cell valueCell = row.getCell(1);
if (valueCell != null && valueCell.getCellType() == CellType.NUMERIC) {
// 创建新的行
Row newRow = newSheet.createRow(i);
// 复制日期单元格
Cell newDateCell = newRow.createCell(0);
newDateCell.setCellValue(date);
// 复制数值单元格
Cell newValueCell = newRow.createCell(1);
newValueCell.setCellValue(valueCell.getNumericCellValue());
}
}
}
}
}
// 对每个月的数据进行补充
for (String month : monthDataCount.keySet()) {
int count = monthDataCount.get(month);
if (count < 5) {
// 解析月份
SimpleDateFormat monthFormat = new SimpleDateFormat('yyyy/MM');
Date date = monthFormat.parse(month);
// 获取当前月份的最后一天
SimpleDateFormat dayFormat = new SimpleDateFormat('yyyy/MM/dd');
Date lastDay = dayFormat.parse(month + '/01');
lastDay.setMonth(lastDay.getMonth() + 1);
lastDay.setDate(lastDay.getDate() - 1);
// 获取当前月份的时间规律
List<Date> pattern = getDatePattern(date, lastDay, count);
// 对时间规律进行处理
for (Date d : pattern) {
// 创建新的行
Row newRow = newSheet.createRow(newSheet.getLastRowNum() + 1);
// 复制日期单元格
Cell newDateCell = newRow.createCell(0);
newDateCell.setCellValue(d);
// 复制数值单元格
Cell newValueCell = newRow.createCell(1);
newValueCell.setCellValue(calculateKNN(sheet, d, 1));
}
}
}
// 创建折线图
XSSFDrawing drawing = newSheet.createDrawingPatriarch();
XSSFChart chart = drawing.createChart(drawing.createAnchor(0, 0, 0, 0, 7, 1, 17, 15));
// 设置图表类型为折线图
chart.getCTChart().getPlotArea().getLineChartArray(0).addNewSmooth().setVal(true);
// 设置 X 轴为日期类型
chart.getCTChart().getPlotArea().getCatAxArray(0).addNewAxId().setVal(123456);
chart.getCTChart().getPlotArea().getCatAxArray(0).addNewScaling().addNewOrientation().setVal(org.openxmlformats.schemas.drawingml.x2006.chart.STOrientation.MIN_MAX);
chart.getCTChart().getPlotArea().getCatAxArray(0).addNewDelete().setVal(false);
chart.getCTChart().getPlotArea().getCatAxArray(0).addNewAxPos().setVal(org.openxmlformats.schemas.drawingml.x2006.chart.STAxPos.B);
chart.getCTChart().getPlotArea().getCatAxArray(0).addNewCrossAx().setVal(123457);
chart.getCTChart().getPlotArea().addNewLayout();
chart.getCTChart().getPlotArea().getLineChartArray(0).addNewMarker().addNewSymbol().setVal(org.openxmlformats.schemas.drawingml.x2006.chart.STMarkerStyle.NONE);
chart.getCTChart().getPlotArea().getLineChartArray(0).addNewMarker().addNewSize().setVal(5);
chart.getCTChart().getPlotArea().getLineChartArray(0).addNewMarker().addNewSpPr().addNewLn().addNewSolidFill().addNewSrgbClr().setVal(new byte[]{(byte) 0, (byte) 0, (byte) 0});
chart.getCTChart().getPlotArea().getLineChartArray(0).addNewSmooth().setVal(true);
chart.getCTChart().getPlotArea().getLineChartArray(0).addNewVaryColors().setVal(false);
chart.getCTChart().getPlotArea().getLineChartArray(0).addNewSer().addNewIdx().setVal(0);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).addNewOrder().setVal(0);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).addNewTx().addNewStrRef().setF('Sheet1!$B$1');
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).addNewSpPr().addNewLn().addNewSolidFill().addNewSrgbClr().setVal(new byte[]{(byte) 0, (byte) 0, (byte) 0});
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).addNewMarker().addNewSymbol().setVal(org.openxmlformats.schemas.drawingml.x2006.chart.STMarkerStyle.NONE);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).addNewMarker().addNewSize().setVal(5);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).addNewSmooth().setVal(true);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).addNewVal().addNewNumRef().setF('Sheet1!$B$2:$B$' + (newSheet.getLastRowNum() + 1));
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).addNewXVal().addNewNumRef().setF('Sheet1!$A$2:$A$' + (newSheet.getLastRowNum() + 1));
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).addNewSmooth().setVal(true);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).addNewMarker().addNewSymbol().setVal(org.openxmlformats.schemas.drawingml.x2006.chart.STMarkerStyle.NONE);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).addNewMarker().addNewSize().setVal(5);
chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).addNewMarker().addNewSpPr().addNewLn().addNewSolidFill().addNewSrgbClr().setVal(new byte[]{(byte) 0, (byte) 0, (byte) 0});
// 将工作簿写入输出文件
newWorkbook.write(outputStream);
System.out.println('Data filling and chart creation 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
}
}
// 获取时间规律
private static List<Date> getDatePattern(Date startDate, Date endDate, int count) {
List<Date> pattern = new ArrayList<Date>();
// 计算时间间隔
long interval = (endDate.getTime() - startDate.getTime()) / (count - 1);
// 填充时间规律
for (int i = 0; i < count; i++) {
long time = startDate.getTime() + i * interval;
Date date = new Date(time);
pattern.add(date);
}
return pattern;
}
}
原文地址: https://www.cveoy.top/t/topic/f2bo 著作权归作者所有。请勿转载和采集!