R interface to Keras

R interface to Keras
有多个版本的python时需要选择一个
sudo pip3 install virtualenv
#首先罗列出所有可用的 python 替代版本信息
update-alternatives --list python
#update-alternatives: error: no alternatives for python
如果出现以上所示的错误信息,则表示 Python 的替代版本尚未被 update-alternatives 命令识别

#--install 选项使用了多个参数用于创建符号链接。最后一个参数指定了此选项的优先级,如果我们没有手动来设置替代选项,那么具有最高优先级的选项就会被选中。
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.5 2
# update-alternatives --config python
python --version

安装

devtools::install_github("rstudio/keras")
library(keras)
install_tensorflow()
#安装GPU版本的tensorflow install_tensorflow(gpu=TRUE),https://rstudio.github.io/keras/

快速入门

Keras的核心数据结构是一个模型,是组织层次的一种方式。 最简单的模型是Sequential模型,一个线性层叠层。 对于更复杂的体系结构,您应该使用Keras功能API,这允许构建层的任意图形。 定义一个顺序模型:
library(keras)
model <- keras_model_sequential()
model %>%
layer_dense(units = 512, activation = 'relu', input_shape = c(784)) %>%
layer_dropout(rate = 0.2) %>%
layer_dense(units = 512, activation = 'relu') %>%
layer_dropout(rate = 0.2) %>%
layer_dense(units = 10, activation = 'softmax')
#使用summary()函数打印模型结构的摘要:
summary(model)
## Model
## ___________________________________________________________________________
## Layer (type) Output Shape Param #
## ===========================================================================
## dense_1 (Dense) (None, 512) 401920
## ___________________________________________________________________________
## dropout_1 (Dropout) (None, 512) 0
## ___________________________________________________________________________
## dense_2 (Dense) (None, 512) 262656
## ___________________________________________________________________________
## dropout_2 (Dropout) (None, 512) 0
## ___________________________________________________________________________
## dense_3 (Dense) (None, 10) 5130
## ===========================================================================
## Total params: 669,706
## Trainable params: 669,706
## Non-trainable params: 0
## ___________________________________________________________________________
##
##
采用适当的损失函数,优化器和矩阵创建模型:
model %>% compile(
loss = 'categorical_crossentropy',
optimizer = optimizer_sgd(lr = 0.02),
metrics = c('accuracy')
)
现在可以批量地迭代训练数据(x_trainy_train是矩阵):
history <- model %>% fit(
x_train, y_train,
epochs = 20, batch_size = 128,
validation_split = 0.2
)
绘制来自训练数据的损失和准确性指标:
plot(history)
评估测试数据的性能:
loss_and_metrics <- model %>% evaluate(x_test, y_test, batch_size = 128)
生成关于新数据的预测:
classes <- model %>% predict(x_test, batch_size = 128)

R中使用MLPMNIST手写数字进行分类

#https://www.analyticsvidhya.com/blog/2017/06/getting-started-with-deep-learning-using-keras-in-r/
library(keras)
#加载mnist数据集
data<-dataset_mnist()

#拆分训练集和测试集
train_x<-data$train$x
train_y<-data$train$y
test_x<-data$test$x
test_y<-data$test$y

rm(data)
2D数组转换为1D数组,送到MLP中,并进行归一化
train_x <- array(train_x, dim = c(dim(train_x)[1], prod(dim(train_x)[-1]))) / 255
test_x <- array(test_x, dim = c(dim(test_x)[1], prod(dim(test_x)[-1]))) / 255
使用keras内置函数将目标变量转换为one-hot编码
train_y<-to_categorical(train_y,10)
test_y<-to_categorical(test_y,10)
定义keras sequential model
model <- keras_model_sequential()
使用1个输入层[784个神经元]1个隐层[784个神经元],具有dropout 0.41个输出层[10个神经元]定义模型
model %>%
layer_dense(units = 784, input_shape = 784) %>%
layer_dropout(rate=0.4)%>%
layer_activation(activation = 'relu') %>%
layer_dense(units = 10) %>%
layer_activation(activation = 'softmax')
metric = precisionoptimiser作为adam编译定义的模型
model %>% compile(
loss = 'categorical_crossentropy',
optimizer = 'adam',
metrics = c('accuracy')
)
模型在训练数据集上拟合
model %>% fit(train_x, train_y, epochs = 100, batch_size = 128)
交叉验证数据集评估模型
loss_and_metrics <- model %>% evaluate(test_x, test_y, batch_size = 128)

上述代码的训练集准确率为99.14,验证准确率为96.89。 代码在i5处理器上运行,在单个epoch占用13.5秒,而在TITANx GPU上,验证精度为98.44,平均epoch2秒。

评论

此博客中的热门博文

V2ray websocket(ws)+tls+nginx分流

Rstudio 使用代理