ValueError:在用户代码中,同时在 R 中使用 keras 模型 [英] ValueError: in user code while using keras model in R

查看:22
本文介绍了ValueError:在用户代码中,同时在 R 中使用 keras 模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 keras 包在 R 中运行一维 CNN.我正在使用以下代码

I am trying to run 1 dimensional CNN in R using keras package. I am using the following code

library(MASS)
library(keras)

##Create some data
data("Boston")
data <- Boston
# create a list of 70% of the rows in the original dataset we can use for training
set.seed(123)
training <- sample(nrow(data), 0.7 * nrow(data))

dataTrain <- data[training,]
dataTest <- data[-training,]

dataTrain_y <- as.matrix(dataTrain$medv)
dataTrain_x <- as.matrix(subset(dataTrain, select = -c(medv)))

dataTest_y <- as.matrix(dataTest$medv)
dataTest_x <- as.matrix(subset(dataTest, select = -c(medv)))

#Reshaping the data for CNN
dataTrain_x <- array_reshape(dataTrain_x, c(ncol(dataTrain_x), nrow(dataTrain_x), 1))
dataTest_x <- array_reshape(dataTest_x, c(ncol(dataTest_x), nrow(dataTest_x), 1))

#CNN model
model <- keras_model_sequential() %>%
  layer_conv_1d(filters=32, kernel_size=4, activation="relu", 
                input_shape=c(ncol(dataTrain_x), nrow(dataTrain_x))) %>%
  layer_max_pooling_1d(pool_size=2) %>%
  layer_conv_1d(filters=64, kernel_size=2, activation="relu") %>%
  layer_max_pooling_1d(pool_size=2) %>%
  layer_dropout(rate=0.4) %>%
  layer_flatten() %>%
  layer_dense(units=100, activation="relu") %>%
  layer_dropout(rate=0.2) %>%
  layer_dense(units=1, activation="linear")

model %>% compile(
  loss = "mse",
  optimizer =  "adam", #'sgd' can also be used
  metrics = list("mean_absolute_error")
)

model %>% summary()

history <- model %>% fit(dataTrain_x, dataTrain_y, 
                         epochs = 100, batch_size = 50, 
                         #callbacks = callback_tensorboard("logs/run_a"),
                         validation_split = 0.2)

但它返回以下错误

py_call_impl(callable, dots$args, dots$keywords) 中的错误:值错误:在用户代码中:C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py:805 train_function *返回 step_function(self, iterator)C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py:795 step_function **输出 = model.distribute_strategy.run(run_step, args=(data,))C:\Python37\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:1259 运行返回 self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)C:\Python37\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2730 call_for_each_replica返回 self._call_for_each_replica(fn, args, kwargs)C:\Python37\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:3417 _call_for_each_replica返回 fn(*args, **kwargs)C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py:788 run_step **输出 = model.train_step(data)C:\Python37\lib\site-pac

Error in py_call_impl(callable, dots$args, dots$keywords) : ValueError: in user code: C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py:805 train_function * return step_function(self, iterator) C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py:795 step_function ** outputs = model.distribute_strategy.run(run_step, args=(data,)) C:\Python37\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:1259 run return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs) C:\Python37\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2730 call_for_each_replica return self._call_for_each_replica(fn, args, kwargs) C:\Python37\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:3417 _call_for_each_replica return fn(*args, **kwargs) C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py:788 run_step ** outputs = model.train_step(data) C:\Python37\lib\site-pac

现在我该如何解决这个错误?

Now how can I solve this error?

推荐答案

错误消息被截断了,所以没有太大帮助,但在我看来你有一些小错误.如果您进行建议的更改(###"注释),则模型似乎按预期编译和训练,例如

The error message is truncated, so it's not much help, but it looks to me like you've got some minor typos. If you make the suggested changes (the "###" comments) the model appears to compile and train as expected, e.g.

library(MASS)
library(keras)

##Create some data
data("Boston")
data <- Boston
# create a list of 70% of the rows in the original dataset we can use for training
set.seed(123)
training <- sample(nrow(data), 0.7 * nrow(data))

dataTrain <- data[training,]
dataTest <- data[-training,]

dataTrain_y <- as.matrix(dataTrain$medv)
dataTrain_x <- as.matrix(subset(dataTrain, select = -c(medv)))

dataTest_y <- as.matrix(dataTest$medv)
dataTest_x <- as.matrix(subset(dataTest, select = -c(medv)))

#Reshaping the data for CNN
### These dimensions don't look correct; switch ncol() with nrow()
dataTrain_x <- array_reshape(dataTrain_x, c(nrow(dataTrain_x), ncol(dataTrain_x), 1))
dataTest_x <- array_reshape(dataTest_x, c(nrow(dataTest_x), ncol(dataTest_x), 1))

#CNN model
model <- keras_model_sequential() %>%
  layer_conv_1d(filters=32, kernel_size=4, activation="relu", 
                ### The input shape doesn't look correct; instead of 
                ### `c(ncol(dataTrain_x), nrow(dataTrain_x))` (354, 13)
                ### I believe you want `dim(dataTest_x)` (13, 1)
                input_shape=c(ncol(dataTrain_x), 1)) %>%
  layer_max_pooling_1d(pool_size=2) %>%
  layer_conv_1d(filters=64, kernel_size=2, activation="relu") %>%
  layer_max_pooling_1d(pool_size=2) %>%
  layer_dropout(rate=0.4) %>%
  layer_flatten() %>%
  layer_dense(units=100, activation="relu") %>%
  layer_dropout(rate=0.2) %>%
  layer_dense(units=1, activation="linear")

model %>% compile(
  loss = "mse",
  optimizer =  "adam", #'sgd' can also be used
  metrics = list("mean_absolute_error")
)

model %>% summary()
#> Model: "sequential"
#> ________________________________________________________________________________
#> Layer (type)                        Output Shape                    Param #     
#> ================================================================================
#> conv1d_1 (Conv1D)                   (None, 10, 32)                  160         
#> ________________________________________________________________________________
#> max_pooling1d_1 (MaxPooling1D)      (None, 5, 32)                   0           
#> ________________________________________________________________________________
#> conv1d (Conv1D)                     (None, 4, 64)                   4160        
#> ________________________________________________________________________________
#> max_pooling1d (MaxPooling1D)        (None, 2, 64)                   0           
#> ________________________________________________________________________________
#> dropout_1 (Dropout)                 (None, 2, 64)                   0           
#> ________________________________________________________________________________
#> flatten (Flatten)                   (None, 128)                     0           
#> ________________________________________________________________________________
#> dense_1 (Dense)                     (None, 100)                     12900       
#> ________________________________________________________________________________
#> dropout (Dropout)                   (None, 100)                     0           
#> ________________________________________________________________________________
#> dense (Dense)                       (None, 1)                       101         
#> ================================================================================
#> Total params: 17,321
#> Trainable params: 17,321
#> Non-trainable params: 0
#> ________________________________________________________________________________

history <- model %>% fit(dataTrain_x, dataTrain_y, 
                         epochs = 100, batch_size = 50, 
                         #callbacks = callback_tensorboard("logs/run_a"),
                         validation_split = 0.2)

reprex 包 (v2.0.0) 于 2021 年 7 月 20 日创建

Created on 2021-07-20 by the reprex package (v2.0.0)

这篇关于ValueError:在用户代码中,同时在 R 中使用 keras 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆