ML.NET鸢尾花教程报错:Label列无效值导致训练实例被跳过
Fixing the TargetInvocationException in ML.NET Iris Tutorial
Hey there, let's get this sorted out—your error makes total sense once we look at the details!
What's Causing the Problem?
The System.Reflection.TargetInvocationException and the "invalid values in Label column" warnings are happening because of a mismatch between your dataset and the IrisData class definition:
- The classic Iris dataset's Label column contains string values (like "Iris-setosa", "Iris-versicolor") representing flower species.
- But you've defined the
Labelfield inIrisDataas afloat—ML.NET can't convert those text labels into floating-point numbers, so it marks every single row as invalid and skips them during training.
The Fixes
Let's adjust your code step by step:
- Update the IrisData Class
Change theLabelfield type fromfloattostringto match the actual data:
namespace Ronald.A.Fisher { public class IrisData { [Column("0")] public float SepalLength; [Column("1")] public float SepalWidth; [Column("2")] public float PetalLength; [Column("3")] public float PetalWidth; [Column("4")] [ColumnName("Label")] public string Label; // Now matches the text labels in the dataset } }
- Adjust Your Training Pipeline
ML.NET's classification algorithms require numeric inputs for labels, so we need to map those string labels to numeric keys before training, then map the predicted keys back to strings for readability. Add these steps to your pipeline:
var pipeline = new LearningPipeline(); // 1. Load your data (keep your existing data loading step) pipeline.Add(new TextLoader<IrisData>(dataPath, separator: ",")); // 2. Map string labels to numeric keys (required for classification models) pipeline.Add(new MapValueToKey("Label", "Label")); // 3. Keep your existing feature engineering and training algorithm steps pipeline.Add(new ColumnConcatenator("Features", "SepalLength", "SepalWidth", "PetalLength", "PetalWidth")); pipeline.Add(new StochasticDualCoordinateAscentClassifier()); // 4. Map predicted numeric keys back to original string labels (for easy interpretation) pipeline.Add(new MapKeyToValue("PredictedLabel", "PredictedLabel")); // Now train the model without errors var model = pipeline.Train<IrisData, IrisPrediction>();
Why This Works
MapValueToKeyconverts each unique string label into a unique integer (e.g., "Iris-setosa" → 0, "Iris-versicolor" → 1), which ML.NET's classification models can process.MapKeyToValuereverses that conversion after prediction, so yourIrisPredictionclass'sPredictedLabelwill show the actual flower species name instead of a confusing number.
Just double-check that your CSV file's 5th column (index 4) is indeed the text-based species labels, and you should be good to go!
内容的提问来源于stack exchange,提问作者Kyle B
相关产品推荐
相关产品推荐

