🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# R 中的 Keras API 我们在第 3 章中了解了 Keras API。在 R 中,此 API 使用`keras` R 包实现。 `keras` R 软件包实现了 Keras Python 接口的大部分功能,包括顺序 API 和函数式 API。 作为示例,我们提供了 MLP 模型的演练,用于在以下链接中对来自 MNIST 数据集的手写数字进行分类: [https://keras.rstudio.com/articles/examples/mnist_mlp.html](https://keras.rstudio.com/articles/examples/mnist_mlp.html) 。 您可以按照 Jupyter R 笔记本中的代码`ch-17c_Keras_in_R`。 1. 首先,加载库: ```r library(keras) ``` 1. 定义超参数: ```r batch_size <- 128 num_classes <- 10 epochs <- 30 ``` 1. 准备数据: ```r # The data, shuffled and split between train and test sets c(c(x_train, y_train), c(x_test, y_test)) %<-% dataset_mnist() x_train <- array_reshape(x_train, c(nrow(x_train), 784)) x_test <- array_reshape(x_test, c(nrow(x_test), 784)) # Transform RGB values into [0,1] range x_train <- x_train / 255 x_test <- x_test / 255 cat(nrow(x_train), 'train samples\n') cat(nrow(x_test), 'test samples\n') # Convert class vectors to binary class matrices y_train <- to_categorical(y_train, num_classes) y_test <- to_categorical(y_test, num_classes) ``` 注释是不言自明的:数据从 Keras 数据集库加载,然后转换为 2D arrray 并归一化为[0,1]范围。 1. 定义模型: ```r model <- keras_model_sequential() model %>% layer_dense(units=256,activation='relu',input_shape=c(784)) %>% layer_dropout(rate = 0.4) %>% layer_dense(units = 128, activation = 'relu') %>% layer_dropout(rate = 0.3) %>% layer_dense(units = 10, activation = 'softmax') summary(model) model %>% compile( loss = 'categorical_crossentropy', optimizer = optimizer_rmsprop(), metrics = c('accuracy') ) ``` 1. 定义和编译顺序模型。我们得到的模型定义如下: ```r _____________________________________________________ Layer (type) Output Shape Param # ===================================================== dense_26 (Dense) (None, 256) 200960 _____________________________________________________ dropout_14 (Dropout) (None, 256) 0 _____________________________________________________ dense_27 (Dense) (None, 128) 32896 _____________________________________________________ dropout_15 (Dropout) (None, 128) 0 _____________________________________________________ dense_28 (Dense) (None, 10) 1290 ===================================================== Total params: 235,146 Trainable params: 235,146 Non-trainable params: 0 ``` 1. 训练模型: ```r history <- model %>% fit( x_train, y_train, batch_size = batch_size, epochs = epochs, verbose = 1, validation_split = 0.2 ) plot(history) ``` 拟合函数的输出存储在历史对象中,其包含来自训练周期的损失和度量值。绘制历史对象中的数据,结果如下: ![](https://img.kancloud.cn/93/f3/93f3dc15b5dbaf685aa13d65bcdd33f4_840x840.png)Training and Validation Accuracy (y-axis) in Epochs (x-axis) 1. 评估模型: ```r score <- model %>% evaluate( x_test, y_test, verbose = 0 ) # Output metrics cat('Test loss:', score[[1]], '\n') cat('Test accuracy:', score[[2]], '\n') ``` 输出如下: ```r Test loss: 0.1128517 Test accuracy: 0.9816 ``` 太酷!! 在以下链接中查找更多关于 Keras in R 的示例:[https://keras.rstudio.com/articles/examples/index.html ](https://keras.rstudio.com/articles/examples/index.html) 有关 Keras R 软件包的更多文档可在以下链接中找到:[https://keras.rstudio.com/reference/index.html](https://keras.rstudio.com/reference/index.html)