1

我试图找出将 keras 模型应用于我的每个列表的正确方法。我使用了iris数据集并创建了 4 个列表,目标是正确预测versicolorvirginica(我省略了setosa,因为我想要一个二元分类模型)。

data(iris)
iris <- iris %>% 
  mutate(
    splt = sample(4, size = nrow(.), replace = TRUE),
    binary = case_when(
      Species == "versicolor" ~ 0,
      Species == "virginica" ~ 1
    )
  ) %>%  
  filter(Species != "setosa") %>% 
  split(., .$splt)

iris_x_train <- iris %>% 
  map(., ~select(., Sepal.Length, Sepal.Width, Petal.Length, Petal.Width) %>% 
        as.matrix())

iris_y_train <- iris %>% 
  map(., ~select(., binary) %>% 
        to_categorical(2))

NN_model <- keras_model_sequential() %>% 
  layer_dense(units = 4, activation = 'relu', input_shape = 4) %>% 
  layer_dense(units = 2, activation = 'softmax')

NN_model %>% 
  summary

NN_model %>% 
  compile(
    loss = 'binary_crossentropy',
    optimizer_sgd(lr = 0.01, momentum = 0.9),
    metrics = c('accuracy')
  )

我的问题发生在这里。当我应用以下代码时:

NN_model %>%
  future_map(., ~future_map2(
    .x = iris_x_train,
    .y = iris_y_train,
    ~fit(
      x = .x,
      y = .y,
      epochs = 5,
      batch_size = 20,
      validation_split = 0
    )
  )
  )

我收到此错误:

py_get_item_impl(x,key,FALSE)中的错误:TypeError:'Sequential'对象不支持索引

当我应用此代码时:

NN_model %>%
  future_map2(
    .x = iris_x_train,
    .y = iris_y_train,
    ~fit(
      x = .x,
      y = .y,
      epochs = 5,
      batch_size = 20,
      validation_split = 0
      )
    )

我收到此错误:

〜fit(x = .x,y = .y,epochs = 5,batch_size = 20,validation_split = 0)py_call_impl中的错误(callable,dots$args,dots$keywords):评估错误:无法将R对象转换为Python类型。

如何将 keras 模型映射到 4 个数据集中的每一个?

library(keras)
library(tensorflow)
library(furrr)
library(purrr)

以下适用于第一个列表:

NN_model %>% 
  fit(
    x = iris_x_train[[1]],
    y = iris_y_train[[1]],
    epochs = 50,
    batch_size = 20,
    validation_split = 0
  )

编辑:我似乎已经解决了。

将函数NN_model放入内部fit()似乎可以工作。

future_map2(
    .x = iris_x_train,
    .y = iris_y_train,
    ~fit(NN_model,
      .x,
      .y,
      epochs = 5,
      batch_size = 20,
      validation_split = 0
    )
  )
4

0 回答 0