Day 38 官方文档的阅读

@浙大疏锦行

大多数 Python 库都会有官方文档,里面包含了函数的详细说明、用法示例以及版本兼容性信息。

通常查询方式包含以下3种:

  1. GitHub 仓库:https://github.com/SauceCat/PDPbox

  2. PyPI 页面:https://pypi.org/project/PDPbox/

  3. 官方文档:https://pdpbox.readthedocs.io/en/latest/

    import pandas as pd
    from sklearn.datasets import load_iris
    from sklearn.model_selection import train_test_split
    from sklearn.ensemble import RandomForestClassifier

    加载鸢尾花数据集

    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['target'] = iris.target # 添加目标列(0-2类:山鸢尾、杂色鸢尾、维吉尼亚鸢尾)

    特征与目标变量

    features = iris.feature_names # 4个特征:花萼长度、花萼宽度、花瓣长度、花瓣宽度
    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)

此时模型已经建模完毕,这是一个经典的三分类项目,之前在基础班的项目三提到过sklearn提供的示例数据集,不了解的同学自行百度了解下该数据。

现在我们开始对这个模型进行解释性分析

先进入官方文档 https://pdpbox.readthedocs.io/en/latest/

现在我们第一步是实例化这个类,TargetPlot类

  1. 先导入这个类(三种不同的导入和引用方法)

  2. 传入实例化参数

python 复制代码
# 选择待分析的特征(如:petal length (cm))
feature = 'petal length (cm)'
feature_name = feature  # 特征显示名称

# 选择待分析的特征(如:petal length (cm))
feature = 'petal length (cm)'
feature_name = feature  # 特征显示名称

# 初始化TargetPlot对象(移除plot_type参数)
target_plot = TargetPlot(
    df=df,  # 原始数据(需包含特征和目标列)
    feature=feature,  # 目标特征列
    feature_name=feature_name,  # 特征名称(用于绘图标签)
    # target='target',  # 多分类目标索引(鸢尾花3个类别)
    target='target',  # 多分类目标索引(鸢尾花3个类别)
    grid_type='percentile',  # 分桶方式:百分位
    num_grid_points=10  # 划分为10个桶
)

# 调用plot方法绘制图形
target_plot.plot()
python 复制代码
fig, axes, summary_df = target_plot.plot(
    which_classes=None,  # 绘制所有类别(0,1,2)
    show_percentile=True,  # 显示百分位线
    engine='plotly',
    template='plotly_white'
)

# 手动设置图表尺寸(单位:像素)
fig.update_layout(
    width=800,  # 宽度800像素
    height=500,  # 高度500像素
    title=dict(text=f'Target Plot: {feature_name}', x=0.5)  # 居中标题
)

fig.show()

其中,fig.update_layout() 是对 Plotly 图表进行 二次修改 的核心方法。很多绘图工具都是调用的底层的绘图包,所以要想绘制出想要的图表,需要先了解底层绘图包的语法。

相关推荐
Learn-Python4 小时前
MongoDB-only方法
python·sql
小途软件5 小时前
用于机器人电池电量预测的Sarsa强化学习混合集成方法
java·人工智能·pytorch·python·深度学习·语言模型
扫地的小何尚5 小时前
NVIDIA RTX PC开源AI工具升级:加速LLM和扩散模型的性能革命
人工智能·python·算法·开源·nvidia·1024程序员节
wanglei2007086 小时前
生产者消费者
开发语言·python
清水白石0086 小时前
《从零到进阶:Pydantic v1 与 v2 的核心差异与零成本校验实现原理》
数据库·python
昵称已被吞噬~‘(*@﹏@*)’~6 小时前
【RL+空战】学习记录03:基于JSBSim构造简易空空导弹模型,并结合python接口调用测试
开发语言·人工智能·python·学习·深度强化学习·jsbsim·空战
2501_941877986 小时前
从配置热更新到运行时自适应的互联网工程语法演进与多语言实践随笔分享
开发语言·前端·python
酩酊仙人6 小时前
fastmcp构建mcp server和client
python·ai·mcp
且去填词7 小时前
DeepSeek API 深度解析:从流式输出、Function Calling 到构建拥有“手脚”的 AI 应用
人工智能·python·语言模型·llm·agent·deepseek
rgeshfgreh8 小时前
Python条件与循环实战指南
python