深度學習之在iOS上運行CNN

1 引言

作爲曾經的iOS開發者,在研究深度學習的時候,總有一個想法就是在iPhone上運行深度學習,不管是在手機上訓練還是利用訓練好的數據進行測試。
因爲iOS的開發環境支持C++,因此,只要你的代碼是C/C++,本質上就可以在iOS上運行。
怎麼才能更快更好地在iOS上運行CNN呢?

2 方法1:通過Matlab轉碼

Matlab自帶轉成c的工具,如果你研究過UFLDL的深度學習教程,就知道如何在Matlab上使用CNN,那麼,轉換成c後,放到iOS的開發環境中,然後將參數存成txt格式再讀取分割,也就是可以實現。
如下圖就是已經將matlab代碼轉換爲c後導入的結果:
這裏寫圖片描述
打開predict.h文件,可以看到可以調用的接口:

/* Function Declarations */
extern real_T predict(const real_T Theta1[10025], const real_T Theta2[260], const real_T X[400]);

這是訓練MNIST的一個神經網絡,我這邊用了測試手寫數字的識別。

因此,接下來需要對圖片進行處理,從而轉換爲x[400]的向量格式。

這個只要能讀取圖片的像素,進行轉換就可以。可以考慮用opencv來實現。

這裏寫圖片描述
這裏我的方法是在用手畫出數字之後,將圖片轉換爲20*20像素的圖片,如右下角所示,再將右下角的圖片轉換爲400的數組,輸入predict得到的結果。

3 方法2:使用DeepBeliefSDK

https://github.com/jetpacapp/DeepBeliefSDK
這個是別人專門寫的一個用於iOS的深度學習的SDK。可以使用,但是存在的問題就是如果要自己訓練的話很受限制。

4 方法3:使用tinyCNN

https://github.com/nyanp/tiny-cnn
這個很不錯,它對比Caffe,Theano等框架最大的特點就是不需要安裝,只要能用C++ 11.然後裏面的例子使用了boost庫。因此,爲了運行它,我們需要在xcode安裝ios的boost庫。

網上找到了一個編譯好的boost庫:
https://github.com/danoli3/ofxiOSBoost

導入boost庫的方法非常簡單:

In Xcode Build Settings for your project:

Add to Library Search Paths ( LIBRARY_SEARCH_PATHS ) $(SRCROOT)/../../../addons/ofxiOSBoost/libs/boost/lib/ios
Add to Header Search Paths ( HEADER_SEARCH_PATHS )
$(SRCROOT)/../../../addons/ofxiOSBoost/libs/boost/include
In the Target under Build Phases

Add to 'Link Binary With Libraries' the boost.a found in the ofxiOSBoost/libs/boost/lib/ios directory.
If not openFrameworks just add the libs/boost/include to Header Search Paths and the libs/boost/ios to Library Search Paths

那麼具體在創建iOS應用的時候,這裏使用作者提供的訓練MNIST的例子,那麼要注意在使用數據時,要更改路徑:

NSString *trainLabels = [[NSBundle mainBundle] pathForResource:@"train-labels" ofType:@"idx1-ubyte"];
    NSString *trainImages = [[NSBundle mainBundle] pathForResource:@"train-images" ofType:@"idx3-ubyte"];
    NSString *t10kLabels = [[NSBundle mainBundle] pathForResource:@"t10k-labels" ofType:@"idx1-ubyte"];
    NSString *t10kImages = [[NSBundle mainBundle] pathForResource:@"t10k-images" ofType:@"idx3-ubyte"];


    parse_mnist_labels([trainLabels cStringUsingEncoding:NSUTF8StringEncoding], &train_labels);
    parse_mnist_images([trainImages cStringUsingEncoding:NSUTF8StringEncoding], &train_images);
    parse_mnist_labels([t10kLabels cStringUsingEncoding:NSUTF8StringEncoding], &test_labels);
    parse_mnist_images([t10kImages cStringUsingEncoding:NSUTF8StringEncoding], &test_images);

基本上這樣就可以運行開始訓練了。

如果想在Mac上訓練,同樣需要安裝boost庫。這個只要在官網下載boost,我用的是1.58版本。然後在terminal中安裝,cd到路徑,然後./boostrap.sh 然後./b2 安裝就可以。然後在xcode引入路徑:

The Boost C++ Libraries were successfully built!

The following directory should be added to compiler include paths:

    /Users/.../.../.../boost

The following directory should be added to linker library paths:

    /Users/.../.../.../boost/stage/lib

路徑初始爲自己boost的文件夾地址。

4 小結

上面說了一些很方便的方法來實現在iOS下運行CNN。當然,我們更多需要就是進行圖像的識別。相信大家自己測試會覺得很有趣。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章