卷积神经网络的R语言代码
时间: 2023-07-16 16:12:05 浏览: 208
以下是一个简单的卷积神经网络的R语言代码示例:
```R
library(keras)
# 设置模型参数
batch_size <- 128
num_classes <- 10
epochs <- 12
# 输入图像维度
img_rows <- 28
img_cols <- 28
# 加载 MNIST 数据集
mnist <- dataset_mnist()
x_train <- mnist$train$x
y_train <- mnist$train$y
x_test <- mnist$test$x
y_test <- mnist$test$y
# 数据预处理
x_train <- array_reshape(x_train, c(nrow(x_train), img_rows, img_cols, 1))
x_test <- array_reshape(x_test, c(nrow(x_test), img_rows, img_cols, 1))
x_train <- x_train / 255
x_test <- x_test / 255
y_train <- to_categorical(y_train, num_classes)
y_test <- to_categorical(y_test, num_classes)
# 定义模型
model <- keras_model_sequential() %>%
layer_conv_2d(filters = 32, kernel_size = c(3, 3), activation = "relu",
input_shape = c(img_rows, img_cols, 1)) %>%
layer_conv_2d(filters = 64, kernel_size = c(3, 3), activation = "relu") %>%
layer_max_pooling_2d(pool_size = c(2, 2)) %>%
layer_dropout(rate = 0.25) %>%
layer_flatten() %>%
layer_dense(units = 128, activation = "relu") %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = num_classes, activation = "softmax")
# 编译模型
model %>% compile(
loss = "categorical_crossentropy",
optimizer = optimizer_adadelta(),
metrics = c("accuracy")
)
# 训练模型
model %>% fit(
x_train, y_train,
batch_size = batch_size,
epochs = epochs,
verbose = 1,
validation_data = list(x_test, y_test)
)
# 评估模型
score <- model %>% evaluate(x_test, y_test, verbose = 0)
cat("Test loss:", score[[1]], "\n")
cat("Test accuracy:", score[[2]], "\n")
```
这个模型使用了两个卷积层和一个最大池化层来提取图像的特征,然后使用两个全连接层来进行分类。在训练过程中,我们使用了 Adadelta 优化器和交叉熵损失函数来最小化模型的误差,并且使用了 Dropout 技术来防止过拟合。最终,我们得到了一个在 MNIST 数据集上达到了 99% 的准确率的模型。
阅读全文