MLService.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. 
  2. using Microsoft.ML;
  3. using Microsoft.ML.Data;
  4. namespace HTEXScreen.Service
  5. {
  6. public static class MLService
  7. {
  8. /// <summary>
  9. ///
  10. /// </summary>
  11. /// <param name="datas">数据需要去掉0</param>
  12. /// <param name="numberOfClusters"></param>
  13. /// <returns></returns>
  14. public static List<ClusterData> KMeans(float[] datas, int numberOfClusters = 5)
  15. {
  16. List<DataPoint> data = new List<DataPoint>();
  17. foreach (var d in datas)
  18. {
  19. data.Add(new DataPoint { Feature = d });
  20. }
  21. // 定义数据视图
  22. var mlContext = new MLContext();
  23. var dataView = mlContext.Data.LoadFromEnumerable(data);
  24. // 定义聚类管道
  25. var pipeline = mlContext.Transforms.Concatenate("Features", new[] { "Feature" })
  26. .Append(mlContext.Clustering.Trainers.KMeans(numberOfClusters: numberOfClusters)); // 假设我们想要将数据分成3个集群
  27. // 训练模型
  28. var model = pipeline.Fit(dataView);
  29. // 转换数据以获取聚类结果
  30. var predictions = model.Transform(dataView);
  31. // 提取聚类结果
  32. var inMemoryCollection = mlContext.Data.CreateEnumerable<ClusterPrediction>(predictions, reuseRowObject: false);
  33. // 打印聚类结果
  34. //var clusterSizes = new int[3]; // 假设有3个聚类
  35. int index = 0;
  36. List<ClusterData> clusterDatas = new List<ClusterData>();
  37. foreach (var prediction in inMemoryCollection)
  38. {
  39. //Console.WriteLine($"Data point: {data[index].Feature}, Cluster: {prediction.ClusterId}");
  40. var clusterData = clusterDatas.Find(x => x.ClusterId.Equals(prediction.ClusterId));
  41. if (clusterData!=null)
  42. {
  43. clusterData.count +=1;
  44. clusterData.datas.Add(data[index].Feature);
  45. clusterData.avg=clusterData.datas.Sum() / clusterData.datas.Count();
  46. }
  47. else
  48. {
  49. clusterDatas.Add(new ClusterData { avg=data[index].Feature, count=1, ClusterId=prediction.ClusterId, datas=new List<float> { data[index].Feature } });
  50. }
  51. index++;
  52. //计算每个聚类的数据点数量
  53. //clusterSizes[prediction.ClusterId-1]++;
  54. }
  55. // 预测聚类
  56. // 确定最密集的部分
  57. // 这通常需要对聚类结果进行分析,比如计算每个聚类的平均距离、大小等
  58. // 在这里,你可以通过比较不同聚类的数据点数量或计算聚类中心周围的密度来估计哪个是最密集的
  59. // 找出最大的聚类
  60. // var maxClusterIndex = clusterSizes.ToList().IndexOf(clusterSizes.Max());
  61. //Console.WriteLine($"The densest cluster is cluster {maxClusterIndex} with {clusterSizes[maxClusterIndex]} data points.");
  62. // 你还可以进一步分析聚类的特性,比如找出聚类中心、计算聚类内的方差等
  63. return clusterDatas;
  64. }
  65. /// <summary>
  66. ///
  67. /// </summary>
  68. /// <param name="datas"></param>
  69. /// <param name="numberOfClusters"></param>
  70. /// <param name="dropPercent">最大平均数的聚类与数量最多的聚类数量的落差小于30% 则以更高的为准</param>
  71. /// <returns></returns>
  72. public static ClusterData GetNormalCluster (float[] datas, int numberOfClusters = 5,double dropPercent=0.3)
  73. {
  74. List<ClusterData> clusterDatas = KMeans(datas, numberOfClusters);
  75. clusterDatas=clusterDatas.OrderByDescending(dr => dr.count).ToList();
  76. ClusterData clusterData = FindSatisfactoryRecord(clusterDatas, 0, dropPercent);
  77. return clusterData;
  78. }
  79. static ClusterData FindSatisfactoryRecord(List<ClusterData> data, int currentIndex,double dropPercent)
  80. { // 如果当前索引小于0,说明已经到达列表开头,返回null
  81. if (currentIndex < 0) { return null; }
  82. // 获取当前数据
  83. ClusterData current = data.ElementAt(currentIndex);
  84. if (currentIndex+1>=data.Count())
  85. {
  86. return current;
  87. }
  88. else
  89. {
  90. ClusterData next = data.ElementAt(currentIndex +1); // 检查平均值和人数差是否满足条件
  91. if (current.avg > next.avg)
  92. {
  93. return current;
  94. }
  95. else
  96. {
  97. var d = (current.count- next.count)*1.0/current.count;
  98. if (d>=dropPercent)
  99. {
  100. return current;
  101. }
  102. else
  103. { // 递归调用,继续向前比较
  104. return FindSatisfactoryRecord(data, currentIndex + 1, dropPercent);
  105. }
  106. }
  107. }
  108. }
  109. }
  110. // 定义数据模型
  111. public class DataPoint
  112. {
  113. public float Feature { get; set; }
  114. }
  115. // 聚类预测类
  116. public class ClusterPrediction
  117. {
  118. [ColumnName("PredictedLabel")]
  119. public uint ClusterId;
  120. // 你可以添加其他预测列,比如距离聚类中心的距离等
  121. }
  122. public class ClusterData
  123. {
  124. public List<float> datas = new List<float>();
  125. public uint ClusterId { get; set; }
  126. public int count { get; set; }
  127. public float avg { get; set; }
  128. }
  129. }