How to implement a neural network model in R language?

In R language, you can implement a neural network model using the neuralnet package. Here is a simple example code:

# 安装并加载 neuralnet 包
install.packages("neuralnet")
library(neuralnet)

# 创建一个数据集
data <- data.frame(
  x1 = runif(100),
  x2 = runif(100),
  y = ifelse(x1 + x2 > 1, 1, 0)
)

# 创建神经网络模型
model <- neuralnet(
  y ~ x1 + x2,
  data = data,
  hidden = c(3), # 设置隐藏层神经元个数
  linear.output = FALSE # 输出层是否使用线性激活函数
)

# 预测
new_data <- data.frame(
  x1 = runif(10),
  x2 = runif(10)
)
predictions <- compute(model, new_data)
print(predictions$net.result)

In the code above, start by installing and loading the neuralnet package, then create a dataset. Next, use the neuralnet function to create a neural network model, specifying input features and output labels, setting the number of hidden layer neurons and the output layer activation function, and other parameters. Finally, make predictions on new data using the compute function.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds