r语言 - 将石灰与具有顺序模型的 keras 一起使用 - 数据框给出的'dimnames'无效



我有两个数据集,我使用一个用于训练,另一个作为外部验证。

我正试图在通过Keras构建的简单顺序模型上使用Lime:

# Building
build_model <- function() {                                
model <- keras_model_sequential() %>%
layer_dense(units = 25,
activation = "relu",
input_shape = dim(X_pca_scores_scaled)[[2]]) %>%
layer_dropout(rate = 0.1) %>%
layer_dense(units = 25, activation = "relu") %>%
layer_dropout(rate = 0.1) %>%
layer_dense(units = 1)
model %>% compile(
optimizer = "adam",
loss = "mse",
metrics = c("mae")
)
}
# Training
model <- build_model()
model %>% fit(as.matrix(X_pca_scores_scaled), train_targets,                    
epochs = num_epochs, verbose = 1, 
callbacks = callback_early_stopping(monitor = "mae",
patience = 5,
min_delta = 0.25,
mode = "min"))

然后我首先尝试在训练数据上使用Lime:

explainer <- lime(X_pca_scores_scaled, model,  bin_continuous = TRUE, n_bins = 4)
explanation <- lime::explain(X_pca_scores_scaled, explainer, n_features = 10)
plot_features (explanation)
然而,当调用lime::explain 时,我遇到了以下错误
Error in `dimnames<-.data.frame`(`*tmp*`, value = list(n)) :   
invalid 'dimnames' given for data frame

训练和测试数据集都被设置为data.frames,我认为这会解决问题,但事实并非如此。我也试着遵循这个线程,但不知道如何将他们的建议实现到我的代码中。

无效& # 39;dimnames& # 39;在R

中对keras CNN模型使用lime时的数据帧

所以我发布的链接中的答案确实有效,我只是在功能描述中犯了一个愚蠢的错误。

######################
# LIME
######################
model_type.keras.engine.sequential.Sequential <- function(x, ...) {
"regression"
}
# Setup lime::predict_model()
predict_model.keras.engine.sequential.Sequential <- function (x, newdata, type, ...) {

## here you have to write function, that takes a data.frame
## and transform it to shape that keras understands

## for example if u flatten your array before training CNN, you just use
## as-matrix()

## if keras model expect 3d dataset, you write something like
## as.array(newdata, dims(n,12,12))

your_function <- function(data){
as.matrix(newdata)
}

pred <- predict(object = x, x = your_function(newdata))
data.frame (pred) }

x <- as.data.frame(your_train_data)  
x2 <- as.data.frame(your_test_data)  
explainer <- lime(x = x, model= model)

explanation <- lime::explain (
x=  x2[1:10,], 
explainer, n_features = 4) 

plot_features (explanation) +
labs (title = "LIME: Feature Importance Visualization") 

最新更新