import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.metrics import r2_score def plot_density_ned(data, degree=2, save_path="density_ned_fit.png"): """ 根据输入二维数组 (density, NED),拟合并可视化趋势。 参数: data: 二维数组或列表 [[density1, ned1], [density2, ned2], ...] degree: 拟合多项式阶数 (默认2阶),二阶多项式拟合 save_path: 保存路径 (默认为 'density_ned_fit.png') 输出: 保存拟合图像,并返回拟合系数与R²值。 """ # 转为numpy数组 data = np.array(data) X = data[:, 0].reshape(-1, 1) # 文字密度 y = data[:, 1] # NED指标 # 多项式特征转换 poly = PolynomialFeatures(degree=degree) X_poly = poly.fit_transform(X) # 拟合回归模型 model = LinearRegression() model.fit(X_poly, y) # 预测与R² y_pred = model.predict(X_poly) r2 = r2_score(y, y_pred) # 平滑曲线点 X_plot = np.linspace(X.min(), X.max(), 200).reshape(-1, 1) X_plot_poly = poly.transform(X_plot) y_plot = model.predict(X_plot_poly) # 绘图 plt.figure(figsize=(8, 6)) plt.scatter(X, y, color='royalblue', alpha=0.7, label='Data points') plt.plot(X_plot, y_plot, color='crimson', linewidth=2.5, label=f'Polynomial Fit (deg={degree})') plt.xlabel("Text Density", fontsize=14) plt.ylabel("NED", fontsize=14) plt.title("Relationship between Text Density and NED", fontsize=16, pad=15) plt.grid(alpha=0.3) plt.legend(fontsize=12) plt.tight_layout() # 保存高分辨率图片 plt.savefig(save_path, dpi=300) plt.close() print(f"✅ 拟合完成,图片已保存至:{save_path}") print(f"📈 拟合公式系数: {model.coef_}") print(f"📊 R² = {r2:.4f}") return model.coef_, r2 # 示例使用 if __name__ == "__main__": data = [ [0.1, 0.12], [0.2, 0.18], [0.3, 0.25], [0.4, 0.32], [0.5, 0.45], [0.6, 0.51], [0.7, 0.62], ] plot_density_ned(data, degree=2, save_path="/vol/density_ned_fit.png")