R 中的 KerastuneR

KerastuneR in R

我正在尝试使用 kerastuneR 来实现此代码以进行超参数调整。

library(keras)
library(tensorflow)
library(kerastuneR)
library(dplyr)
    
x_data <- matrix(data = runif(500,0,1),nrow = 50,ncol = 5)
y_data <-  ifelse(runif(50,0,1) > 0.6, 1L,0L) %>% as.matrix()

x_data2 <- matrix(data = runif(500,0,1),nrow = 50,ncol = 5)
y_data2 <-  ifelse(runif(50,0,1) > 0.6, 1L,0L) %>% as.matrix()

build_model = function(hp) {
  
  model = keras_model_sequential()
  model %>% layer_dense(units=hp$Int('units',
                                     min_value=32,
                                     max_value=512,
                                     step=32),
                        input_shape = ncol(x_data),
                        activation='relu') %>% 
    layer_dense(units=1, activation='sigmoid') %>% 
    compile(
      optimizer= tf$keras$optimizers$Adam(
        hp$Choice('learning_rate',
                  values=c(1e-2, 1e-3, 1e-4))),
      loss='binary_crossentropy',
      metrics='accuracy') 
  return(model)
}



tuner = RandomSearch(
  build_model,
  objective = 'val_accuracy',
  max_trials = 5,
  executions_per_trial = 3,
  directory = 'my_dir',
  project_name = 'helloworld')
    
tuner %>% search_summary()
 
# Fit   
tuner %>% fit_tuner(x_data,y_data,
                    epochs=5, 
                    validation_data = list(x_data2,y_data2))

因此这段代码运行良好,期待出现此错误的最后一段代码:

 Error in py_call_impl(callable, dots$args, dots$keywords) : 
  ValueError: Objective value missing in metrics reported to the Oracle, expected: ['val_accuracy'], found: dict_keys(['loss', 'acc', 'val_loss', 'val_acc']) 

那么有人可以帮助解决这个错误吗?

报错是给你解决问题的钥匙。您需要将 fit_tuner 生成的键名与提供给 RandomSearch 函数的键名相匹配。尝试用 'val_accuracy' 替换 RandomSearch 函数中的 'val_acc'。