"""
===========================LOF处理离群因子=====================================================
一:调库
"""
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import LocalOutlierFactor
from sklearn.metrics import silhouette_score
# LOF为无监督学习,不需要对数据集进行划分
# from sklearn.model_selection import train_test_split
"""
二 :数据处理
"""
# 将功率与风速转为Numpy数组
Speed_Feature = df["windspeed"].to_numpy()
Power_Feature = df["power"].to_numpy()
# 将数据整合为一个特征矩阵
Feature_Matrix = np.column_stack((Speed_Feature,Power_Feature))
# 归一化特征矩阵
scaler = StandardScaler()
Feature_Matrix_scaled = scaler.fit_transform(Feature_Matrix)
"""
三:模型建立
"""
# 模型建立
LOF = LocalOutlierFactor(n_neighbors = 180,contamination= 'auto',leaf_size = 30,metric = 'minkowski',
p = 2,metric_params = None,n_jobs = -1)
"""
四 模型拟合与预测
"""
# 模型预测
y_pred = LOF.fit_predict(Feature_Matrix_scaled)
# y_pred的值为-1表示离群点,1表示正常点
outliers_fac = Feature_Matrix[y_pred == -1]
inliers_fac = Feature_Matrix[y_pred == 1]
"""
五 模型评价
"""
# silhouette_avg = silhouette_score(Feature_Matrix_scaled[y_pred == 1], y_pred[y_pred == 1])
# print(f'Silhouette Score (轮廓系数): {silhouette_avg}')
"""
五 可视化结果
"""
plt.figure(figsize=(10, 6))
plt.scatter(inliers_fac[:, 0], inliers_fac[:, 1], label='Inliers', color='blue')
plt.scatter(outliers_fac[:, 0], outliers_fac[:, 1], label='Outliers', color='red')
plt.title("Wind Speed vs Power Output with LOF Outliers")
plt.xlabel("Wind Speed (m/s)")
plt.ylabel("Power Output (kW)")
plt.legend()
plt.grid()
plt.show()
LOF处理离群点
最新推荐文章于 2025-05-28 20:48:34 发布