# \donttest{
if (requireNamespace("keras3", quietly = TRUE)) {
library(keras3)
library(parsnip)
library(dials)
# 1. Define layer blocks for a complete model.
# The first block must initialize the model. `input_shape` is passed automatically.
input_block <- function(model, input_shape) {
keras_model_sequential(input_shape = input_shape)
}
# A block for hidden layers. `units` will become a tunable parameter.
hidden_block <- function(model, units = 32) {
model |> layer_dense(units = units, activation = "relu")
}
# The output block. `num_classes` is passed automatically for classification.
output_block <- function(model, num_classes) {
model |> layer_dense(units = num_classes, activation = "softmax")
}
# 2. Create the spec, providing blocks in the correct order.
create_keras_sequential_spec(
model_name = "my_mlp_seq_spec",
layer_blocks = list(
input = input_block,
hidden = hidden_block,
output = output_block
),
mode = "classification"
)
# 3. Use the newly created specification function!
# Note the new arguments `num_hidden` and `hidden_units`.
model_spec <- my_mlp_seq_spec(
num_hidden = 2,
hidden_units = 64,
epochs = 10,
learn_rate = 0.01
)
print(model_spec)
remove_keras_spec("my_mlp_seq_spec")
}
# }
Run the code above in your browser using DataLab