如何解决CoreML输出标签NSCFString-标签显示不正确
我正在使用需要使用CoreML模型执行图像分类的iOS应用程序。
我使用Google Cloud Platform AutoML Vision来训练模型。 Google提供了该模型的CoreML版本,我下载了该模型以在我的应用中使用。
我遵循了Google的教程,一切似乎都进行得很顺利。但是,当它花时间开始使用模型时,得到了非常奇怪的预测。我得到了预测的信心,然后得到了一个非常奇怪的字符串,我不知道它是什么。
<VNClassificationObservation: 0x600002091d40> A7DBD70C-541C-4112-84A4-C6B4ED2EB7E2 requestRevision=1 confidence=0.332127 "CICAgICAwPmveRIJQWdsYWlzX2lv"
我所指的字符串是CICAgICAwPmveRIJQWdsYWlzX2lv
。
经过研究和调试,我发现这是一个NSCFString。
https://developer.apple.com/documentation/foundation/1395135-nsclassfromstring
显然,这是基础API的一部分。有人对此有任何经验吗?
CoreML文件还附带带有正确标签的dict.txt文件。我是否必须将此字符串转换为标签?我该怎么做。
这是我到目前为止的代码。
//
// Classification.swift
// Lepidoptera
//
// Created by Tomás Mamede on 15/09/2020.
// Copyright © 2020 Tomás Santiago. All rights reserved.
//
import Foundation
import SwiftUI
import Vision
import CoreML
import ImageIO
class Classification {
private lazy var classificationRequest: VNCoreMLRequest = {
do {
let model = try VNCoreMLModel(for: AutoML().model)
let request = VNCoreMLRequest(model: model,completionHandler: { [weak self] request,error in
if let classifications = request.results as? [VNClassificationObservation] {
print(classifications.first ?? "No classification!")
}
})
request.imageCropAndScaleOption = .scaleFit
return request
}
catch {
fatalError("Error! Can't use Model.")
}
}()
func classifyImage(receivedImage: UIImage) {
let orientation = CGImagePropertyOrientation(rawValue: UInt32(receivedImage.imageOrientation.rawValue))
if let image = CIImage(image: receivedImage) {
DispatchQueue.global(qos: .userInitiated).async {
let handler = VNImageRequestHandler(ciImage: image,orientation: orientation!)
do {
try handler.perform([self.classificationRequest])
}
catch {
fatalError("Error classifying image!")
}
}
}
}
}
解决方法
标签存储在您的mlmodel文件中。如果您在Xcode 12模型查看器中打开mlmodel,它将显示这些标签是什么。
我的猜测是,您的 mlmodel文件包含实际的标签,而不是实际的标签“ CICAgICAwPmveRIJQWdsYWlzX2lv”,等等。
看起来Google的AutoML没有将正确的类标签放入Core ML模型中。
您可以在应用程序中制作一个字典,将“ CICAgICAwPmveRIJQWdsYWlzX2lv”映射到真实标签。
或者您可以通过使用coremltools编辑mlmodel文件中的标签来替换它们。 (我的电子书《核心ML生存指南》有一章介绍了如何替换模型中的标签。)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。