六、模型瘦身及其影响

机器学习模型文件,一般来说都是比较大的文件,即使是能够用在移动端的小型模型,动辄也要几十上百兆。模型瘦身能够将文件大小成倍缩减,我们首先看一下如何进行模型瘦身,然后来研究一下瘦身后的影响:

一、如何瘦身

有英文阅读能力的同学,可以看这篇官方文档,然后可以跳过这个章节。

首先你需要安装coremltools:

pip3 install -U coremltools

然后新建一个Python3文件,输入一下内容:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2019-01-17 10:41 - Larkin <yangchenlarkin@gmail.com>

import coremltools
import sys


def main():
    if len(sys.argv) == 1:
        print('请输入模型文件路径')

    # Load a model, lower its precision, and then save the smaller model.
    model_spec = coremltools.utils.load_spec(sys.argv[1])
    model_fp16_spec = coremltools.utils.convert_neural_network_spec_weights_to_fp16(model_spec)
    coremltools.utils.save_spec(model_fp16_spec, 'ModelFP16.mlmodel')


if __name__ == '__main__':
    main()

最后运行脚本:

python3 main.py <mlmodel file path>

这里我们的<mlmodel file path>我们使用MobileNet.mlmodel文件,然后你再同名文件夹下可以得到一个名为ModelFP16.mlmodel的文件,我们将文件名修改为MobileNet16.mlmodel。

二、准备一个iOS工程

我们新建一个Single View App,名叫CoreML-FP16,到网上随便找一张图片,和MobileNet.mlmodel以及MobileNet16.mlmodel一起拖到项目中去,我使用的是这张图片:

找到main.m文件,加入如下代码:

#import "MobileNet.h"
#import "MobileNet16.h"
#import <mach/mach_time.h>

UIImage *scaleImage(UIImage *image, 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);
    
    assert(status == kCVReturnSuccess && pxbuffer != NULL);
    
    CVPixelBufferLockBaseAddress(pxbuffer, 0);
    void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
    assert(pxdata != NULL);
    
    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    
    CGContextRef context = CGBitmapContextCreate(pxdata,
                                                 frameWidth,
                                                 frameHeight,
                                                 8,
                                                 CVPixelBufferGetBytesPerRow(pxbuffer),
                                                 rgbColorSpace,
                                                 (CGBitmapInfo)kCGImageAlphaNoneSkipFirst);
    assert(context);
    CGContextConcatCTM(context, CGAffineTransformIdentity);
    CGContextDrawImage(context, CGRectMake(0,
                                           0,
                                           frameWidth,
                                           frameHeight),
                       image);
    CGColorSpaceRelease(rgbColorSpace);
    CGContextRelease(context);
    
    CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
    
    return pxbuffer;
}

double MachTimeToMillisecond(uint64_t time) {
    mach_timebase_info_data_t timebase;
    mach_timebase_info(&timebase);
    return (double)time * (double)timebase.numer / (double)timebase.denom /1e6;
}

double measureBlock(void (^block)(void)) {
    if (!block) {
        return 0;
    }
    uint64_t begin = mach_absolute_time();
    block();
    uint64_t end = mach_absolute_time();
    return MachTimeToMillisecond(end - begin);
}

void logBlockTime(NSString *description, void (^block)(void)) {
    double time = measureBlock(block);
    NSLog(@"<%@>: time:%fms", description, time);
}

将main函数修改为:

int main(int argc, char * argv[]) {
    UIImage *image = [UIImage imageNamed:@"cat.jpeg"];
    UIImage *image224 = scaleImage(image, 224);
    CVPixelBufferRef input = pixelBufferFromCGImage(image224.CGImage);
    //TODO: do testing
}

三、文件大小:

我们分别打开MobileNet.mlmodel和MobileNet16.mlmodel,在描述中可以看到两个文件的大小,分别是17.1M和8.6M,确实是少了一倍。

四、性能测试:

我们添加如下函数:


void run_test(CVPixelBufferRef input) {
    MLModelConfiguration *config = [[MLModelConfiguration alloc] init];
    
    config.computeUnits = MLComputeUnitsCPUOnly;
    MobileNet *cpuModel = [[MobileNet alloc] initWithConfiguration:config error:nil];
    MobileNet16 *cpuModel16 = [[MobileNet16 alloc] initWithConfiguration:config error:nil];
    
    config.computeUnits = MLComputeUnitsCPUAndGPU;
    MobileNet *gpuModel = [[MobileNet alloc] initWithConfiguration:config error:nil];
    MobileNet16 *gpuModel16 = [[MobileNet16 alloc] initWithConfiguration:config error:nil];
    
    config.computeUnits = MLComputeUnitsAll;
    MobileNet *allModel = [[MobileNet alloc] initWithConfiguration:config error:nil];
    MobileNet16 *allModel16 = [[MobileNet16 alloc] initWithConfiguration:config error:nil];
    
    logBlockTime(@"cpu", ^{
        for (int i = 0; i < 100; i++) {
            [cpuModel predictionFromImage:input error:nil];
        }
    });
    logBlockTime(@"gpu", ^{
        for (int i = 0; i < 100; i++) {
            [gpuModel predictionFromImage:input error:nil];
        }
    });
    logBlockTime(@"all", ^{
        for (int i = 0; i < 100; i++) {
            [allModel predictionFromImage:input error:nil];
        }
    });
    
    logBlockTime(@"cpu16", ^{
        for (int i = 0; i < 100; i++) {
            [cpuModel16 predictionFromImage:input error:nil];
        }
    });
    logBlockTime(@"gpu16", ^{
        for (int i = 0; i < 100; i++) {
            [gpuModel16 predictionFromImage:input error:nil];
        }
    });
    logBlockTime(@"all16", ^{
        for (int i = 0; i < 100; i++) {
            [allModel16 predictionFromImage:input error:nil];
        }
    });
}

在main函数中调用他:


int main(int argc, char * argv[]) {
    //...
    //TODO: do testing
    run_test(input);
}

我们得到以下结果:


这个结果嘛,咳咳。。。好吧。。。
我们把CPUOnly去掉再看看:


只能说,如果你项目中使用的是CPUAndGPU,那这个压缩对运行效率还是有比较好的影响的,但是如果你只能用CPU,这条路还是不走为好。

五、准确率测试:

我们参考二、使用Core ML加载.mlmodel模型文件中的iOS项目,在ObjectRecognition/ORViewController.m中添加如下代码:

#pragma mark - predict
- (UIImage *)scaleImage:(UIImage *)image size:(CGFloat)size {
    //参考:二、使用Core ML加载.mlmodel模型文件
}

- (CVPixelBufferRef)pixelBufferFromCGImage:(CGImageRef)image {
    //参考:二、使用Core ML加载.mlmodel模型文件
}

- (void)predict:(UIImage *)image {
    UIImage *scaledImage = [self scaleImage:image size:224];
    CVPixelBufferRef buffer = [self pixelBufferFromCGImage:scaledImage.CGImage];
    
    NSError *error = nil;
    
    MLModelConfiguration *config = [[MLModelConfiguration alloc] init];
    config.computeUnits = MLComputeUnitsCPUAndGPU;
    MobileNet16 *model16 = [[MobileNet16 alloc] initWithConfiguration:config error:&error];
    if (error) {
        NSLog(@"%@", error);
        return;
    }
    
    MobileNet16Output *output16 = [model16 predictionFromImage:buffer error:&error];
    if (error) {
        NSLog(@"%@", error);
        return;
    }
    
    MobileNet *model = [[MobileNet alloc] initWithConfiguration:config error:&error];
    if (error) {
        NSLog(@"%@", error);
        return;
    }
    
    MobileNetOutput *output = [model predictionFromImage:buffer error:&error];
    if (error) {
        NSLog(@"%@", error);
        return;
    }
    
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:2];
    [result addObject:@[@"MobileNet", output.classLabel]];
    [result addObject:@[@"MobileNet16", output16.classLabel]];
    self.array = result;
}

随便拍一拍,得到以下八张测试结果:


我们可以发现,模型经过压缩后,正确率并没有很明显的损失。当然8张图片可能并不能很好的说明问题。手头有大量数据集的同学,可以做一个进一步的测试。

上图中有明显的检测错误的现象,但这并非我们关心的。我们在评价压缩模型算法的时候,我们通常关心压缩后的正确率/召回率/查准率损失了多少,而不是非常关心压缩前正确率/召回率/查准率原本是多少。

六、总结

  • 苹果官方提供的这个模型压缩算法,可以将模型文件大小降低一半。
    这无论对于Coding阶段就将模型集成到代码中的方案,还是对于从服务端下载模型的方案来说,都是非常有利的。
  • 但是对于无法受用CPU的机型、操作系统来说,预测阶段耗时的激增,无疑使得这个方案成了鸡肋。
  • 这个方案对正确率的影响,目前来看可以忽略不计。当然和需要大量的测试结果才能更加笃定的做出这个结论。

总之,你能用CPUAndGPU,就可以放心的压缩,如果只能用CPU,那还是别用这种方式了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,539评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,594评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,871评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,963评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,984评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,763评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,468评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,850评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,002评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,144评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,823评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,483评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,026评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,150评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,415评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,092评论 2 355

推荐阅读更多精彩内容