獨(dú)家 | 教你在R中使用Keras和TensorFlow構(gòu)建深度學(xué)習(xí)模型
引言:
在R和Python之間如何進(jìn)行選擇一直是一個(gè)熱議的話題。機(jī)器學(xué)習(xí)世界也被不同語言偏好所劃分。但是隨著深度學(xué)習(xí)的盛行,天平逐漸向Python傾斜,因?yàn)榻刂聊壳盀橹筆ython具有大量R所沒有的深度學(xué)習(xí)的資源庫和框架。
我個(gè)人從R轉(zhuǎn)到Python是因?yàn)槲蚁敫由钊霗C(jī)器學(xué)習(xí)的領(lǐng)域,而僅僅使用R的話,這(在之前)是幾乎不可能實(shí)現(xiàn)的事情。不過也僅此而已!
隨著Keras在R中的實(shí)現(xiàn),語言選擇的斗爭又重新回到舞臺(tái)中央。Python幾乎已經(jīng)慢慢變成深度學(xué)習(xí)建模的默認(rèn)語言,但是隨著在R中以TensorFlow(CPU和GPU均兼容)為后端的Keras框架的發(fā)行, 即便是在深度學(xué)習(xí)領(lǐng)域,R與Python搶占舞臺(tái)的戰(zhàn)爭也再一次打響。
下面我們將會(huì)看到怎樣在R中安裝以TensorFlow為基礎(chǔ)的Keras框架,然后在RStudio中構(gòu)建我們基于經(jīng)典MNIST數(shù)據(jù)集的***個(gè)神經(jīng)網(wǎng)絡(luò)模型。
內(nèi)容列表:
- 以TensorFlow為后端的Keras框架安裝
- 在R中可以使用Keras來構(gòu)建模型的不同類型
- 在R中使用MLP將MNIST手寫數(shù)字進(jìn)行歸類
- 將MNIST結(jié)果與Python中同等代碼結(jié)果進(jìn)行比較
- 結(jié)語
一、以TensorFlow為后端的Keras框架安裝
在RStudio中安裝Keras的步驟非常簡單。只要跟著以下步驟,你就可以在R中構(gòu)建你的***個(gè)神經(jīng)網(wǎng)絡(luò)模型。
- install.packages("devtools")
- devtools::install_github("rstudio/keras")
以上步驟會(huì)從Github資源庫下載Keras。現(xiàn)在是時(shí)候把keras加載進(jìn)R,然后安裝TensorFlow。
- library(keras)
在默認(rèn)情況下,RStudio會(huì)加載CPU版本的TensorFlow。如果沒有成功加載CPU版本的TensorFlow, 使用以下指令來下載。
- install_tensorflow()
如要為單獨(dú)用戶或桌面系統(tǒng)安裝GPU支持的TensorFlow,使用以下指令。
- install_tensorflow(gpu=TRUE)
為多重用戶安裝,請(qǐng)參考這個(gè)指南:https://tensorflow.rstudio.com/installation_gpu.html。
現(xiàn)在在我們的RStudio里,keras和TensorFlow都安裝完畢了。讓我們開始構(gòu)建***個(gè)在R中的神經(jīng)網(wǎng)絡(luò)來處理MNIST數(shù)據(jù)集吧。
二、在R中可以使用keras來構(gòu)建模型的不同類型
以下是可以在R中使用Keras構(gòu)建的模型列表
- 多層感知器(Multi-Layer Perceptrons)
- 卷積神經(jīng)網(wǎng)絡(luò)(Convoluted Neural Networks)
- 遞歸神經(jīng)網(wǎng)絡(luò)(Recurrent Neural Networks)
- Skip-Gram模型
- 使用預(yù)訓(xùn)練的模型(比如VGG16、RESNET等)
- 微調(diào)預(yù)訓(xùn)練的模型
讓我們從構(gòu)建僅有一個(gè)隱藏層的簡單MLP模型開始,來試著對(duì)手寫數(shù)字進(jìn)行歸類。
三、在R中使用MLP將MNIST手寫數(shù)字進(jìn)行歸類
- #loading keras library
- library(keras)
- #loading the keras inbuilt mnist dataset
- data<-dataset_mnist()
- #separating train and test file
- train_x<-data$train$x
- train_y<-data$train$y
- test_x<-data$test$x
- test_y<-data$test$y
- rm(data)
- # converting a 2D array into a 1D array for feeding into the MLP and normalising the matrix
- 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
- #converting the target variable to once hot encoded vectors using keras inbuilt function
- train_y<-to_categorical(train_y,10)
- test_y<-to_categorical(test_y,10)
- #defining a keras sequential model
- model <- keras_model_sequential()
- #defining the model with 1 input layer[784 neurons], 1 hidden layer[784 neurons] with dropout rate 0.4 and 1 output layer[10 neurons]
- #i.e number of digits from 0 to 9
- 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')
- #compiling the defined model with metric = accuracy and optimiser as adam.
- model %>% compile(
- loss = 'categorical_crossentropy',
- optimizer = 'adam',
- metrics = c('accuracy')
- )
- #fitting the model on the training dataset
- model %>% fit(train_x, train_y, epochs = 100, batch_size = 128)
- #Evaluating model on the cross validation dataset
- loss_and_metrics <- model %>% evaluate(test_x, test_y, batch_size = 128)
以上的代碼獲得了99.14%的訓(xùn)練精度和96.89%的驗(yàn)證精度。在我的i5處理器上跑這段代碼完整訓(xùn)練一次用時(shí)13.5秒,而在TITANx GPU上,驗(yàn)證精度可以達(dá)到98.44%,訓(xùn)練一次平均用時(shí)2秒。
四、使用keras來構(gòu)建MLP模型——R Vs. Python
為了更好地比較,我同樣使用Python來實(shí)現(xiàn)解決以上的MINIST歸類問題。結(jié)果不應(yīng)當(dāng)有任何差別,因?yàn)镽會(huì)創(chuàng)建一個(gè)進(jìn)程(conda instance)并在其中運(yùn)行keras。但你仍然可以嘗試以下同等的Python代碼。
- #importing the required libraries for the MLP model
- import keras
- from keras.models import Sequential
- import numpy as np
- #loading the MNIST dataset from keras
- from keras.datasets import mnist
- (x_train, y_train), (x_test, y_test) = mnist.load_data()
- #reshaping the x_train, y_train, x_test and y_test to conform to MLP input and output dimensions
- x_train=np.reshape(x_train,(x_train.shape[0],-1))/255
- x_test=np.reshape(x_test,(x_test.shape[0],-1))/255
- import pandas as pd
- y_train=pd.get_dummies(y_train)
- y_test=pd.get_dummies(y_test)
- #performing one-hot encoding on target variables for train and test
- y_train=np.array(y_train)
- y_test=np.array(y_test)
- #defining model with one input layer[784 neurons], 1 hidden layer[784 neurons] with dropout rate 0.4 and 1 output layer [10 #neurons]
- model=Sequential()
- from keras.layers import Dense
- model.add(Dense(784, input_dim=784, activation='relu'))
- keras.layers.core.Dropout(rate=0.4)
- model.add(Dense(10,input_dim=784,activation='softmax'))
- # compiling model using adam optimiser and accuracy as metric
- model.compile(loss='categorical_crossentropy', optimizer="adam", metrics=['accuracy'])
- # fitting model and performing validation
- model.fit(x_train,y_train,epochs=50,batch_size=128,validation_data=(x_test,y_test))
以上模型在同樣的GPU上達(dá)到了98.42%的驗(yàn)證精度。所以,就像我們?cè)谝婚_始猜測的那樣,結(jié)果是相同的。
五、結(jié)語
如果這是你用R構(gòu)建的***個(gè)深度學(xué)習(xí)模型,我希望你很享受這個(gè)過程。使用很簡單的代碼,你就可以對(duì)手寫數(shù)值進(jìn)行精確度達(dá)到98%的分類。這應(yīng)該可以給你足夠的動(dòng)力讓你在機(jī)器學(xué)習(xí)的領(lǐng)域探索。
如果你已經(jīng)在Python中使用過keras深度學(xué)習(xí)框架,那么你會(huì)發(fā)現(xiàn)R中keras框架的句式和結(jié)構(gòu)跟其在Python中非常相似。事實(shí)上,R中的keras安裝包創(chuàng)造了一個(gè)conda環(huán)境而且安裝了在該環(huán)境下運(yùn)行keras所需要的所有東西。但是,更讓我興奮的是:看到現(xiàn)在數(shù)據(jù)科學(xué)家們使用R構(gòu)建有關(guān)現(xiàn)實(shí)生活的深度學(xué)習(xí)模型。就像有句話說的一樣,競爭永不停歇。