我已经开始学习Lime了。当我使用LimeTabular形式的Interpret时,我遇到一个问题,我按照标准完成了功能,但它不起作用。 错误是 TypeError: init () 缺少 1 个必需的位置参数:'model'
# %% Imports
from utils import DataLoader
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score, accuracy_score
from interpret.blackbox import LimeTabular
from interpret import show
# %% Load and preprocess data
data_loader = DataLoader()
data_loader.load_dataset()
data_loader.preprocess_data()
# Split the data for evaluation
X_train, X_test, y_train, y_test = data_loader.get_data_split()
# Oversample the train data
X_train, y_train = data_loader.oversample(X_train, y_train)
print(X_train.shape)
print(X_test.shape)
# %% Fit blackbox model
rf = RandomForestClassifier()
rf.fit(X_train, y_train)
y_pred = rf.predict(X_test)
print(f"F1 Score {f1_score(y_test, y_pred, average='macro')}")
print(f"Accuracy {accuracy_score(y_test, y_pred)}")
# %% Apply lime
# Initilize Lime for Tabular data
lime = LimeTabular(predict_fn=rf.predict_proba,
data=X_train,
random_state=1)
# Get local explanations
lime_local = lime.explain_local(X_test[-20:],
y_test[-20:],
name='LIME')
show(lime_local)
# %%
错误消息表明你正在使用
LimeTabular
类的一个旧版本,该版本没有将
model
作为
__init__
方法中的必需参数。要解决此问题,你需要
将预测函数 (
rf.predict_proba
) 直接传递给
explain_local
方法
,而不是在初始化
LimeTabular
时传递。
以下是如何修改代码的方法:
# %% Imports
from utils import DataLoader
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score, accuracy_score
from interpret.blackbox import LimeTabular
from interpret import show
# %% Load and preprocess data
data_loader = DataLoader()
data_loader.load_dataset()
data_loader.preprocess_data()
# Split the data for evaluation
X_train, X_test, y_train, y_test = data_loader.get_data_split()
# Oversample the train data
X_train, y_train = data_loader.oversample(X_train, y_train)
print(X_train.shape)
print(X_test.shape)
# %% Fit blackbox model
rf = RandomForestClassifier()
rf.fit(X_train, y_train)
y_pred = rf.predict(X_test)
print(f"F1 Score {f1_score(y_test, y_pred, average='macro')}")
print(f"Accuracy {accuracy_score(y_test, y_pred)}")
# %% Apply lime
# Initilize Lime for Tabular data
lime = LimeTabular(data=X_train,
random_state=1)
# Get local explanations
# 将 predict_fn 传递给 explain_local
lime_local = lime.explain_local(X_test[-20:],
y_test[-20:],
name='LIME',
predict_fn=rf.predict_proba)
show(lime_local)
# %%
通过此更改,你应该能够在不出现
TypeError
的情况下运行代码。