我将我的mlmodel从tf.keras转换过来。目标是从图像中识别手写文本。当我使用以下代码运行时:
func performCoreMLImageRecognition(_ image: UIImage) { let model = try! HTRModel() // 处理输入图像 let scale = image.scaledImage(200) let sized = scale?.resize(size: CGSize(width: 200, height: 50)) let gray = sized?.rgb2GrayScale() guard let pixelBuffer = sized?.pixelBufferGray(width: 200, height: 50) else { fatalError("无法将图像转换为pixelBufferGray")} UIImageWriteToSavedPhotosAlbum(gray! , self, #selector(self.didFinishSavingImage(_:didFinishSavingWithError:contextInfo:)), nil) let mlArray = try! MLMultiArray(shape: [1, 1], dataType: MLMultiArrayDataType.float32) let htrinput = HTRInput(image: pixelBuffer, label: mlArray) if let prediction = try? model.prediction(input: htrinput) { print(prediction) } }
我得到了以下错误:
[espresso] [Espresso::handle_ex_plan] exception=Espresso exception: "Invalid argument": generic_reshape_kernel: 无效的底部形状 (64 12 1 1 1) 无法重塑为 (768 50 -1 1 1) status=-62021-01-21 20:23:50.712585+0900 Guided Camera[7575:1794819] [coreml] 计算NN输出时出错 -62021-01-21 20:23:50.712611+0900 Guided Camera[7575:1794819] [coreml] 在 -executePlan:error: 中失败。
这是模型配置模型运行得很好。我在这方面出了什么问题?我对Swift不太熟练,需要帮助。这个错误是什么意思?我该如何解决这个问题?
回答:
有时候在从Keras(或其他)转换到Core ML的过程中,转换器无法理解如何处理某些操作,导致模型无法正常工作。
在你的案例中,有一个层输出一个形状为(64, 12, 1, 1, 1)的张量,而有一个重塑层期望能重塑为(768, 50, -1, 1, 1)。
你需要找出哪个层进行这种重塑,然后检查Core ML模型为什么会接收到大小不正确的输入张量。仅仅因为它在Keras中运行良好,并不意味着转换到Core ML是完美的。
你可以使用Netron,一个开源模型查看器,来检查Core ML模型。
(请注意,64×12 = 768,所以问题似乎出在那个张量的50上。)