R語言中不能進行深度學習?
更多深度文章,請關注:https://yq.aliyun.com/cloud
眾所周知,R語言是統計分析最好用的語言。但在Keras和TensorFlow的幫助下,R語言也可以進行深度學習了。
在機器學習的語言的選擇上,R和Python之間選擇一直是一個有爭議的話題。但隨著深度學習的爆炸性增長,越來越多的人選擇了Python,因為它有一個很大的深度學習庫和框架,而R卻沒有(直到現在)。
但是我就是想使用R語言進入深度學習空間,所以我就從Python領域轉入到了R領域,繼續我的深度學習的研究了。這可能看起來幾乎不可能的。但是今天這變成了可能。
隨著Keras在R上的推出,R與Python的鬥爭回到了中心。Python慢慢成為了最流行的深度學習模型。但是,隨著Keras庫在R後端的發布,並且在後台還可以使用張力流(TensorFlow)(CPU和GPU兼容性),所以在深度學習領域,R將再次與Python打成平手。
下麵我們將看到如何使用Tensorflow在R中安裝Keras,並在RStudio的經典MNIST數據集上構建我們的第一個神經網絡模型。
目錄:
1.在後端安裝帶有張量的Keras。
2.使用Keras可以在R中構建不同類型的模型。
3.在R中使用MLP對MNIST手寫數字進行分類。
4.將MNIST結果與Python中的等效代碼進行比較。
5.結束筆記。
1.在後端安裝帶有TensorFlow的Keras。
在RStudio中安裝Keras的步驟非常簡單。隻需按照以下步驟,您將很順利的在R中創建您的第一個神經網絡模型。
install.packages("devtools")
devtools::install_github("rstudio/keras")
上述步驟將從GitHub倉庫加載keras庫。現在是將keras加載到R並安裝TensorFlow的時候了。
library(keras)
默認情況下,RStudio加載TensorFlow的CPU版本。使用以下命令下載TensorFlow的CPU版本。
install_tensorflow()
要為單個用戶/桌麵係統安裝具有GPU支持的TensorFlow版本,請使用以下命令。
install_tensorflow(gpu=TRUE)
有關更多的用戶安裝,請參閱本安裝指南。
現在我們在RStudio中安裝了keras和TensorFlow,讓我們在R中啟動和構建我們的第一個神經網絡來解決MNIST數據集
2.使用keras可以在R中構建的不同類型的模型
以下是使用Keras可以在R中構建的模型列表。
1.多層感知器
2.卷積神經網絡
3.循環神經網絡
4.Skip-Gram模型
5.使用預先訓練的模型,如VGG16,RESNET等
6.微調預先訓練的模型。
讓我們開始構建一個非常簡單的MLP模型,隻需一個隱藏的層來嚐試分類手寫數字。
3.使用R中的MLP對MNIST手寫數字進行分類
#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,驗證準確率為96.89。代碼在i5處理器上運行,運行時間為13.5秒,而在TITANx GPU上,驗證精度為98.44,平均運行時間為2秒。
4.MLP使用keras–R VS Python
為了比較起見,我也在Python中實現了上述的MNIST問題。我覺得在keras-R和Python中應該沒有任何區別,因為R中的keras創建了一個conda實例並在其中運行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上實現了98.42的驗證精度。所以,我們最初猜到的結果是正確的。
5.結束筆記
如果這是你在R的第一個深度學習模型,我希望你喜歡它。通過一個非常簡單的代碼,您可以有98%位準確率對是否為手寫數字進行分類。這應該是足夠的動力讓你開始深度學習。
如果您已經在Python中使用keras深度學習庫,那麼您將在R中找到keras庫的語法和結構與Python中相似的地方。事實上,R中的keras包創建了一個conda環境,並安裝了在該環境中運行keras所需的一切。但是,讓我更為激動的是,現在看到數據科學家在R中建立現實生活中的深層次的學習模型。據說 - 競爭應該永遠不會停止。我也想聽聽你對這一新發展觀點的看法。你可以在下麵留言分享你的看法。
本文由北郵@愛可可-愛生活老師推薦,阿裏雲雲棲社區組織翻譯。
文章原標題《Getting started with Deep Learning using Keras and TensorFlow in R》,作者: ,
譯者:袁虎,審閱: 阿福
文章為簡譯,更為詳細的內容,請查看原文
最後更新:2017-06-23 23:02:46