# \donttest{
if (torch::torch_is_installed()) {
# Matrix method — no preprocessing
model = train_nn(
x = as.matrix(iris[, 2:4]),
y = iris$Sepal.Length,
hidden_neurons = c(64, 32),
activations = "relu",
epochs = 50
)
# Data frame method — y as a vector
model = train_nn(
x = iris[, 2:4],
y = iris$Sepal.Length,
hidden_neurons = c(64, 32),
activations = "relu",
epochs = 50
)
# Data frame method — y as a formula evaluated against x
model = train_nn(
x = iris,
y = Sepal.Length ~ . - Species,
hidden_neurons = c(64, 32),
activations = "relu",
epochs = 50
)
# Formula method — outcome derived from formula
model = train_nn(
x = Sepal.Length ~ .,
data = iris[, 1:4],
hidden_neurons = c(64, 32),
activations = "relu",
epochs = 50
)
# No hidden layers — linear model
model = train_nn(
x = Sepal.Length ~ .,
data = iris[, 1:4],
epochs = 50
)
# Architecture object (nn_arch -> train_nn)
mlp_arch = nn_arch(nn_name = "mlp_model")
model = train_nn(
x = Sepal.Length ~ .,
data = iris[, 1:4],
hidden_neurons = c(64, 32),
activations = "relu",
architecture = mlp_arch,
epochs = 50
)
# Custom layer architecture
custom_linear = torch::nn_module(
"CustomLinear",
initialize = function(in_features, out_features, bias = TRUE) {
self$layer = torch::nn_linear(in_features, out_features, bias = bias)
},
forward = function(x) self$layer(x)
)
custom_arch = nn_arch(
nn_name = "custom_linear_mlp",
nn_layer = ~ custom_linear
)
model = train_nn(
x = Sepal.Length ~ .,
data = iris[, 1:4],
hidden_neurons = c(16, 8),
activations = "relu",
architecture = custom_arch,
epochs = 50
)
# With early stopping
model = train_nn(
x = Sepal.Length ~ .,
data = iris[, 1:4],
hidden_neurons = c(64, 32),
activations = "relu",
epochs = 200,
validation_split = 0.2,
early_stopping = early_stop(patience = 10)
)
}
# }
# \donttest{
if (torch::torch_is_installed()) {
# torch dataset method — labels come from the dataset itself
iris_cls_dataset = torch::dataset(
name = "iris_cls_dataset",
initialize = function(data = iris) {
self$x = torch::torch_tensor(
as.matrix(data[, 1:4]),
dtype = torch::torch_float32()
)
# Species is a factor; convert to integer (1-indexed -> keep as-is for cross_entropy)
self$y = torch::torch_tensor(
as.integer(data$Species),
dtype = torch::torch_long()
)
},
.getitem = function(i) {
list(self$x[i, ], self$y[i])
},
.length = function() {
self$x$size(1)
}
)()
model_nn_ds = train_nn(
x = iris_cls_dataset,
hidden_neurons = c(32, 10),
activations = "relu",
epochs = 80,
batch_size = 16,
learn_rate = 0.01,
n_classes = 3, # Iris dataset has only 3 species
validation_split = 0.2,
verbose = TRUE
)
pred_nn = predict(model_nn_ds, iris_cls_dataset)
class_preds = c("Setosa", "Versicolor", "Virginica")[predict(model_nn_ds, iris_cls_dataset)]
# Confusion Matrix
table(actual = iris$Species, pred = class_preds)
}
# }
Run the code above in your browser using DataLab