# 求一个C#实现的K-Means聚类算法

0

public  List<Crowd> Compute(List<double> list, int count)  这种类型的函数

0
public static List<Crowd> Compute(List<double> list, int count)
{
var crowds = new List<Crowd>(count);
list.Sort();

var step = list.Count() / (count * 2);
for (var i = 0; i < count; i++)
{
crowds[i].Center = list[step + step*2*i];
}

while (crowds.Sum(crowd => crowd.Change) > 0.01)
{
//Empty List and refresh Center
crowds.ForEach(
crowd =>
{
if (!crowd.List.Any()) return;
crowd.RefreshCenter();
crowd.List.Clear();
});

foreach (var num in list)
{
var index = 0; var minDistance = double.MaxValue;
for (var i = 0; i < count; i++)
{
var distance = Math.Abs(crowds[i].Center - num);
if (!(distance < minDistance)) continue;
index = i; minDistance = distance;
}
}
}
return crowds;
}

/// <summary>
/// 集群
/// </summary>
public class Crowd
{
public List<double> List { get; set; }

public double Average { get { return List.Average(); } }

public double Center { get; set; }

public double Change { get; private set; }

public Crowd()
{
Change = double.MaxValue;
List = new List<double>();
}

public void RefreshCenter()
{
Change = Math.Abs(Average - Center);
Center = Average;
}
}

Allen MM | 菜鸟二级 |园豆：302 | 2014-06-03 12:50

您需要登录以后才能回答，未注册用户请先注册