Microsoft.ML.ImageAnalytics 2.0中SchemaDefinition.Create抛异常求助
解决Microsoft.ML.ImageAnalytics 2.0中SchemaDefinition创建异常问题
问题背景
在Microsoft.ML.ImageAnalytics 2.0版本中,执行代码SchemaDefinition def = SchemaDefinition.Create(typeof(ImageData), SchemaDefinition.Direction.Read);时抛出System.ArgumentOutOfRangeException: 'Could not determine an IDataView type and registered custom types for member Image (Parameter 'rawType')'异常,该代码在1.71版本可正常运行。涉及的ImageData类定义如下:
public class ImageData { [ColumnName("image")] [ImageType(height:100, width:100)] public Bitmap Image { get; set; } }
解决方案
方案1:通过MLContext获取SchemaDefinition
2.0版本中,直接调用SchemaDefinition.Create不会自动加载ImageAnalytics组件的类型映射逻辑,改用MLContext.Data.GetSchemaDefinition方法可自动处理类型关联:
var mlContext = new MLContext(); SchemaDefinition def = mlContext.Data.GetSchemaDefinition(typeof(ImageData), SchemaDefinition.Direction.Read);
方案2:手动注册ImageDataViewType
如果无法依赖MLContext,可手动为Image属性指定对应的ImageDataViewType:
// 获取ImageType属性配置 var imageProp = typeof(ImageData).GetProperty(nameof(ImageData.Image)); var imageTypeAttr = imageProp.GetCustomAttribute<ImageTypeAttribute>(); // 创建匹配的ImageDataViewType var imageColumnType = ImageDataViewType.Create(imageTypeAttr.Height, imageTypeAttr.Width, ImageDataViewType.ColorBits.Rgb); // 创建SchemaDefinition并手动设置列类型 SchemaDefinition def = SchemaDefinition.Create(typeof(ImageData), SchemaDefinition.Direction.Read); def[nameof(ImageData.Image)].ColumnType = imageColumnType;
原因说明
1.71及更早版本中,SchemaDefinition.Create会自动识别ImageType属性并关联对应的ImageDataViewType;但2.0版本重构了类型映射逻辑,移除了这一自动关联,需要通过MLContext触发组件初始化,或手动指定列类型来解决。
内容的提问来源于stack exchange,提问作者Trifon
相关产品推荐
相关产品推荐

