首页 > 解决方案 > 用于 Keras 的 IDataView 为 ImageClassification 转换的 ONNX 模型

问题描述

我有一个带有 Keras 和 Tensorflow 后端的训练模型(Keras 2.2.4 Tensorflow 1.13.1),我想在带有 ML.Net 的 Visual Studio 中使用该模型。

因此,我使用 winmltools.convert_keras 将我的模型转换为 ONNX(我用 Tensorflow 2.0 模型厌倦了它,但我得到了No module named 'tensorflow.tools.graph_transforms' 错误)。现在我终于设法加载模型:

string outName = "dense_6";
string inName = "conv2d_9_input";
string imgFolder = "path\to\Testimage
string pathToMLFile = "path\to\.onnx"

 var pipeline = mlContext.Transforms.LoadImages(outputColumnName: outName, imageFolder: imgFolder, inputColumnName: inName)
                    .Append(mlContext.Transforms.ResizeImages(outName, 299, 299, inName))
                    .Append(mlContext.Transforms.ExtractPixels(outputColumnName: outName, interleavePixelColors: true, offsetImage: 117))
                    .Append(mlContext.Transforms.ApplyOnnxModel(outputColumnName: outName, inputColumnName: inName, modelFile: pathToMLFile, fallbackToCpu: true));

但是现在我需要一个 IDataView 来“拟合”模型(根据我的理解,它需要初始化它?)因此我加载了一个空的 IDataView:

var data = mlContext.Data.LoadFromEnumerable(new List<ImageNetData>());

ImageNetData是_

    public class ImageNetData
    {
        [ColumnName("conv2d_9_input")]
        [ImageType(299, 299)]
        public Bitmap Image { get; set; }

        [ColumnName("dense_6")]
        public string Label;
    }

现在我得到错误:

Schema mismatch for input column 'conv2d_9_input': expected String, got Image<299, 299>
Parametername: inputSchema

我的 Netron 模型:

Netron 模型

为什么它需要一个字符串?如果我删除[ImageType(299,299)]并将位图更改为字符串,我得到:

Schema mismatch for input column 'conv2d_9_input': expected Image, got String

我希望我的问题是可以理解的。

更新:在 Gopal Vashishtha 的提示之后,我更改了输入/输出名称:

var pipeline = mlContext.Transforms.LoadImages(outputColumnName: "image_object", imageFolder: imgFolder, inputColumnName: inName)
                    .Append(mlContext.Transforms.ResizeImages(outputColumnName: "image_object_resized", imageWidth: 299, imageHeight: 299, inputColumnName: "image_object"))
                    .Append(mlContext.Transforms.ExtractPixels(outputColumnName: "input", inputColumnName: "image_object_resized", interleavePixelColors: true, offsetImage: 117, scaleImage: 1 / 255f))
                    .Append(mlContext.Transforms.ApplyOnnxModel(outputColumnName: outName, inputColumnName: "input", modelFile: pathToMLFile + "\\Converted.onnx", fallbackToCpu: true))

但我仍然有同样的错误。我训练模型的方式可能有问题吗?我使用 numpy-array 作为图像,使用 0/1/2 作为相应的类。

标签: c#tensorflowkerasml.netonnx

解决方案


如果查看samples,您可以看到转换链中的输出列需要匹配下一个估计器的输入列。我注意到在您的示例中,您始终使用相同的输入和输出列名称。


推荐阅读