R深度学习——Keras入门
在人工智能时代到来之际,最成熟的AI框架莫过于Tensorflow,但其构建是基于Python的,但我们作为熟练R语言的数据科学家,也想使用Tensorflow,这一梦想Rstudio已经帮我们实现,这里将介绍如何在R中装配和运行Tensorflow的上层Keras框架:
install.packages("keras")
首先安装keras包,默认将Tensorflow作为其后端引擎,要安装核心Keras库和Tensorflow引擎:
library(keras)
install_keras()
这时CPU版Keras的安装方法,如果想体验GPU编程,可以看该函数的文档。
这一章我们遵守惯例深入MNIST数据集,如果想进一步了解深度学习和Keras应用,可以了解Deep Learning with R一书
首先我们将数据集分为训练集和测试集:
library(keras)
mnist <- dataset_mnist()
x_train <- mnist$train$x
y_train <- mnist$train$y
x_test <- mnist$test$x
y_test <- mnist$test$y
x数据集存储了(images, width, height)三维像素值,我们将其宽和高的量降维,变为一个matrice,再将像素值标准化:
# reshape
x_train <- array_reshape(x_train, c(nrow(x_train), 784))
x_test <- array_reshape(x_test, c(nrow(x_test), 784))
# rescale
x_train <- x_train / 255
x_test <- x_test / 255
这里使用了array_reshape()函数而不是dim()函数,是因为我们想使用以行为主的语义符而不是R默认的以列为主的语义符。
y数据集代表了0-9的数字,我们使用to_ategorical()使其可以用于分类:
y_train <- to_categorical(y_train, 10)
y_test <- to_categorical(y_test, 10)
模型的建立我们使用Sequential model:
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')
这里输入的input_shape指定了输入值的维度,最后一层units = 10表示输出对各个数值的概率,使用softmax**函数,我们可以用summary()看模型结构:
summary(model)
Model
Layer (type) Output Shape Param
==================================================================
dense_1 (Dense) (None, 256) 200960
dropout_1 (Dropout) (None, 256) 0
dense_2 (Dense) (None, 128) 32896
dropout_2 (Dropout) (None, 128) 0
dense_2 (Dense) (None, 10) 1290
==================================================================
Total params: 235,146
Trainable params: 235,146
Non-trainable params: 0
再将模型进行编译,给予合适的损失函数,优化器,矩阵:
model %>% compile(
loss = 'categorical_crossentropy',
optimizer = optimizer_rmsprop(),
metrics = c('accuracy')
)
模型训练:
history <- model %>% fit(
x_train, y_train,
epochs = 30, batch_size = 128,
validation_split = 0.2
)
plot(history)
再评估其对测试集的效果:
model %>% evaluate(x_test, y_test)
$loss
[1] 0.1149
$acc
[1] 0.9807
对新的数据集进行预测:
model %>% predict_classes(x_test)