首页 新闻 会员 周边 捐助

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

0
悬赏园豆:100 [已解决问题] 解决于 2014-06-06 14:59

能提供一个double类型的结合,提供一个分类个数   实现分组的函数

 

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

李辉健的主页 李辉健 | 初学一级 | 园豆:56
提问于:2014-06-02 11:06
< >
分享
最佳答案
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.Add(new Crowd());
                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;
                    }
                    crowds[index].List.Add(num);
                }
            }
            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;
            }
        }
收获园豆:100
Allen MM | 菜鸟二级 |园豆:302 | 2014-06-03 12:50
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册