目录
【定义一】:部分依赖图(Partial Dependence Plot)显示了一个或两个特征对机器学习模型的预测结果的边际效应
【定义二】:通过改变感兴趣特征的值同时保持补充特征的值不变,分析模型输出,从而计算特征变量对模型预测结果影响的函数关系:例如近似线性关系、单调关系或者更复杂的关系。
def partial_dependence( ind, //目标特征 model, //预测函数model.predict data, //数据集 xmin="percentile(0)", xmax="percentile(100)", npoints=None, feature_names=None, hist=True, model_expected_value=False, //平均模型预测 feature_expected_value=False, //平均特征值 shap_values=None, ylabel=None, ice=True, //是否制作部份依赖图或个体条件期望图 ace_opacity=1, pd_opacity=1, pd_linewidth=2, ace_linewidth='auto', ax=None, show=True)补充说明:model_expected_value,feature_expected_value
- from sklearn.datasets import fetch_california_housing
- from sklearn.ensemble import RandomForestRegressor
- X, y = fetch_california_housing(return_X_y=True, as_frame=True)
- model = RandomForestRegressor(random_state=42).fit(X, y)
- X100 = X.sample(n=100)
-
- from shap.plots._partial_dependence import partial_dependence
- partial_dependence(ind="AveOccup", model=model.predict, data=X100, ice=False, model_expected_value=True, feature_expected_value=True)
- partial_dependence(ind="MedInc", model=model.predict, data=X100, ice=False, model_expected_value=True, feature_expected_value=True)


- partial_dependence(ind="AveOccup", model=model.predict, data=X100, ice=True, model_expected_value=True, feature_expected_value=True)
- partial_dependence(ind="MedInc", model=model.predict, data=X100, ice=True, model_expected_value=True, feature_expected_value=True)


pip install plotly_express
- import plotly_express as px
- fig = px.scatter(x=X["AveOccup"], y=X["MedInc"], color=y,labels={"x": "AveOccup", "y": "MedInc", "color": "price"},range_x=(0, 10))
- fig.write_image('./1.png')
- fig.show()

【参考资料】: