using InfluxData.Net.Common.Enums; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.ML; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using InfluxData.Net.Common.Enums; using InfluxData.Net.InfluxDb; using Microsoft.ML.Data; using Microsoft.ML.Transforms; namespace Ropin.IOT.MLService.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger _logger; public WeatherForecastController(ILogger logger) { _logger = logger; } [HttpGet] public IEnumerable Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } [HttpPatch] public async void PatchAI() { // Create a new context for ML operations var mlContext = new MLContext(); // Sample data points in-memory collection IDataView dataPoints = mlContext.Data.LoadFromEnumerable(new[] { new DataPoint() { Feature = 1, Label = 2 }, new DataPoint() { Feature = 2, Label = 4 }, new DataPoint() { Feature = 3, Label = 6 }, new DataPoint() { Feature = 4, Label = 8 }, new DataPoint() { Feature = 5, Label = 10 } }); // Define the pipeline var pipeline = mlContext.Transforms.Concatenate("Features", nameof(DataPoint.Feature)) .Append(mlContext.Regression.Trainers.Sdca()); // Train the model var trainedModel = pipeline.Fit(dataPoints); // Create a prediction engine to make predictions on individual data points var predEngine = mlContext.Model.CreatePredictionEngine(trainedModel); // Make a prediction var prediction = predEngine.Predict(new DataPoint() { Feature = 6 }); Console.WriteLine($"Predicted value: {prediction.PredictedValue}"); } public class DataPoint { [LoadColumn(0)] public float Feature { get; set; } [LoadColumn(1)] public float Label { get; set; } } public class DeviceStatusPoint { [LoadColumn(0)] public DateTime TimeStamp { get; set; } [LoadColumn(1)] public float Temperature { get; set; } [LoadColumn(2)] public float Pressure { get; set; } [LoadColumn(3)] public bool IsFaulty { get; set; } [LoadColumn(4)] public float Label { get; set; } } public class Prediction { [ColumnName("Score")] public float PredictedValue { get; set; } } [HttpPost] public async void GetAI() { await GetData(); } private async Task GetData() { //// 查询最近 10 条 CPU 使用率数据 // var query1 = "SELECT * FROM fanyidev ORDER BY time DESC LIMIT 10"; // var results = await client.QueryMultiSeriesAsync("fanyidb", query1); // if (results != null && results.Count > 0) // { // } // if (results != null && results.Count > 0) // { // // 处理查询结果 // foreach (var series in results) // { // Console.WriteLine($"查询结果集: {series.Name}"); // foreach (var point in series.Entries) // { // // 根据字段名获取值 // var time = point.GetTimeAsDateTime(); // var host = point.GetTagAsString("host"); // var value = point.GetFieldAsDouble("value"); // Console.WriteLine($"时间: {time}, 主机: {host}, CPU 使用率: {value}"); // } //} // } //传入查询命令,支持多条 var queries = new[] { " SELECT * FROM fanyidev WHERE time> now() - 1h " }; var dbName = "fanyidb"; InfluxDbClient influxDbClient = new InfluxDbClient("http://10.126.126.131:8085/", "admin", "123456", InfluxDbVersion.Latest); //从指定库中查询数据 var response = await influxDbClient.Client.QueryAsync(queries, dbName); if (response.Any()) { var series = response.ToList(); foreach (var value in series[0].Values) { //var TimeStamp = DateTime.Parse((string)value[0]); var Pressure = Convert.ToDouble(value[2]); } //var dataPoints = series[0].Values.Select(value => // new DeviceStatusDataPoint // { // //TimeStamp = DateTime.Parse((string)value[0]), // //Temperature = Convert.ToDouble(value[1]), // Pressure = Convert.ToDouble(value[2])//, // //IsFaulty = (bool)value[3] // }).ToList(); var dataPoints = new List(); var v1 = new DeviceStatusPoint { TimeStamp = DateTime.Now.AddMilliseconds(-1), Temperature = 70, Pressure = 150, IsFaulty = true, Label = 10 }; var v2 = new DeviceStatusPoint { TimeStamp = DateTime.Now, Temperature = 60, Pressure = 140, IsFaulty = false, Label = 20 }; dataPoints.Add(v1); dataPoints.Add(v2); // 使用 ML.NET 训练模型 var mlContext = new MLContext(); // 将数据加载到 IDataView IDataView dataView = mlContext.Data.LoadFromEnumerable(dataPoints); //// Define the pipeline //var pipeline1 = mlContext.Transforms.Concatenate("Features", nameof(DeviceStatusPoint.Temperature), nameof(DeviceStatusPoint.Pressure)) // .Append(mlContext.Regression.Trainers.Sdca()); //// Train the model //var trainedModel = pipeline1.Fit(dataView); //// Create a prediction engine to make predictions on individual data points //var predEngine = mlContext.Model.CreatePredictionEngine(trainedModel); //// Make a prediction //var prediction1 = predEngine.Predict(new DeviceStatusPoint { Temperature = 75, Pressure = 150 }); //Console.WriteLine($"Predicted value: {prediction1.PredictedLabel}"); // 分割数据集为训练集和测试集 var trainTestSplit = mlContext.Data.TrainTestSplit(dataView, testFraction: 0.2); var trainingData = trainTestSplit.TrainSet; var testData = trainTestSplit.TestSet; // 定义管道 var pipeline = mlContext.Transforms.Concatenate("Features", nameof(DeviceStatusPoint.Temperature), nameof(DeviceStatusPoint.Pressure)) .Append(mlContext.BinaryClassification.Trainers.SdcaLogisticRegression(labelColumnName: nameof(DeviceStatusPoint.IsFaulty))); var progressHandler = new TrainingProgressHandler(); //Console.WriteLine("Starting model training..."); //var cvResults = mlContext.MulticlassClassification.CrossValidate(trainingData, pipeline, numberOfFolds: 5, progressHandler: progressHandler); //Console.WriteLine("Training completed."); // 训练模型 var model = pipeline.Fit(trainingData); // 创建预测引擎 var predictionEngine = mlContext.Model.CreatePredictionEngine(model); // 预测新样本 var sampleData = new DeviceStatusPoint { Temperature = 75, Pressure = 150 }; var prediction = predictionEngine.Predict(sampleData); Console.WriteLine($"Predicted IsFaulty: {prediction.PredictedLabel}, Probability: {prediction.Probability}"); // 评估模型 var predictions = model.Transform(testData); var metrics = mlContext.BinaryClassification.Evaluate(predictions); Console.WriteLine($"Accuracy: {metrics.Accuracy}"); } else { Console.WriteLine("Failed to retrieve data from InfluxDB."); } } } public class TrainingProgressHandler : IProgress> { public void Report(TrainCatalogBase.CrossValidationResult value) { //Console.WriteLine(value: $"Fold: {value.Model.Properties.TrainingTime}"); } } }