将自定义R生成器函数与fit_generator(Keras,R)结合使用

时间:2018-11-18 04:29:51

标签: r image keras generator

我想训练一个卷积网络,以解决图像数据上的多类,多标签问题。由于数据的性质,出于种种原因,我将不遗余力,最好是我可以使用自定义的R生成器函数而不是内置的{{1 }}和fit_generator命令(我成功地开始工作,只是没有解决这个特定问题)。

这里(https://www.rdocumentation.org/packages/keras/versions/2.2.0/topics/fit_generator)表示我可以做到这一点,而无需给出任何示例。因此,我尝试了以下方法。这是我要做的事情的精简示例(此代码完全独立):

image_data_generator

在训练时,东西冻结了,没有给我任何错误消息或任何东西。对于原始问题,我还使用了自定义图像数据生成器进行了尝试,结果相同。

请注意,如果我仅使用flow_images_from_directory并手动输入训练数据,则该网络训练就很好:

library(keras)
library(reticulate)      #for py_iterator function

play.network = keras_model_sequential() %>%
  layer_dense(units = 10, activation = "relu", input_shape = c(10)) %>%
  layer_dense(units = 1, activation = "relu")

play.network %>% compile(
  optimizer = "rmsprop",
  loss = "mse"
)

mikes.custom.generator.function = function()     #generates a 2-list of a random 1 x 10 array, and a scalar
{
  new.func = function()
  {
    arr = array(dim = c(1,10))
    arr[,] = sample(1:10, 10, replace = TRUE)/10
    return(list(arr,runif(1)))
  }
}

mikes.custom.iterator = py_iterator(mikes.custom.generator.function())          #creates a python iterator object

generator_next(mikes.custom.iterator)                 #correctly returns a 2-member list consisting of a 1 x 10 array, and a scalar
generator_next(mikes.custom.iterator)[[1]]            #a 1 x 10 array
generator_next(mikes.custom.iterator)[[2]]            #a scalar

#try to fit with "fit_generator":

play.network %>% fit_generator(                       #FREEZES.
  mikes.custom.iterator,
  steps_per_epoch = 1,
  epochs = 1
)

我认为我知道问题所在,但是我不知道解决方案。如果您将其作为我的自定义迭代器的类,它将给出

fit

而如果我使用内置的play.network %>% fit(generator_next(mikes.custom.iterator)[[1]],generator_next(mikes.custom.iterator)[[2]], epochs = 1, batch_size = 1) #trains just fine class(mikes.custom.iterator) [1] "python.builtin.iterator" "rpytools.generator.RGenerator" "python.builtin.object" 命令构建一个迭代器,它将给出

image_data_generator

所以我的猜测是flow_images_from_directory和/或train_datagen <- image_data_generator(rescale = 1/255) class(train_datagen) [1] "keras.preprocessing.image.ImageDataGenerator" "keras_preprocessing.image.ImageDataGenerator" "python.builtin.object" train_generator <- flow_images_from_directory( train_dir, train_datagen, .... ) class(train_generator) [1] "python.builtin.iterator" "keras_preprocessing.image.DirectoryIterator" "keras_preprocessing.image.Iterator" "tensorflow.python.keras.utils.data_utils.Sequence" "python.builtin.object" 具有train_datagen没有的属性,并且train_generator试图使用函数调用mikes.custom.iterator除了基本的fit_generator(理论上这是它真正需要的)。但是,即使在网上搜索了两个小时之后,我也不知道它们可能是什么,或者如何正确构建mikes.custom.iterator

帮助任何人?

2 个答案:

答案 0 :(得分:2)

在R中,您可以使用<<-运算符来构建迭代器。这对于构建自定义生成器功能非常有帮助。并且与Keras的fit_generator()函数兼容。

一些最小的例子:

# example data
data <- data.frame(
  x = runif(80),
  y = runif(80),
  z = runif(80)
)

# example generator
data_generator <- function(data, x, y, batch_size) {

  # start iterator
  i <- 1

  # return an iterator function
  function() {

    # reset iterator if already seen all data
    if ((i + batch_size - 1) > nrow(data)) i <<- 1

    # iterate current batch's rows
    rows <- c(i:min(i + batch_size - 1, nrow(data)))

    # update to next iteration
    i <<- i + batch_size

    # create container arrays
    x_array <- array(0, dim = c(length(rows), length(x)))
    y_array <- array(0, dim = c(length(rows), length(y)))

    # fill the container
    x_array[1:length(rows), ] <- data[rows, x]
    y_array[1:length(rows), ] <- data[rows, y]

    # return the batch
    list(x_array, y_array)

  }

}

# set-up a generator
gen <- data_generator(
  data = data.matrix(data),
  x = 1:2, # it is flexible, you can use the column numbers,
  y = c("y", "z"), # or the column name
  batch_size = 32
)

从上面的函数中,您可以通过调用生成器来简单地检查结果数组:

gen()

或者您也可以使用简单的Keras模型测试生成器:

# import keras
library(keras)

# set up a simple keras model
model <- keras_model_sequential() %>% 
  layer_dense(32, input_shape = c(2)) %>% 
  layer_dense(2)

model %>% compile(
  optimizer = "rmsprop",
  loss = "mse"
)

# fit using generator
model %>% fit_generator(
  generator = gen,
  steps_per_epoch = 100, # will auto-reset after see all sample
  epochs = 10
)

我必须承认该过程有点复杂,需要大量编程。您应该亲自François Chollet或我亲自开发的kerasgenerator软件包来查看此精选博客文章。

答案 1 :(得分:0)

sampling_generator <- function(X_data, Y_data, batch_size) {
  function() {
    rows <- sample(1:nrow(X_data), batch_size, replace = TRUE)
    list(X_data[rows,], Y_data[rows,])
  }
}

model %>% 
  fit_generator(sampling_generator(X_train, Y_train, batch_size = 128), 
            steps_per_epoch = nrow(X_train) / 128, epochs = 10)

我在R keras常见问题解答中找到了这个答案,

https://keras.rstudio.com/articles/faq.html#how-can-i-use-keras-with-datasets-that-dont-fit-in-memory