ML.NET-API(一)_常用代码片段
1、训练图像
//Append ImageClassification trainer to your pipeline containing any preprocessing transforms
pipeline
.Append(mlContext.MulticlassClassification.Trainers.ImageClassification(featureColumnName: "Image")
.Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel");
// 训练模型
var model = pipeline.Fit(trainingData);
// 预测
var predictedData = model.Transform(newData).GetColumn<string>("PredictedLabel");
2、训练文本
// Define training pipeline using TextClassification trainer
var pipeline =
mlContext.Transforms.Conversion.MapValueToKey("Label","Sentiment")
.Append(mlContext.MulticlassClassification.Trainers.TextClassification(sentence1ColumnName: "Text"))
.Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
// 训练模型
var model = pipeline.Fit(trainingData);
// 预测
var predictedData = model.Transform(newData).GetColumn<string>("PredictedLabel");
3、句子相似性
// Define your pipeline
var pipeline = mlContext.Regression.Trainers.SentenceSimilarity(sentence1ColumnName: "Sentence", sentence2ColumnName: "Sentence2");
// 训练模型
var model = pipeline.Fit(trainingData);
// 预测
var score = model.Transform(newData).GetColumn<float>("Score");
4、使用预先训练的TensorFlow模型
// Load TensorFlow model
TensorFlowModel tensorFlowModel = mlContext.Model.LoadTensorFlowModel(_modelPath);
//Append ScoreTensorFlowModel transform to your pipeline containing any preprocessing transforms
pipeline.Append(tensorFlowModel.ScoreTensorFlowModel(outputColumnName: "Prediction/Softmax", inputColumnName:"Features"))
// 训练
ITransformer model = pipeline.Fit(dataView);
// 预测方式一
var predictions = pipeline.Fit(data).GetColumn<float[]>(TinyYoloModelSettings.ModelOutput);
// 预测方式二:
var predictions = model.Transform(dataView).GetColumn<float>("Prediction/Softmax");
5、使用预先训练的ONNX模型
// Append ApplyOnnxModel transform to pipeline containing any preprocessing transforms
pipeline.Append((modelFile: modelLocation, outputColumnNames: new[] { TinyYoloModelSettings.ModelOutput }, inputColumnNames: new[] { TinyYoloModelSettings.ModelInput })
// 训练
var model = pipeline.Fit(data);
// 预测方式一
var predictions = pipeline.Fit(data).GetColumn<float[]>(TinyYoloModelSettings.ModelOutput);
// 预测方式二:
IDataView scoredData = model.Transform(imageDataView);
6、使用‘模型生成器工具’的代码进行预测
MLModel1.Predict(sampleData); // 预测
MLModel1.PredictAllLabels(sampleData); // 预测标签
本文来自博客园,作者:꧁执笔小白꧂,转载请注明原文链接:https://www.cnblogs.com/qq2806933146xiaobai/p/18297590