day36官方文档的阅读@浙大疏锦行
准备工作
importpandasaspdfromsklearn.datasetsimportload_irisfromsklearn.model_selectionimporttrain_test_splitfromsklearn.ensembleimportRandomForestClassifierimportpdpboxfrompdpboximportpdp,info_plots# 打印版本以确认print(f"PDPbox version:{pdpbox.__version__}")# 加载鸢尾花数据集iris=load_iris()df=pd.DataFrame(iris.data,columns=iris.feature_names)df['target']=iris.target# 特征与目标变量features=iris.feature_names target='target'# 划分训练集与测试集X_train,X_test,y_train,y_test=train_test_split(df[features],df[target],test_size=0.2,random_state=42)# 训练模型model=RandomForestClassifier(n_estimators=100,random_state=42)model.fit(X_train,y_train)1. PDPIsolate (单特征偏依赖图)
分析petal length (cm)特征对模型预测的影响。
# 1. PDPIsolate (单特征偏依赖图)# 实例化 PDPIsolate 类pdp_isolate_obj=pdp.PDPIsolate(model=model,df=df,model_features=features,feature='petal length (cm)',feature_name='petal length (cm)')# 绘制图形fig,axes=pdp_isolate_obj.plot(center=True,plot_lines=True,# 显示ICE线frac_to_plot=100,# 绘制100条线plot_pts_dist=True,# 显示数据点分布to_bins=False,show_percentile=True,engine='plotly',template='plotly_white')fig.show()2. PDPInteract (双特征交互偏依赖图)
分析petal length (cm)和petal width (cm)两个特征的交互作用对模型预测的影响。
# 2. PDPInteract (双特征交互偏依赖图)# 实例化 PDPInteract 类pdp_interact_obj=pdp.PDPInteract(model=model,df=df,model_features=features,features=['petal length (cm)','petal width (cm)'],feature_names=['petal length','petal width'])# 绘制图形fig,axes=pdp_interact_obj.plot(plot_type='contour',# 等高线图plot_pdp=True,# 同时显示单特征PDPto_bins=False,show_percentile=True,engine='plotly',template='plotly_white')fig.show()总结
-PDPIsolate帮助我们理解单个特征如何影响模型预测。
-PDPInteract帮助我们理解两个特征之间的交互作用如何影响模型预测。
@浙大疏锦行