from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from lime.lime_tabular import LimeTabularExplainer import numpy as np import pandas as pd # 准备数据 data = load_breast_cancer() # df=pd.DataFrame(data.data,columns=data.feature_names) # df['target']=data.target # print(df.head()) X = data.data y = data.target # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # 训练模型 rfc = RandomForestClassifier(n_estimators=100, random_state=42) rfc.fit(X_train, y_train) # 预测结果 y_pred = rfc.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f"Accuracy:{accuracy:.3f}") # 解释模型结果 def explain_sample(x, model, feature_names): explainer = LimeTabularExplainer(X_train, feature_names=feature_names, class_names=data.target_names) exp = explainer.explain_instance(x, model.predict_proba, num_features=len(feature_names)) return exp # 随机选择一个测试样本并解释 idx = np.random.randint(len(X_test)) x=X_test[idx] exp=explain_sample(x,rfc,data.feature_names) fig=exp.as_pyplot_figure() print(f"Sample index:{idx}") fig.show()优化一下这段代码,让可视化图片不要一闪而过
时间: 2024-03-17 19:42:16 浏览: 154
Python数据集乳腺癌数据集(from sklearn.datasets import load-breast-cancer)
5星 · 资源好评率100%
可以使用`input()`函数让程序等待用户输入后再继续执行,这样就可以让可视化图片在用户输入后再显示。代码如下:
```python
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from lime.lime_tabular import LimeTabularExplainer
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 准备数据
data = load_breast_cancer()
X = data.data
y = data.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 训练模型
rfc = RandomForestClassifier(n_estimators=100, random_state=42)
rfc.fit(X_train, y_train)
# 预测结果
y_pred = rfc.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy:{accuracy:.3f}")
# 解释模型结果
def explain_sample(x, model, feature_names):
explainer = LimeTabularExplainer(X_train, feature_names=feature_names, class_names=data.target_names)
exp = explainer.explain_instance(x, model.predict_proba, num_features=len(feature_names))
return exp
# 随机选择一个测试样本并解释
idx = np.random.randint(len(X_test))
x=X_test[idx]
exp=explain_sample(x,rfc,data.feature_names)
fig=exp.as_pyplot_figure()
print(f"Sample index:{idx}")
fig.show()
input("Press Enter to continue...")
```
这样,当程序运行到`fig.show()`时,会显示可视化图片,并等待用户输入后才会继续执行下去。用户可以在图片显示的状态下仔细观察,直到输入回车键后程序才会结束。
阅读全文