The “neuralnet” Function in R

  • Package: neuralnet

  • Purpose: Train and fit a neural network model.

  • General class: Model

  • Required argument(s):

    • formula: A formula specifying the model structure (e.g., response ~ predictors).

    • data: Data frame containing the variables in the formula.

    • hidden: A vector specifying the number of neurons in each hidden layer.

  • Notable optional arguments:

    • linear.output: Boolean indicating if the output should be linear (default is TRUE).

    • threshold: A numeric value to set the stopping criterion based on the threshold for error reduction.

    • stepmax: Maximum number of steps for the training process.

    • learningrate: The learning rate used for training the network.

  • Example:

  • # Load the required library
    library(neuralnet)

    # Example dataset
    data(iris)

    # Fit a neural network model
    model <- neuralnet(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = iris, hidden = c(5, 3), linear.output = FALSE)

    # Print the model summary
    print(model)

    # Predict on the same dataset
    predictions <- predict(model, iris)
    head(predictions)

  • In this example, the neuralnet function is used to fit a neural network model to the iris dataset. The formula specifies that the model should predict Species based on the four features. The hidden argument specifies a network with two hidden layers (5 and 3 neurons). The linear.output = FALSE argument indicates that the output should be a classification. The function outputs the model, and predictions are made on the same dataset.

Previous
Previous

The “map” Function in R

Next
Next

The “predict” Function in R