Я хочу знать, как обучать и оценивать модель ответов на вопросы на естественном языке с помощью ML.Net. У меня уже работает обучение, но я застрял на этапе оценки, где вы задаете вопрос и, используя обученную модель, она предсказывает правильный ответ. Я не знаю, правильно ли я делаю, но я знаю, что вы обычно делаете прогнозы по модели естественного языка, используя облачные варианты, такие как экземпляры графического процессора на AWS, Google Cloud Platform или Azure, но мой ноутбук не поддерживает графический процессор, и я не поддерживаю его. Я не хочу использовать облачное решение. Итак, я изо всех сил стараюсь, чтобы это работало с тем, что у меня есть, используя обработку процессора. Вот пример файла Program.cs моего консольного приложения:
using Microsoft.ML;
using Microsoft.ML.Data;
using HtmlAgilityPack;
using Microsoft.Data.Analysis;
///
/// All-in-one Program.cs file that contains the sample implementation of Natural Language Question Answering Training
/// and Evaluation. This contains all the classes it needs to easily build and run in Visual Studio.
///
/// To test this:
///
/// 1. First create a new C# ConsoleApp using .net 8.0 framework or later.
///
/// 2. Add the necessary nuget packages. In a terminal, copy and run these commands:
/// dotnet add package HtmlAgilityPack
/// dotnet add package Microsoft.Data.Analysis
/// dotnet add package Microsoft.ML
///
/// 3. Create your ML training data source by adding a .txt file. Create sample data like this:
///
/// Column to predict Context Question Answer Index
/// Capital < body > Paris is the capital of France. What is the capital of France? 0
/// Author George Orwell wrote the novel 1984. Who wrote the novel "1984"? 0
///
/// 4. Copy this Program.cs code and modify it to declare your ML source data folder variables.
/// For example:
///
/// private const string _mlFolder = @"C:\repo\Blazor.Tools\Blazor.Tools\Data\ML";
/// private const string _languageDataFileName = "languageData.txt";
///
/// 5. In Visual Studio, Press F5 to run to train and evaluate.
///
///
public class Program
{
// Declare your ML source data folder here:
private const string _mlFolder = @"C:\repo\Blazor.Tools\Blazor.Tools\Data\ML";
private const string _languageDataFileName = "languageData.txt";
private static string _dataFilePath = string.Empty;
private static MLContext _mlContext;
public static void Main(string[] args)
{
_dataFilePath = Path.Combine(_mlFolder, _languageDataFileName);
// ML.NET model training pipeline
_mlContext = new MLContext();
// Data preparation and model training flow
PreprocessHtmlData();
TrainQAModel();
ValidateModel();
AnswerUserQuestion();
}
public static void PreprocessHtmlData()
{
Console.WriteLine("HTML preprocessing started...");
// Example HTML preprocessing
string htmlContent = "
This is a sample HTML content.
";
string cleanedText = HtmlHelper.CleanHtml(htmlContent);
Console.WriteLine($"Cleaned HTML text: {cleanedText}");
Console.WriteLine("HTML preprocessing completed.");
}
public static void TrainQAModel()
{
Console.WriteLine("Model training started...");
// Load data from languageData.txt
var dataView = _mlContext.Data.LoadFromTextFile(_dataFilePath, separatorChar: '\t', hasHeader: true);
// Define the ML.NET data preprocessing pipeline
var pipeline = _mlContext.Transforms.Text.FeaturizeText("Features_Context", nameof(LanguageData.Context))
.Append(_mlContext.Transforms.Text.FeaturizeText("Features_Question", nameof(LanguageData.Question)))
.Append(_mlContext.Transforms.Concatenate("Features", "Features_Context", "Features_Question"))
.Append(_mlContext.Regression.Trainers.LbfgsPoissonRegression(labelColumnName: nameof(LanguageData.AnswerIndex)));
// Train the model
var model = pipeline.Fit(dataView);
// Save the model for future predictions
_mlContext.Model.Save(model, dataView.Schema, "model.zip");
Console.WriteLine("Model trained and saved successfully.");
}
public static void ValidateModel()
{
Console.WriteLine("Model validation started...");
// Load the trained model
ITransformer model;
using (var stream = new FileStream("Model.zip", FileMode.Open, FileAccess.Read, FileShare.Read))
{
model = _mlContext.Model.Load(stream, out var modelSchema);
}
// Sample input for prediction
var sampleData = new DataFrame(new List
{
new StringDataFrameColumn("ColumnToPredict", new[] { "Sample Prediction" }),
new StringDataFrameColumn("Context", new[] { "
This is a sample HTML content.
" }),
new StringDataFrameColumn("Question", new[] { "Sample Question" })
});
// Transform the sample data
var transformedData = model.Transform(sampleData);
// Extract predictions from transformed data
var predictionColumn = transformedData.GetColumn("ColumnToPredict");
// Retrieve the prediction (assuming single prediction in this case)
string prediction = predictionColumn.FirstOrDefault();
Console.WriteLine($"Predicted Answer: {prediction}");
Console.WriteLine("Model validation completed.");
}
public static void AnswerUserQuestion()
{
while (true)
{
Console.WriteLine();
Console.WriteLine("Ask a question (or type 'exit' to quit):");
string question = Console.ReadLine();
if (question.ToLower() == "exit")
break;
// Load the trained model for answering questions
ITransformer model;
using (var stream = new FileStream("Model.zip", FileMode.Open, FileAccess.Read, FileShare.Read))
{
model = _mlContext.Model.Load(stream, out var modelSchema);
}
var predictionEngine = _mlContext.Model.CreatePredictionEngine(model);
// Use ML.NET model to predict sentiment
var prediction = predictionEngine.Predict(new LanguageData { Question = question });
var response = prediction.PredictedLabel;
Console.WriteLine($"Response: {response}");
}
}
// Define the data schema
public class LanguageData
{
[LoadColumn(0)]
public string ColumnToPredict { get; set; }
[LoadColumn(1)]
public string Context { get; set; }
[LoadColumn(2)]
public string Question { get; set; }
[LoadColumn(3)]
public float AnswerIndex { get; set; }
}
// Prediction output class
public class LanguagePrediction
{
[ColumnName("PredictedLabel")]
public float PredictedLabel { get; set; }
}
// Helper class for HTML preprocessing
public static class HtmlHelper
{
public static string CleanHtml(string html)
{
// Implement HTML cleaning logic here
var doc = new HtmlDocument();
doc.LoadHtml(html);
// Example: Extracting text from paragraphs
var text = string.Join(" ", doc.DocumentNode.SelectNodes("//p")
.Select(p => p.InnerText.Trim()));
return text;
}
}
}
Ошибка:
System.Reflection.TargetInvocationException HResult=0x80131604
Message=Exception был создан целью вызова.
Source=System.Private.CoreLib StackTrace: at
System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object
obj, Span1 copyOfArgs, BindingFlags invokeAttr) at System.Reflection.MethodBaseInvoker.InvokeWithFewArgs(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) at Microsoft.ML.Internal.Utilities.Utils.MarshalInvoke[TArg1,TArg2,TResult](FuncStaticMethodInfo33
func, Type genArg1, Type genArg2, Type genArg3, TArg1 arg1, TArg2
arg2) в Microsoft.ML.ApiUtils.GeneratePeek[TOwn,TRow](Column
column ) в
Microsoft.ML.Data.DataViewConstructionUtils.InputRow1.MakePeeks(InternalSchemaDefinition schemaDef) at Microsoft.ML.Data.DataViewConstructionUtils.InputRow1..ctor(IHostEnvironment
env, InternalSchemaDefinition SchemaDef) в
Microsoft.ML.Data.DataViewConstructionUtils.CreateInputRow[TRow](IHostEnvironment
env, SchemaDefinition SchemaDefinition) в
Microsoft.ML.PredictionEngineBase2..ctor(IHostEnvironment env, ITransformer transformer, Boolean ignoreMissingColumns, SchemaDefinition inputSchemaDefinition, SchemaDefinition outputSchemaDefinition, Boolean ownsTransformer) at Microsoft.ML.PredictionEngine2..ctor(IHostEnvironment env,
преобразователь ITransformer, логическое значение ignoreMissingColumns,
SchemaDefinition inputSchemaDefinition, SchemaDefinition
outputSchemaDefinition, логическое значение ownsTransformer) в
Microsoft.ML.PredictionEngineExtensions. CreatePredictionEngine[TSrc,TDst](ITransformer
transformer, IHostEnvironment env, Boolean ignoreMissingColumns,
SchemaDefinition inputSchemaDefinition, SchemaDefinition
outputSchemaDefinition, Boolean ownsTransformer) в
Microsoft.ML.ModelOperationsCatalog.CreatePredictionEngine[ TSrc,TDst](ITransformer
transformer, Boolean ignoreMissingColumns, SchemaDefinition
inputSchemaDefinition, SchemaDefinition outputSchemaDefinition) в
Program.AnswerUserQuestion() в
C:\repo\Blazor.Tools\NaturalLanguageQA \NaturalLanguageQA\Program.cs:line
141 в Program.Main(String[] args) в
C:\repo\Blazor.Tools\NaturalLanguageQA\NaturalLanguageQA\Program.cs:line
53
Это исключение изначально было создано в этом стеке вызовов:
[Внешний код]
Внутреннее исключение 1: PlatformNotSupportedException: Динамический кодгенерация не поддерживается на этой платформе.
Строка кода ошибки:
var predictionEngine = _mlContext.Model.CreatePredictionEngine(model);
Подробнее здесь: https://stackoverflow.com/questions/787 ... ing-ml-net
Ответы на вопросы на естественном языке: как вы тренируетесь и оцениваете использование ML.Net ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как создать собственное решение математических задач для описаний на естественном языке?
Anonymous » » в форуме Python - 0 Ответы
- 26 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Невозможно задать вопрос на естественном языке базе данных MySQL - Оллама [закрыто]
Anonymous » » в форуме C# - 0 Ответы
- 24 Просмотры
-
Последнее сообщение Anonymous
-