第三十二天打卡
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()
@浙大疏锦行