发外链的网站排名,茂名哪里有网站开发公司,dz网站模板,北京网站建设 shwl前言
这段代码的目标是使用 随机森林分类器#xff08;Random Forest Classifier#xff09; 来进行二分类任务#xff0c;并基于每个数据子集计算 ROC 曲线#xff08;Receiver Operating Characteristic Curve#xff09;以及 AUC#xff08;Area Under Curve#xf…
前言
这段代码的目标是使用 随机森林分类器Random Forest Classifier 来进行二分类任务并基于每个数据子集计算 ROC 曲线Receiver Operating Characteristic Curve以及 AUCArea Under Curve。 一、步骤
代码执行以下步骤
数据预处理按列选择目标变量和特征每次循环时从 newdata 数据中选择前14列作为特征X并选择第14列之后的某一列作为目标变量y。处理缺失值和无效值通过将数据转换为数值类型并删除包含 NaN 或无效值如 -9999的行确保数据的干净和有效。数据标准化使用 标准化StandardScaler 将特征矩阵 X 转换为标准化数据使得数据的均值为0标准差为1从而确保每个特征对模型的贡献是均衡的。训练和验证数据集划分在每轮循环中数据被划分为训练集和验证集比例为 2/5 和 3/5。此划分方式通过计算 split_index 和 train_index 来实现后续用训练集训练模型并在验证集上评估性能。模型训练与评估训练使用 RandomForestClassifier 对训练集数据进行训练。模型的参数包括 n_estimators1000树的数量和 max_depthNone树的深度不限制。验证与 ROC 曲线计算使用训练好的分类器在验证集上进行预测并计算 ROC 曲线 和 AUC。ROC 曲线描绘了模型分类性能在不同决策阈值下的变化AUC 是 ROC 曲线下的面积表示模型的分类能力。通过 RocCurveDisplay.from_estimator 来计算并显示这些值。存储和平均化性能曲线插值为了绘制更平滑的ROC曲线使用 np.interp 方法对每次计算得到的曲线进行插值使其与均匀的 mean_fpr 对应。存储每轮5次的 TPRTrue Positive Rate 和 AUC并计算所有折fold上的平均 TPR 和 AUC。绘制最终 ROC 曲线最后在单一的图表上绘制所有 5 次训练得到的 ROC 曲线并标注每个模型的 AUC 值显示在图例中。图表定制为了符合出版标准设置了图表的样式包括坐标轴的宽度、字体大小、图例位置等。使用 Arial 字体 并调整了 ax1绘制 ROC 曲线的轴的刻度和标签样式。代码的核心目的
模型评估使用随机森林分类器对数据进行训练评估模型的分类性能。
ROC 和 AUC 计算对每个模型计算并展示其 ROC 曲线 和 AUC这些是评估分类模型性能的常用指标。
多次交叉验证通过多次训练和评估5次保证模型在不同数据子集上的稳健性和泛化能力。
绘图和展示生成一张带有多个模型 ROC 曲线的图直观展示各个模型的表现。代码
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import RocCurveDisplay, auc
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import StandardScaler
import xgboost as xgb
import numpy as np
import pandas as pd
import os
from matplotlib.font_manager import FontProperties# 创建一个字体属性对象
font_prop FontProperties(familyArial, size20)#%%读取数据 设置默认路径10
outdir/DATA/
random_state np.random.RandomState(0)
fig1, ax1 plt.subplots(1, 1, figsize(8, 8)) # 这里设置为 1x1 只包含一个图
Factors pd.read_excel(T.xlsx, sheet_nameFactors)
MSWEPpd.read_excel(T.xlsx, sheet_nameMSWEP)
#%%
pres [A,B,C]
# 创建子目录如果不存在
label_dir os.path.join(outdir, GPM)
os.makedirs(label_dir, exist_okTrue)
mean_fprs []
mean_tprs []
mean_aucs []
std_aucs []
FactorsnewFactors.iloc[:, 0:14]
MSWEPdwi MSWEP.iloc[:, 0:10] ** 0.5
newdata pd.concat([Factorsnew, MSWEPdwi], axis1)#根据字符串变量 pre_name 中存储的列名来获取对应的 DataFrame。这种方式可以动态地根据字符串变量来执行代码
for i in range(5):dwidata pd.concat([newdata.iloc[:, 0:14], newdata.iloc[:, i14]], axis1)#根据字符串变量 pre_name 中存储的列名来获取对应的 DataFrame。这种方式可以动态地根据字符串变量来执行代码# 查找包含NaN值的索引dwidata dwidata.apply(pd.to_numeric, errorscoerce) nan_indices np.isnan(dwidata)# 删除包含NaN值的行dwidata dwidata[~np.any(nan_indices, axis1)]dwidata dwidata.loc[~dwidata.isin([-9999]).any(axis1)]y pd.concat([dwidata.iloc[:, 13]], axis1)Xpd.concat([dwidata.iloc[:, 0:13],dwidata.iloc[:, 14]], axis1)scaler StandardScaler()X scaler.fit_transform(X)yy.values#让y重新排列不再有原始序列因为X标准化过后会生成新的序列y y.ravel()#将 y 转换为一维数组形式n_splits 5cv StratifiedKFold(n_splitsn_splits)classifier RandomForestClassifier(n_estimators1000, max_depthNone,random_state42)tprs []aucs []mean_fpr np.linspace(0, 1, 100)fig, ax plt.subplots(figsize(6, 6))for fold, (train, test) in enumerate(cv.split(X, y)):classifier.fit(X[train], y[train])viz RocCurveDisplay.from_estimator(classifier,X[test],y[test],namefROC fold {fold},alpha0.3,lw1.5,axax,#plot_chance_level(fold n_splits - 1),)plt.close(all)ax.clear() # 清空绘图区域 将上面的交叉验证图清除interp_tpr np.interp(mean_fpr, viz.fpr, viz.tpr)interp_tpr[0] 0.0tprs.append(interp_tpr)aucs.append(viz.roc_auc)mean_tpr np.mean(tprs, axis0)mean_tpr[-1] 1.0mean_auc auc(mean_fpr, mean_tpr)std_auc np.std(aucs)mean_fprs.append(mean_fpr)mean_tprs.append(mean_tpr)mean_aucs.append(mean_auc)std_aucs.append(std_auc)# # Plot all ROC curves together after the loop
for i in range(len(mean_fprs)):ax1.plot(mean_fprs[i],mean_tprs[i],labelf{pres[i]} (AUC {mean_aucs[i]:.2f}),lw2,alpha0.8,)ax1.legend(locbest,prop{size: 10, family: Arial}, frameonFalse)
ax1.set_xlabel(False Positive Rate, fontsize15, fontnameTimes New Roman)
ax1.set_ylabel(True Positive Rate, fontsize15, fontnameTimes New Roman)
ax1.text(0.1, 1.2, (a), transformax1.transAxes, fontsize20, vatop, fontpropertiesfont_prop)# 设置ax1的样式
ax1.spines[bottom].set_linewidth(1.5)
ax1.spines[left].set_linewidth(1.5)
ax1.spines[top].set_linewidth(1.5)
ax1.spines[right].set_linewidth(1.5)
ax1.tick_params(axisboth, width1.5,labelsize15)
ax1.set_ylim(0.7, 1.1)font { size: 15, family:Arial} # xlabes
x1_label ax1.get_xticklabels()
[x1_label_temp.set_font(font) for x1_label_temp in x1_label]
x1_label ax1.get_yticklabels()
[x1_label_temp.set_font(font) for x1_label_temp in x1_label]del X
del yfig1.show()
print(done)总结
这段代码的目的是通过 RandomForestClassifier 对数据进行训练并评估其分类性能通过多轮训练、验证、计算 ROC 曲线 和 AUC最终生成一张汇总图比较不同模型的表现。这种方法广泛应用于分类任务的模型评估特别是在需要评估多个模型或参数组合