您的数据不是最小的工作示例。
你的train 指的是没有给出的东西。没有人可以尝试您的代码。
因此没有人帮忙。
总是发布一个最小的工作示例 - 尽管你不经常看到它。这是快速获得答案的最快方法!
但是,我花了一些时间来回答这个问题。并创造了我需要的东西。
在虚拟环境中安装keras 和R
我使用 conda,创建虚拟环境 - 因为当您必须安装像 keras 这样的复杂软件包时,它可以节省大量工作。
# create new environment in conda
conda create --name newR
# enter new environment
conda activate newR
# install 'keras' package - and at the same time R and
# everything you need to run keras properly.
conda install -c r r-keras
# enter R
R
# to fully intall 'keras' with 'tensorflow', do
require(keras)
install_keras()
# so easy the installation is with conda ... 5 min maybe.
生成数据
由于你没有给出示例数据,我拿了虹膜数据。
data(iris)
X <- iris[, 1:4]
y <- as.numeric(iris[, 5])
你提供的数据想要做回归,但是鸢尾花的标签y
是分类数据。我在分类数据上应用了as.numeric() 以使其成为数字。
试试你给定的代码
然后,我拿走了你的代码,将train 更改为X 和train_labels 为y。
build_model <- function() {
model <- keras_model_sequential() %>%
layer_dense(units = 5, activation = "relu",
input_shape = dim(X)[2]) %>%
layer_dense(units = 5, activation = "relu") %>%
layer_dense(units = 1)
model %>% compile(
loss = "mse",
optimizer = optimizer_rmsprop(),
metrics = list("mean_absolute_error")
)
model
}
print_dot_callback <- callback_lambda(
on_epoch_end = function(epoch, logs) {
if (epoch %% 80 == 0) cat("\n")
cat(".")
}
)
epochs <- 200
history <- model %>% fit(
as.matrix(X),
y,
epochs = epochs,
validation_split = 0.2,
verbose = 0,
callbacks = list(print_dot_callback)
)
它运行顺利,没有任何错误! (点)。
>history
Trained on 120 samples (batch_size=32, epochs=200)
Final epoch (plot to see history):
loss: 0.04127
mean_absolute_error: 0.1497
val_loss: 0.1147
val_mean_absolute_error: 0.2761
# save model
keras::save_model_hdf5(model, filepath = "test_rkeras.h5")
# load model
keras::load_model_hdf5("test_rkeras.h5")
导致:
Model
________________________________________________________________________________
Layer (type) Output Shape Param #
================================================================================
dense (Dense) (None, 5) 25
________________________________________________________________________________
dense_1 (Dense) (None, 5) 30
________________________________________________________________________________
dense_2 (Dense) (None, 1) 6
================================================================================
Total params: 61
Trainable params: 61
Non-trainable params: 0
________________________________________________________________________________
所以效果很好!
结论
这证明你的模型和代码是有效的。
只是您的输入数据一定是问题所在!
使用str(train) 检查其结构。它应该是一个简单的二维数字矩阵!你的标签/目标向量是一个简单的数字向量吗?
大多数错误发生在读入数据时。
读入一些数据后,请务必检查数据是否符合您的预期!