0

下面是一个简单的代码。

  1. 我正在尝试使用foreach循环并行化训练具有不同数量神经元的三个 ANN。
  2. 后来我试图预测使用models[[1]]

但我收到错误。foreach 模型的输出是类keras_training_history

Error in UseMethod("predict") : 
  no applicable method for 'predict' applied to an object of class "keras_training_history"
library(keras)
library(tidyverse)
library(foreach)
library(doFuture)


# parallel processing
registerDoFuture()
plan(multicore, workers = 3)

# Data
x = matrix(data = runif(30000), nrow = 10000, ncol = 3)
y = ifelse(rowSums(x) > 1.5, 1, 0)
y = to_categorical(y)

# finding best number of neurons
neurons_list <- seq(20, 60, 20)

models <- foreach(neurons = neurons_list) %dopar%
  {
    model <- keras_model_sequential() %>%   
      layer_dense(units = neurons, activation = "relu", input_shape = ncol(x)) %>%
      layer_dense(units = ncol(y), activation = "softmax")
    
    model %>%
      compile(loss = "categorical_crossentropy", 
              optimizer = optimizer_rmsprop(), 
              metrics = "accuracy")
    
    model %>% 
      fit(x, y, 
          epochs = 20,
          batch_size = 128,
          validation_split = 0.2, 
          verbose = 0)
  }

# predict output from first model
models[[1]] %>% predict_proba(x)
4

0 回答 0