Как интегрировать Keras с Shiny в R (код выбрасывает ошибки) - PullRequest
0 голосов
/ 21 июня 2019

Я пытаюсь создать небольшое блестящее приложение, которое выводит прогноз на основе определенных входных данных.Серверная часть использует Keras, и я в основном пытаюсь интегрировать это с внешним интерфейсом Shiny

. Я пытался обернуть все в реактив и т. Д., Но я все еще получаю ошибки.Кажется, что ошибки происходят от Keras, но я не совсем понимаю, как работает код keras сам по себе (с теми же входными данными, что и данные, передаваемые блестящим приложением).

Ниже приведен блестящий код приложения:

library(shiny)
library(keras)
library(tidyverse)

# Define UI for application
ui <- fluidPage(

   # Application title
   titlePanel("Sales Number Prediction"),

   # Sidebar
   sidebarLayout(
     sidebarPanel(numericInput("id", "ID", 0, 0),
                  numericInput("car_id", "Car ID", 0, 0),
                  numericInput("make_id", "Make ID", 0, 0),
                  numericInput("model_id", "Model ID", 0, 0),
                  numericInput("month", "Month", 0, 0),
                  numericInput("quarter", "Quarter", 0, 0),
                  selectInput("auction", "Auction", read_csv(file = "Fugazi foogazi.csv") %>% select(auction) %>% distinct %>% pull),
                  submitButton("Submit", "Predict")
                ),
   mainPanel(textOutput(outputId = "result"))
   )
)



# Define server logic required to draw a histogram
server <- function(input, output) {
  model <- load_model_hdf5(filepath = "Model1", compile = T) 
  tokenizer <- load_text_tokenizer("tokenizer")
  auction <- reactive({input$auction})
  sequence <- tokenizer %>% texts_to_sequences(renderText(auction())) 

  sequence_padded <- sequences %>% pad_sequences(maxlen = 12)
  X <- c(input$id, input$car_id, input$make_id, input$model_id, input$month, input$quarter, sequence_padded)
  pred_Y <- model1 %>% predict_on_batch(X %>% array_reshape(list(nrow(X), 18, 1))) %>% array
  output$result <- pred_Y
}

# Run the application 
shinyApp(ui = ui, server = server)

Проблема, похоже, исходит из этой строки:

 sequence <- tokenizer %>% texts_to_sequences(renderText(auction())) 

Это модель Keras (которая прекрасно работает сама по себе:

model1 <- keras_model_sequential()

model1 %>%
layer_conv_1d(filters = 100, kernel_size = 3, activation = "relu", input_shape = c(18,1)) %>% 
layer_max_pooling_1d(pool_size = 3, padding = "same")  %>% 
layer_conv_1d(filters = 64, kernel_size = 2, activation = "relu") %>% 
layer_max_pooling_1d(pool_size = 3, padding = "same")  %>%
layer_gru(units = 50, activation = "relu") %>% 
layer_dense(units = 32, activation = "relu") %>% 
layer_dense(units = 16, activation = "relu") %>% 
layer_dense(units = 1)

Ятакже приведен ниже код токенизатора, используемый в модели keras (поскольку именно здесь, похоже, и возникает ошибка в блестящем приложении:


data <- data %>% select(price, id, car_id, make_id, model_id, month, quarter, auction) %>% drop_na 

data$auction[data %>% pull(auction) %>% is.na] <- "" 

text <- data$auction
tokenizer <-  text_tokenizer(num_words = 165) %>% 
  fit_text_tokenizer(text)

tokenizer %>% save_text_tokenizer("tokenizer")

sequences <-  texts_to_sequences(tokenizer, text) 

word_index <-  tokenizer$word_index

maxlen <- sequences %>% map(length) %>% unlist %>% max

sequences_padded <-  pad_sequences(sequences, maxlen = maxlen)

data <- data %>% select(price, id, car_id, make_id, model_id, month, quarter) %>% as.matrix

data <- cbind(data, sequences_padded)

train <- data[1:round(0.8*nrow(data)),]
test <- data[round(0.8*nrow(data)):nrow(data),]


Y_train <- train[,1]
Y_test <-  test[,1]

X_train <- train[,-1]
X_test <- test[,-1]

Я просто хочу, чтобы блестящая основная панель выводила выходные данныеМодель keras для входов, которые у меня есть. Текущий код ошибки, который я получаю:

Warning: Error in py_call_impl: TypeError: 'function' object is not iterable

Detailed traceback: 
  File "/Users/denizalp/anaconda2/envs/r-tensorflow/lib/python3.6/site-packages/keras_preprocessing/text.py", line 279, in texts_to_sequences
    return list(self.texts_to_sequences_generator(texts))
  File "/Users/denizalp/anaconda2/envs/r-tensorflow/lib/python3.6/site-packages/keras_preprocessing/text.py", line 298, in texts_to_sequences_generator
    for text in texts:

  60: <Anonymous>
Error in py_call_impl(callable, dots$args, dots$keywords) : 
  TypeError: 'function' object is not iterable

Detailed traceback: 
  File "/Users/denizalp/anaconda2/envs/r-tensorflow/lib/python3.6/site-packages/keras_preprocessing/text.py", line 279, in texts_to_sequences
    return list(self.texts_to_sequences_generator(texts))
  File "/Users/denizalp/anaconda2/envs/r-tensorflow/lib/python3.6/site-packages/keras_preprocessing/text.py", line 298, in texts_to_sequences_generator
    for text in texts:
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...