python打卡训练营day32————2025.05.21

官方文档的阅读
官方文档的检索方式:github和官网
官方文档的阅读和使用:要求安装的包和文档为同一个版本
类的关注点:
实例化所需要的参数
普通方法所需要的参数
普通方法的返回值
绘图的理解:对底层库的调用
作业:参考pdpbox官方文档中的其他类,绘制相应的图,任选即可

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)
# 首先要确保库的版本是最新的,因为我们看的是最新的文档,库的版本可以在github上查看
import  pdpbox
print(pdpbox.__version__)  # pdpbox版本
# 导入这个类
# 选择待分析的两个特征
feature1 = 'petal length (cm)'
feature2 = 'sepal length (cm)'
feature1_name = feature1
feature2_name = feature2
# 初始化交互目标
from pdpbox.info_plots import InteractTargetPlot  # 导入交互目标图类
# 初始化交互目标图
interact_plot = InteractTargetPlot(
    df=df,  # 原始数据
    features=[feature1, feature2],  # 两个特征
    feature_names=[feature1_name, feature2_name],  # 特征名称
    target='target',  # 目标变量
    grid_types=['percentile', 'percentile'],  # 两个特征都使用百分位分桶
    num_grid_points=[10, 10]  # 每个特征划分为10个桶
)
fig, axes, summary_df = interact_plot.plot(
    which_classes=None,  # 绘制所有类别
    show_percentile=True,  # 显示百分位线
    engine='plotly',
    template='plotly_white'
)

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

python打卡训练营day32————2025.05.21_第1张图片@浙大疏锦行

你可能感兴趣的:(Python打卡,python,开发语言)