在 xcode 中部署 Keras 模型到 ml 模型转换

问题描述

我有一个在 Keras python 中制作的模型,并转换为 Xcode 的 mlmodel。我在这里使用了以下 xcode 代码...我在这里一个 github 版本... https://github.com/jbkey730/SeeFood-iOS13-Completed.git 这是什么错误...

2021-01-09 19:22:32.231074-0600 SeeFood-CoreML[818:53598] [Camera] Failed to read exposureBiasesByMode dictionary: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: data is NULL" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: data is NULL}
2021-01-09 19:22:35.192738-0600 SeeFood-CoreML[818:53598] Metal API Validation Enabled
0.016954016

这里是 mlmodel 的 xcode...

//
//  ViewController.swift
//  SeeFood-CoreML
//
//

import UIKit
import CoreML
import Vision
import Social

class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    @IBOutlet weak var imageView: UIImageView!
    var classificationResults : [VNClassificationObservation] = []
    let imagePicker = UIImagePickerController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        imagePicker.delegate = self
        
    }
    
    func detect(image: CIImage) {
        
        // Load the ML model through its generated class
        guard let model = try? VNCoreMLModel(for: club(configuration: MLModelConfiguration()).model) else {
            fatalError("can't load ML model")
        }
        
        let request = VNCoreMLRequest(model: model) { [weak self] request,error in guard let results = request.results as? [VNClassificationObservation],let topResult = results.first?.confidence
       
            //VNImageCropAndScaleOption
                                                                                          
        else{
                    print("No results")
                    return
        }
        print(topResult)
        let predInt = Double(topResult)
        var thresh: Double
        thresh = 0.5
        if predInt < thresh {
            dispatchQueue.main.async {
                //self?.navigationItem.title = "Lax Wheat"
                self?.navigationItem.title = String(predInt)
                self?.navigationController?.navigationBar.barTintColor = UIColor.orange
                self?.navigationController?.navigationBar.isTranslucent = false
                                        }
        }
            else{
                dispatchQueue.main.async {
                    self?.navigationItem.title = String(predInt) //"Club Wheat"
                    self?.navigationController?.navigationBar.barTintColor = UIColor.orange
                    self?.navigationController?.navigationBar.isTranslucent = false
                    }
            }
       
        }
        
        let handler = VNImageRequestHandler(ciImage: image)
        
        do {
            try handler.perform([request])
        }
        catch {
            print(error)
        }
    }
        
    
    
    
        
        
      
    func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediawithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        if let image = info[.originalImage] as? UIImage {
            
            imageView.image = image
            imagePicker.dismiss(animated: true,completion: nil)
            guard let ciImage = CIImage(image: image) else {
                fatalError("Couldn't convert uiimage to CIImage")
            }
            detect(image: ciImage)
        }
    }
    
    
    @IBAction func cameraTapped(_ sender: Any) {
        
        imagePicker.sourceType = .camera
        imagePicker.allowsEditing = false
        present(imagePicker,animated: true,completion: nil)
    }
    
}


// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
    return input.rawValue
}

我在python中使用coreml将keras模型转换为mlmodel。我在这里使用了来自 tensorflow python API 的自定义代码,您可以在其中重现示例模型。

https://github.com/keras-team/keras-io/blob/master/examples/vision/image_classification_from_scratch.py

import coremltools as ct
model = tf.keras.models.load_model('/media/jacoblamkey/Storage/club and lax wheat/save_at_2.h5')



#convert to Core ML and check predictions
class_labels = ['Wheat']
#your_model = coremltools.converters.keras.convert('/media/jacoblamkey/Storage/club and lax wheat/save_at_500.h5',#                                                  input_names=['image'],#                                                  output_names=['output'],#                                                 class_labels=output_labels,#                                                  image_input_names='image')
classifier_config = ct.ClassifierConfig(class_labels)
your_model = ct.convert(model,inputs=[ct.ImageType()],classifier_config=classifier_config)
#your_model = coremltools.converters.keras.convert(model,input_names=['image'],output_names=['output'],#                                                   class_labels=output_labels,image_input_names='image')


your_model.short_description = 'Clasify Club and Lax wheat'
your_model.version = "1.0"
#your_model.input_description['image'] = 'Takes an image and gives a class'
#your_model.output_description['output'] = 'Prediction of digit'
your_model.save('club.mlmodel')
print(your_model)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)