四、Core ML模型的熱更新

關鍵詞:
Core ML,熱更新,動態(tài)部署,動態(tài)加載

《二、使用Core ML加載.mlmodel模型文件》中我們介紹了如何加載并使用.mlmodel模型文件,但是這里是在coding階段,將模型文件加入到項目中的,這里存在一些問題:

  • 模型文件動輒幾十兆,這將增加安裝包的大小
  • 很多模型會被在線數(shù)據(jù)不停的訓練,參數(shù)經(jīng)常發(fā)生變化,每次跟新都要打一個包發(fā)版,這是非常麻煩的事情

于是我們想:mlmodel文件,能不能通過下載的方式加載到項目中呢?為了解決這個問題,我們需要做兩件事情:

  1. mlmodel文件,要以下載的方式獲取;
  2. 我們需要自己生成模型對應的類;

本文將探索如何達成此目的。

本文中會將mlmodel以資源文件的形式加入到項目中,以此模擬下載。另外,請首先閱讀《二、使用Core ML加載.mlmodel模型文件》

一、準備一個Core ML模型

Core ML模型文件一般以.mlmodel作為后綴,我們可以通過很多途徑獲得一個已經(jīng)訓練好的模型,最直接的方式,就是從蘋果官網(wǎng)上直接下載。

二、查看.mlmodel對應的類

首先,我們將一個mlmodel模型拖到項目中,然后查看對應類的頭文件(具體請參考《二、使用Core ML加載.mlmodel模型文件》)。

在頭文件任意位置右擊鼠標,點擊Show in Finder,我們可以看到一對文件,我們把它們加入到項目中來。

打開m文件,我們找到他的init方法以及init方法中調用的一個類方法:

+ (NSURL *)urlOfModelInThisBundle {
    NSString *assetPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"MobileNet" ofType:@"mlmodelc"];
    return [NSURL fileURLWithPath:assetPath];
}

- (nullable instancetype)init {
        return [self initWithContentsOfURL:self.class.urlOfModelInThisBundle error:nil];
}

三、模型編譯

我們注意到,這里的type是一個mlmodelc文件,這個c是什么意思呢?我們可以看一下蘋果官方的這篇文檔:

https://developer.apple.com/documentation/coreml/mlmodel/2921516-compilemodelaturl?language=objc

也就是說,mlmodel文件,是要首先被編譯成mlmodelc文件,才可以被加載的。那么,我們的思路就很清晰了,我們只需要做如下幾件事情:

  1. 從服務器上獲取最新的.mlmodel模型文件,存到本地沙盒中。
  2. 使用compileModelAtURL:error:方法,編譯mlmodel文件,并獲得mlmodelc文件的路徑URL。
  3. 自己寫一個模型類,來封裝一些方法,比如我們可以直接將之前自動生成的類拷貝過來即可,如果對Coding Style有要求的同學可以自行修改一下命名。
  4. 使用initWithContentsOfURL:error:方法初始化模型類并使用他進行預測。

有英文閱讀能力的同學,也可以看這篇蘋果的官方介紹。值得注意的是,這邊官方介紹中提到:

To limit the use of bandwidth, avoid repeating the download and compile processes when possible. The model is compiled to a temporary location. If the compiled model can be reused, move it to a permanent location, such as your app's support directory.

compileModelAtURL:error:方法會將編譯后的文件存儲到臨時文件夾中,如果希望編譯后的文件被復用,可以將其移動到持久化存儲的文件夾中。文中還給出了一段示例代碼:

// find the app support directory
let fileManager = FileManager.default
let appSupportDirectory = try! fileManager.url(for: .applicationSupportDirectory,
        in: .userDomainMask, appropriateFor: compiledUrl, create: true)
// create a permanent URL in the app support directory
let permanentUrl = appSupportDirectory.appendingPathComponent(compiledUrl.lastPathComponent)
do {
    // if the file exists, replace it. Otherwise, copy the file to the destination.
    if fileManager.fileExists(atPath: permanentUrl.absoluteString) {
        _ = try fileManager.replaceItemAt(permanentUrl, withItemAt: compiledUrl)
    } else {
        try fileManager.copyItem(at: compiledUrl, to: permanentUrl)
    }
} catch {
    print("Error during copy: \(error.localizedDescription)")
}

接下來,讓我們嘗試完成Demo。

四、準備服務器

首先我們需要準備一個可供下載MobileNet.mlmodel的服務器,我是借助于http-server,用自己的電腦提供MobileNet.mlmodel的下載。這一步大家就各憑本事,自由發(fā)揮了。

五、準備一個iOS項目

同樣,大家可以自己創(chuàng)建一個項目,或者直接clone我的初始項目:

git clone git@github.com:yangchenlarkin/CoreML.git

我們需要在DynamicLoading/DLViewController.m文件最末的download方法中添加代碼,完成模型下載和編譯,并將編譯后的mlmodelc文件,移動到documents文件夾中。

然后在ObjectRecognition/ORViewController.m最末的predict中加載mlmodelc文件,并完成預測。

六、下載并編譯模型文件

首先打開DynamicLoading/DLViewController.m文件,添加如下代碼:

#import <CoreML/CoreML.h>

在最末實現(xiàn)download函數(shù):


- (void)download {
    NSData *data = nil;
    //下載數(shù)據(jù),下載鏈接請?zhí)鎿Q成自己的
    NSURL *url = [NSURL URLWithString:@"http://192.168.31.121:8080/MobileNet.mlmodel"];
    data = [NSData dataWithContentsOfURL:url];
    
    //我們暫時就將文件存儲到存到臨時文件夾中吧
    NSString *tmpPath = NSTemporaryDirectory();
    NSString *tmpModelPath = [tmpPath stringByAppendingPathComponent:@"MobileNet.mlmodel"];
    [data writeToFile:tmpModelPath atomically:YES];
    
    //編譯文件
    NSError *error = nil;
    NSURL *tmpModelcPathURL = [MLModel compileModelAtURL:[NSURL fileURLWithPath:tmpModelPath] error:nil];
    if (error) {
        NSLog(@"%@", error);
        return;
    }
    
    //拷貝文件到Document文件夾
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *docModelcPath = [docPath stringByAppendingPathComponent:@"MobileNet.mlmodelc"];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager moveItemAtURL:tmpModelcPathURL toURL:[NSURL fileURLWithPath:docModelcPath] error:&error];
    if (error) {
        NSLog(@"%@", error);
        return;
    }
}

七、編寫模型類

我們可以直接使用二、查看.mlmodel對應的類中找到的MobileNet類,也可以自己重新寫一個,我這里將直接使用這個類:

MobileNet類

八、讀取mlmodelc文件并完成預測

打開ObjectRecognition/ORViewController.m文件,首先你需要引入MobileNet類:

#import "MobileNet.h"

然后參考《二、使用Core ML加載.mlmodel模型文件》添加圖像處理代碼:

#pragma mark - predict

- (UIImage *)scaleImage:(UIImage *)image size:(CGFloat)size {
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(size, size), YES, 1);
    
    CGFloat x, y, w, h;
    CGFloat imageW = image.size.width;
    CGFloat imageH = image.size.height;
    if (imageW > imageH) {
        w = imageW / imageH * size;
        h = size;
        x = (size - w) / 2;
        y = 0;
    } else {
        h = imageH / imageW * size;
        w = size;
        y = (size - h) / 2;
        x = 0;
    }
    
    [image drawInRect:CGRectMake(x, y, w, h)];
    UIImage * scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

- (CVPixelBufferRef)pixelBufferFromCGImage:(CGImageRef)image {
    NSDictionary *options = @{
                              (NSString *)kCVPixelBufferCGImageCompatibilityKey : @YES,
                              (NSString *)kCVPixelBufferCGBitmapContextCompatibilityKey : @YES,
                              (NSString *)kCVPixelBufferIOSurfacePropertiesKey: [NSDictionary dictionary]
                              };
    CVPixelBufferRef pxbuffer = NULL;
    
    CGFloat frameWidth = CGImageGetWidth(image);
    CGFloat frameHeight = CGImageGetHeight(image);
    
    CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault,
                                          frameWidth,
                                          frameHeight,
                                          kCVPixelFormatType_32ARGB,
                                          (__bridge CFDictionaryRef) options,
                                          &pxbuffer);
    
    NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);
    
    CVPixelBufferLockBaseAddress(pxbuffer, 0);
    void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
    NSParameterAssert(pxdata != NULL);
    
    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    
    CGContextRef context = CGBitmapContextCreate(pxdata,
                                                 frameWidth,
                                                 frameHeight,
                                                 8,
                                                 CVPixelBufferGetBytesPerRow(pxbuffer),
                                                 rgbColorSpace,
                                                 (CGBitmapInfo)kCGImageAlphaNoneSkipFirst);
    NSParameterAssert(context);
    CGContextConcatCTM(context, CGAffineTransformIdentity);
    CGContextDrawImage(context, CGRectMake(0,
                                           0,
                                           frameWidth,
                                           frameHeight),
                       image);
    CGColorSpaceRelease(rgbColorSpace);
    CGContextRelease(context);
    
    CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
    
    return pxbuffer;
}

最后實現(xiàn)predict方法:


- (void)predict:(UIImage *)image {
    //獲取input
    UIImage *scaleImage = [self scaleImage:image size:224];
    CVPixelBufferRef buffer = [self pixelBufferFromCGImage:scaleImage.CGImage];
    
    //讀取沙盒中的mlmodelc文件
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *docModelcPath = [docPath stringByAppendingPathComponent:@"MobileNet.mlmodelc"];
    NSURL *url = [NSURL fileURLWithPath:docModelcPath];
    NSError *error = nil;
    MobileNet *model = [[MobileNet alloc] initWithContentsOfURL:url error:&error];
    if (error) {
        NSLog(@"%@", error);
        return;
    }
    
    //predict
    MobileNetOutput *output = [model predictionFromImage:buffer error:&error];
    if (error) {
        NSLog(@"%@", error);
        return;
    }
    
    //顯示
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:output.classLabelProbs.count + 1];
    [result addObject:@[@"這張圖片可能包含:", output.classLabel]];
    [output.classLabelProbs enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSNumber * _Nonnull obj, BOOL * _Nonnull stop) {
        NSString *title = [NSString stringWithFormat:@"%@的概率:", key];
        [result addObject:@[title, obj.stringValue]];
    }];
    self.array = result;
}

至此,可以運行項目,并嘗試拍照識別物體了!

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容