I have the below code which uses the iris
data set to train a number of Machine Learning models:
I want to make predictions for the keras
model. The below code works and I am able to obtain predictions for all the models (except the keras
model):
When I uncomment the else if
- keras
part of the code I obtain "errors" or the model produces.
[1] "skipping\n"
[1] "skipping\n"
[1] "skipping\n"
[1] "skipping\n"
[1] "skipping\n"
[1] "skipping\n"
[1] "skipping\n"
[1] "skipping\n"
[1] "skipping\n"
[1] "skipping\n"
[1] "skipping\n"
[1] "skipping\n"
My question is where am I going wrong on the keras
predict part? I want to modify this part of the code such that it will give me predicted classes:
# else if(attr(x, "class")[1] == "keras_training_history"){
# # Keras Single Layer Neural Network
# tibble(
# modelname = attr(x, "class")[1],
# prediction = predict_classes(object = x, x = as.matrix(dat))
# )
# }
EDIT 1:
My attempt at the debugging:
dat <- iris %>%
filter(Species != "setosa") %>%
mutate(Species = +(Species == "virginica"))
mod <- keras_model_sequential() %>%
layer_dense(units = 2, activation = 'relu', input_shape = 2) %>%
layer_dense(units = 2, activation = 'softmax')
mod
mod %>% compile(
loss = 'binary_crossentropy',
optimizer_sgd(lr = 0.01, momentum = 0.9),
metrics = c('accuracy')
)
mod
fit(mod,
x = as.matrix(dat[, 2:3]),
y = to_categorical(dat$Species, 2),
epochs = 5,
batch_size = 5,
validation_split = 0
)
predict_classes(mod, as.matrix(dat[, 2:3]))
Gives me:
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[44] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[87] 0 0 0 0 0 0 0 0 0 0 0 0 0 0
EDIT:
When I run the code in EDIT 1. and then pass:
attr(mod, "class")
I get the following output:
[1] "keras.engine.sequential.Sequential"
[2] "keras.engine.training.Model"
[3] "keras.engine.network.Network"
[4] "keras.engine.base_layer.Layer"
[5] "tensorflow.python.module.module.Module"
[6] "tensorflow.python.training.tracking.tracking.AutoTrackable"
[7] "tensorflow.python.training.tracking.base.Trackable"
[8] "python.builtin.object"
However when I run the models_list
code and then run the following:
attr(models_list[[1]]$models$Model_Keras, "class")
I get:
[1] "keras_training_history"
So I am passing a different function to the predict
. Therefore I am starting to think the code when building the model stores the data incorrectly.