机器学习Tensorflow笔记4:iOS通过Core ML使用Tensorflow训练模型

Tensorflow是Google推出的人工智能框架,而Core ML是苹果推出的人工智能框架,两者是有很大的区别,其中Tensorflow是包含了训练模型和评估模型,Core ML只支持在设备上评估模型,不能训练模型。
通常而言我们通过Tensorflow训练模型,导出我们训练的模型pb,然后转换了Core ML的格式mlmodel,从而实现在iOS实现评估模型。

系列文章

《机器学习Tensorflow笔记1:Hello World到MNIST实验》
《机器学习Tensorflow笔记2:超详细剖析MNIST实验》
《机器学习Tensorflow笔记3:Python训练MNIST模型,在Android上实现评估》
《机器学习Tensorflow笔记4:iOS通过Core ML使用Tensorflow训练模型》

导出MNIST训练模型

我们在上一篇文章介绍了如何导出.pb格式的解决,但是这种格式只适合在Tensorflow框架上使用,如果要在iOS上使用,那么就要转换到CoreML能够使用的.mlmodel格式。如何导出.pb格式的教程请看我的另一篇文章
《机器学习Tensorflow笔记3:Python训练MNIST模型,在Android上实现评估》

安装tfcoreml

安装tfcoreml很简单,github 上也有详细的介绍。我的Tensorflow是通过Virtualenv安装的,如果安装tfcoreml,那么需要先激活环境,通过pip安装即可。

$ cd targetDirectory 
$ source ./bin/activate
(targetDirectory) $ pip install -U tfcoreml
把pb转换成mlmodel
import tfcoreml as tf_converter

tf_converter.convert(tf_model_path='model/mnist2.pb',
                     mlmodel_path='my_model.mlmodel',
                     output_feature_names=['Softmax:0'],input_name_shape_dict={"input/x_input:0":[1,784]})
项目添加mlmodel模型文件

把.mlmodel文件添加到项目中


image.png

需要保证文件已经添加到Compile Sources


image.png
分析原理

我们可以点击.mlmodel文件的箭头,就可以看到一个代码文件,实际上mlmodel是保护了三个类,Mnist,MnistInput,MnistOutput,通过这几个类就可以实现模型的评估。

image.png

评估模型
do{
    let image = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,18,18,18,126,136,175,26,166,255,247,127,0,0,0,0,0,0,0,0,0,0,0,0,30,36,94,154,170,253,253,253,253,253,225,172,253,242,195,64,0,0,0,0,0,0,0,0,0,0,0,49,238,253,253,253,253,253,253,253,253,251,93,82,82,56,39,0,0,0,0,0,0,0,0,0,0,0,0,18,219,253,253,253,253,253,198,182,247,241,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,80,156,107,253,253,205,11,0,43,154,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,14,1,154,253,90,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,139,253,190,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,190,253,70,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,35,241,225,160,108,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,81,240,253,253,119,25,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,45,186,253,253,150,27,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,93,252,253,187,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,249,253,249,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,46,130,183,253,253,207,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,39,148,229,253,253,253,250,182,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,114,221,253,253,253,253,201,78,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23,66,213,253,253,253,253,198,81,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,18,171,219,253,253,253,253,195,80,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,55,172,226,253,253,253,253,244,133,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,136,253,253,253,212,135,132,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    // print shape
    for i in 0...783{
        if(i % 28 == 0){
            print("")
        }
        print("\(String(format: "% 2x", image[i]))",terminator: "")
    }
    print("")
    
    let array = try MLMultiArray(shape: [784], dataType: MLMultiArrayDataType.float32)
    for i in 0...(image.count-1) {
        let value = Double(image[i]) / 255.0
        array[i]  = NSNumber(floatLiteral: value)
    }
    let mnistInput = MnistInput(input__x_input__0: array)
    let result = try mnist.prediction(input: mnistInput)
    for i in 0...(result.Softmax__0.count - 1){
        let item = result.Softmax__0[i]
        print("\(i) possibility : \(String(format:"%.2f",item.floatValue))")
    }
}catch{
    print(error)
}

结果:

最可能是值是 5

0 possibility : 0.00
1 possibility : 0.00
2 possibility : 0.00
3 possibility : 0.14
4 possibility : 0.00
5 possibility : 0.86
6 possibility : 0.00
7 possibility : 0.00
8 possibility : 0.00
9 possibility : 0.00
评估模型(改进)

上面是直接使用数组进行评估模型,下面我们直接读取图片文件来实现评估模型。

let imagePath = Bundle.main.path(forResource: "test_image", ofType: "png")
let imageData:UIImage = UIImage(contentsOfFile: imagePath!)!
imageView.image = imageData
let width = imageData.cgImage?.width
let height = imageData.cgImage?.height

let data:UnsafePointer<UInt8> = CFDataGetBytePtr(imageData.cgImage?.dataProvider?.data!)
var image = Array<Int>()
for i in 0...(width! * height! - 1){
    let postion = i*4
    image.append(Int(data[postion]))
}

let mnist = Mnist()
do{
    // print shape
    for i in 0...783{
        if(i % 28 == 0){
            print("")
        }
        print("\(String(format: "% 2x", image[i]))",terminator: "")
    }
    print("")
    
    let array = try MLMultiArray(shape: [784], dataType: MLMultiArrayDataType.float32)
    for i in 0...(image.count-1) {
        let value = Double(image[i]) / 255.0
        array[i]  = NSNumber(floatLiteral: value)
    }
    let mnistInput = MnistInput(input__x_input__0: array)
    let result = try mnist.prediction(input: mnistInput)
    var text = ""
    for i in 0...(result.Softmax__0.count - 1){
        let item = result.Softmax__0[i]
        text += "\(i) possibility : \(String(format:"%.2f",item.floatValue))\n"
    }
    label.text = text
}catch{
    print(error)
}

添加图片
test_image.png
image.png

image.png
测试结果
image.png
Demo源码

https://github.com/taoweiji/TensorflowIOSDemo

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