我在r中测试keras . 8个数字预测变量和6个类的分类响应变量 .
我知道我的例子是荒谬的 - 但我只想理解为什么keras没有运行 - 为什么我收到这个错误:
py_call_impl中的错误(callable,dots $ args,dots $ keywords):ValueError:检查目标时出错:期望dense_18具有形状(None,6)但得到形状的数组(1500,7)
# Create an artificial example with a categorical response variable:
set.seed(123)
y <- sample(1:6, 2000, replace = TRUE)
set.seed(1234)
x <- as.data.frame(matrix(rnorm(2000 * 8), nrow = 2000))
str(y)
str(x)
# Create a train-test split:
library(caret)
set.seed(12)
forTrain <- createDataPartition(y, p = 0.74887, list = FALSE)
x.train <- x[forTrain, ]
x.test <- x[-forTrain, ]
y.train <- y[forTrain]
y.test <- y[-forTrain]
dim(x.train)[1] == length(y.train)
length(y.train); length(y.test)
# Build network:
library(keras)
network <- keras_model_sequential() %>%
layer_dense(units = 100, activation = "relu", input_shape = c(1 * 8)) %>%
layer_dense(units = 6, activation = "softmax")
network %>% compile(
optimizer = "rmsprop",
loss = "categorical_crossentropy",
metrics = c("accuracy")
)
# Transform inputs:
x.train <- as.matrix(x.train)
x.test <- as.matrix(x.test)
x.train <- array_reshape(x.train, c(1500, 1 * 8))
x.test <- array_reshape(x.test, c(500, 1 * 8))
y.train <- to_categorical(y.train)
y.test <- to_categorical(y.test)
# Try to train:
network %>% fit(x.train, y.train, epochs = 5, batch_size = 25)
或者是错误,因为to_categorical由于某种原因创建7列?非常感谢你!
1 回答
我认为这是因为你的标签在[1,7]范围内,但对于
to_categorical
你应该有[0,6]范围内的标签 .与question相同 .