1.使用官方最新发布的CoreML
2.测试object-c swift
3.引用apple案例里使用的机器学习模型,下载地址:https://pan.baidu.com/s/1jHYJW6i 下载后更名为MarsHabitatPricer.mlmodel
4.首先使用Xcode 9 创建新项目,
4.1 导入MarsHabitatPricer.mlmodel包,官网说Xcode 9 会自动根据使用语言生成对应类,但导入后如图1 :
Model Class 会报:
Model is not part of any target. Add the model to a target to enable generation of the model class.
解决办法:把此模型添加到项目中,
如图 2:
此时再点击导入的模型,会看到生成的Model Class,如图 3
此时在项目中已经可以使用此模型的类及函数了
4.2 代码
#import "ViewController.h"
#import <CoreML/CoreML.h>
#import "MarsHabitatPricer.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupCoreML];
}
/** model input */
- (void)setupCoreML
{
MarsHabitatPricer *marsPrice = [[MarsHabitatPricer alloc] init];
double panels = 1.5;
double green = 3.0;
double size = 1500;
MarsHabitatPricerOutput *output = [marsPrice predictionFromSolarPanels:panels greenhouses:green size:size error:nil];
double price = output.price;
NSLog(@"price = %f", price);
}
@end
4.3 swift
let model = MarsHabitatPricer()
let solar = 1.5
let green = 3.0
let acres = 1500.0
let output = try? model.prediction(solarPanels: solar, greenhouses: Double(green), size: acres)
let price = output?.price;
print(price ?? 0)