WeatherForecastController.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. using InfluxData.Net.Common.Enums;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.Extensions.Logging;
  4. using Microsoft.ML;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. using InfluxData.Net.Common.Enums;
  10. using InfluxData.Net.InfluxDb;
  11. using Microsoft.ML.Data;
  12. using Microsoft.ML.Transforms;
  13. namespace Ropin.IOT.MLService.Controllers
  14. {
  15. [ApiController]
  16. [Route("[controller]")]
  17. public class WeatherForecastController : ControllerBase
  18. {
  19. private static readonly string[] Summaries = new[]
  20. {
  21. "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
  22. };
  23. private readonly ILogger<WeatherForecastController> _logger;
  24. public WeatherForecastController(ILogger<WeatherForecastController> logger)
  25. {
  26. _logger = logger;
  27. }
  28. [HttpGet]
  29. public IEnumerable<WeatherForecast> Get()
  30. {
  31. var rng = new Random();
  32. return Enumerable.Range(1, 5).Select(index => new WeatherForecast
  33. {
  34. Date = DateTime.Now.AddDays(index),
  35. TemperatureC = rng.Next(-20, 55),
  36. Summary = Summaries[rng.Next(Summaries.Length)]
  37. })
  38. .ToArray();
  39. }
  40. [HttpPatch]
  41. public async void PatchAI()
  42. {
  43. // Create a new context for ML operations
  44. var mlContext = new MLContext();
  45. // Sample data points in-memory collection
  46. IDataView dataPoints = mlContext.Data.LoadFromEnumerable(new[]
  47. {
  48. new DataPoint() { Feature = 1, Label = 2 },
  49. new DataPoint() { Feature = 2, Label = 4 },
  50. new DataPoint() { Feature = 3, Label = 6 },
  51. new DataPoint() { Feature = 4, Label = 8 },
  52. new DataPoint() { Feature = 5, Label = 10 }
  53. });
  54. // Define the pipeline
  55. var pipeline = mlContext.Transforms.Concatenate("Features", nameof(DataPoint.Feature))
  56. .Append(mlContext.Regression.Trainers.Sdca());
  57. // Train the model
  58. var trainedModel = pipeline.Fit(dataPoints);
  59. // Create a prediction engine to make predictions on individual data points
  60. var predEngine = mlContext.Model.CreatePredictionEngine<DataPoint, Prediction>(trainedModel);
  61. // Make a prediction
  62. var prediction = predEngine.Predict(new DataPoint() { Feature = 6 });
  63. Console.WriteLine($"Predicted value: {prediction.PredictedValue}");
  64. }
  65. public class DataPoint
  66. {
  67. [LoadColumn(0)]
  68. public float Feature { get; set; }
  69. [LoadColumn(1)]
  70. public float Label { get; set; }
  71. }
  72. public class DeviceStatusPoint
  73. {
  74. [LoadColumn(0)]
  75. public DateTime TimeStamp { get; set; }
  76. [LoadColumn(1)]
  77. public float Temperature { get; set; }
  78. [LoadColumn(2)]
  79. public float Pressure { get; set; }
  80. [LoadColumn(3)]
  81. public bool IsFaulty { get; set; }
  82. [LoadColumn(4)]
  83. public float Label { get; set; }
  84. }
  85. public class Prediction
  86. {
  87. [ColumnName("Score")]
  88. public float PredictedValue { get; set; }
  89. }
  90. [HttpPost]
  91. public async void GetAI()
  92. {
  93. await GetData();
  94. }
  95. private async Task GetData()
  96. {
  97. //// 查询最近 10 条 CPU 使用率数据
  98. // var query1 = "SELECT * FROM fanyidev ORDER BY time DESC LIMIT 10";
  99. // var results = await client.QueryMultiSeriesAsync("fanyidb", query1);
  100. // if (results != null && results.Count > 0)
  101. // {
  102. // }
  103. // if (results != null && results.Count > 0)
  104. // {
  105. // // 处理查询结果
  106. // foreach (var series in results)
  107. // {
  108. // Console.WriteLine($"查询结果集: {series.Name}");
  109. // foreach (var point in series.Entries)
  110. // {
  111. // // 根据字段名获取值
  112. // var time = point.GetTimeAsDateTime();
  113. // var host = point.GetTagAsString("host");
  114. // var value = point.GetFieldAsDouble("value");
  115. // Console.WriteLine($"时间: {time}, 主机: {host}, CPU 使用率: {value}");
  116. // }
  117. //}
  118. // }
  119. //传入查询命令,支持多条
  120. var queries = new[]
  121. {
  122. " SELECT * FROM fanyidev WHERE time> now() - 1h "
  123. };
  124. var dbName = "fanyidb";
  125. InfluxDbClient influxDbClient = new InfluxDbClient("http://10.126.126.131:8085/", "admin", "123456", InfluxDbVersion.Latest);
  126. //从指定库中查询数据
  127. var response = await influxDbClient.Client.QueryAsync(queries, dbName);
  128. if (response.Any())
  129. {
  130. var series = response.ToList();
  131. foreach (var value in series[0].Values)
  132. {
  133. //var TimeStamp = DateTime.Parse((string)value[0]);
  134. var Pressure = Convert.ToDouble(value[2]);
  135. }
  136. //var dataPoints = series[0].Values.Select(value =>
  137. // new DeviceStatusDataPoint
  138. // {
  139. // //TimeStamp = DateTime.Parse((string)value[0]),
  140. // //Temperature = Convert.ToDouble(value[1]),
  141. // Pressure = Convert.ToDouble(value[2])//,
  142. // //IsFaulty = (bool)value[3]
  143. // }).ToList();
  144. var dataPoints = new List<DeviceStatusPoint>();
  145. var v1 = new DeviceStatusPoint
  146. {
  147. TimeStamp = DateTime.Now.AddMilliseconds(-1),
  148. Temperature = 70,
  149. Pressure = 150,
  150. IsFaulty = true,
  151. Label = 10
  152. };
  153. var v2 = new DeviceStatusPoint
  154. {
  155. TimeStamp = DateTime.Now,
  156. Temperature = 60,
  157. Pressure = 140,
  158. IsFaulty = false,
  159. Label = 20
  160. };
  161. dataPoints.Add(v1);
  162. dataPoints.Add(v2);
  163. // 使用 ML.NET 训练模型
  164. var mlContext = new MLContext();
  165. // 将数据加载到 IDataView
  166. IDataView dataView = mlContext.Data.LoadFromEnumerable(dataPoints);
  167. //// Define the pipeline
  168. //var pipeline1 = mlContext.Transforms.Concatenate("Features", nameof(DeviceStatusPoint.Temperature), nameof(DeviceStatusPoint.Pressure))
  169. // .Append(mlContext.Regression.Trainers.Sdca());
  170. //// Train the model
  171. //var trainedModel = pipeline1.Fit(dataView);
  172. //// Create a prediction engine to make predictions on individual data points
  173. //var predEngine = mlContext.Model.CreatePredictionEngine<DeviceStatusPoint, FaultPrediction>(trainedModel);
  174. //// Make a prediction
  175. //var prediction1 = predEngine.Predict(new DeviceStatusPoint { Temperature = 75, Pressure = 150 });
  176. //Console.WriteLine($"Predicted value: {prediction1.PredictedLabel}");
  177. // 分割数据集为训练集和测试集
  178. var trainTestSplit = mlContext.Data.TrainTestSplit(dataView, testFraction: 0.2);
  179. var trainingData = trainTestSplit.TrainSet;
  180. var testData = trainTestSplit.TestSet;
  181. // 定义管道
  182. var pipeline = mlContext.Transforms.Concatenate("Features", nameof(DeviceStatusPoint.Temperature), nameof(DeviceStatusPoint.Pressure))
  183. .Append(mlContext.BinaryClassification.Trainers.SdcaLogisticRegression(labelColumnName: nameof(DeviceStatusPoint.IsFaulty)));
  184. var progressHandler = new TrainingProgressHandler();
  185. //Console.WriteLine("Starting model training...");
  186. //var cvResults = mlContext.MulticlassClassification.CrossValidate(trainingData, pipeline, numberOfFolds: 5, progressHandler: progressHandler);
  187. //Console.WriteLine("Training completed.");
  188. // 训练模型
  189. var model = pipeline.Fit(trainingData);
  190. // 创建预测引擎
  191. var predictionEngine = mlContext.Model.CreatePredictionEngine<DeviceStatusPoint, FaultPrediction>(model);
  192. // 预测新样本
  193. var sampleData = new DeviceStatusPoint { Temperature = 75, Pressure = 150 };
  194. var prediction = predictionEngine.Predict(sampleData);
  195. Console.WriteLine($"Predicted IsFaulty: {prediction.PredictedLabel}, Probability: {prediction.Probability}");
  196. // 评估模型
  197. var predictions = model.Transform(testData);
  198. var metrics = mlContext.BinaryClassification.Evaluate(predictions);
  199. Console.WriteLine($"Accuracy: {metrics.Accuracy}");
  200. }
  201. else
  202. {
  203. Console.WriteLine("Failed to retrieve data from InfluxDB.");
  204. }
  205. }
  206. }
  207. public class TrainingProgressHandler : IProgress<TrainCatalogBase.CrossValidationResult<MulticlassClassificationMetrics>>
  208. {
  209. public void Report(TrainCatalogBase.CrossValidationResult<MulticlassClassificationMetrics> value)
  210. {
  211. //Console.WriteLine(value: $"Fold: {value.Model.Properties.TrainingTime}");
  212. }
  213. }
  214. }