gpt4 book ai didi

objective-c - 让 coreml 在 objective-C 中运行

转载 作者:行者123 更新时间:2023-12-04 16:08:24 39 4
gpt4 key购买 nike

我在创建一个在 Objective-C 中使用 Apple 的 CoreML 的非常简单的示例时遇到了问题。我已经使用 python 创建了一个模型文件,它现在工作起来相当简单:

coreml_model_svm = coremltools.models.MLModel("svm.mlmodel")
test_x = [1.0 for x in range(160)]
predictions_coreml_svm = coreml_model_svm.predict({"input":test_x})

我想在 Objective-C 中重现以上三行。我知道我的数据必须是 MLMultiArray 并且模型需要加载到 MLModel 中。我一直在尝试查找有关语法的一些信息,但似乎我不明白文档是如何工作的,而且所有示例都在 Swift 中。到目前为止,这是我的代码。注释 MLMultiArray 会导致初始化 MLModel 时出现未捕获的异常。当不评论 MLMultiArray 时,我得到 no known class method for selector 'initWithShape:dataType:error'

#import <Foundation/Foundation.h>
#import <CoreML/CoreML.h>

//clang -framework Foundation coremltest.m -o coremltest
int main (int argc, const char * argv[])
{
NSLog(@"start");

NSArray * shape = [[NSArray alloc] init];
MLMultiArrayDataType dataType = MLMultiArrayDataTypeDouble;
NSError * error = nil;

MLMultiArray * input = [MLMultiArray initWithShape:(NSArray*) shape
dataType:(MLMultiArrayDataType ) dataType
error:(NSError **) error];

MLModel * mymodel = [[MLModel init] initWithContentsOfFile:@"svm.mlmodel"];

return 0;
}

我将不胜感激。

最佳答案

首先你需要导入你的模型类,在你的例子中是 svm(最好是 Svm 以大写字母开头):

#import "svm.h" 

此类定义包含输入和输出以及方法定义所需的所有信息。当您选择左侧的 mlmodel 文件时,您可以通过单击类名称旁边的小箭头在自动生成的类描述中找到此规范。在这个类的描述中

enter image description here

在您的例子中,输入是一个包含 160 个 Double 元素作为向量的 MLMultiArray。所以首先用 shape 数组定义维度

NSArray *shape = @[@1, @160];

然后定义 MLMultiArray,它将成为预测过程的 svmModelInput(再次由 XCode 自动定义):

    MLMultiArrayDataType dataType = MLMultiArrayDataTypeDouble;
NSError *error = nil;

MLMultiArray *theMultiArray = [[MLMultiArray alloc] initWithShape:(NSArray*)shape
dataType:(MLMultiArrayDataType)dataType
error:&error] ;

for (int i = 0; i < 160; i++) {
[theMultiArray setObject:[NSNumber numberWithDouble:1.0] atIndexedSubscript:(NSInteger)i];
}

用过的

initWithShape

是 Apple 的一种 MLMultiArray 方法。我用“1”填充数组只是为了测试,但你当然必须稍后用你的真实输入替换它。

无需获取模型,只需实例化 svm 然后运行 ​​

predictionFromInput:

再次由XCode构建的类中的方法:

        svm *mySvm = [[svm alloc] init];

svmOutput * svmModelOutput = [(svm *)mySvm predictionFromInput:theMultiArray error:&error];
NSLog(@"SVM Model output = %lld -- %@", svmModelOutput.classLabel, svmModelOutput.classProbability );

if (!error)
{
NSLog(@"svm finished without error");
}
else
{
NSLog(@"Error: %@", error.localizedDescription);
}

当您打印出 svmModelOutput(由 XCode 为您创建)时,您可以检查预测的 classLabel 作为整数和所有标签的概率,如下所示:

2017-12-04 07:32:45.765015+0100 CoreML_test[2634:877638] SVM Model output = 2 -- {
11 = "0.002656571278812773";
3 = "0.2121030282896462";
10 = "0.004570897664662783";
2 = "0.5825387375626612";
9 = "0.02911120023388797";
4 = "0.1690195649703292";
}

关于objective-c - 让 coreml 在 objective-C 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47534758/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com