聚类

前面做过一个神经网络的分类器 


现在有一些数据需要做聚类处理。 


那什么叫做聚类呢 跟分类有什么区别。


分类:明确知道类别,然后把数据归类。

聚类:你不知道类别,但你想把这些数据分成N类,根据某种算法把数据进行分组,相似或相近的自动归到一组中。(一般用k均值聚类算法)



聚类与分类相比较:

分类:实例式学习,分类前明确各个类别的信息,并可以直接断言每个元素映射到一个类别;

聚类:无监督学习,在聚类前不知道类别甚至不给定类别数量,不依赖预定义的类和类标号。


聚类的应用:

在许多时候分类条件不满足,尤其是处理海量数据时,如果通过预处理使数据满足分类算法的要求,代价巨大,应考虑聚类算法。

聚类的用途是很广泛的。在商业上,聚类可以帮助市场分析人员从消费者数据库中区分出不同的消费群体来,并且概括出每一类消费者的消费模式或者说习惯。它作为数据挖掘中的一个模块,可以作为一个单独的工具以发现数据库中分布的一些深层的信息,并且概括出每一类的特点,或者把注意力放在某一个特定的类上以作进一步的分析;并且,聚类分析也可以作为数据挖掘算法中其他分析算法的一个预处理步骤。

目前聚类广泛应用于统计学、生物学、数据库技术和市场营销等领域。

 

聚类算法的局限:

(1)要求数据分离度好。对相互渗透的类无法得到统一的结果。

(2)线性相关。聚类方法分析仅是简单的一对一的关系。忽视了生物系统多因素和非线性的特点。


K均值聚类算法

算法思想:

给定一个有N个元素的集合,划分为K个簇,每一个簇就代表一个聚类,K<N。而且这K个簇满足下列条件:

(1) 每一个簇至少包含一个元素;

(2) 每一个元素属于且仅属于一个簇。

对于给定的K,算法首先给出一个初始的分组方法,以后通过反复迭代的方法改变分组,使得每一次改进之后的分组方案都较前一次优化,即同一分组中的元素相异度降低,而不同分组中的元素相异度升高。

 

只要去重后集合的元素仍大于k时 才能进行聚类

 

算法过程:

1、预处理: 数据规格化;

(1).剔除异常数据  剔除异常数据的方法可考虑均值-标准差法


(2).(具体根据情况判断是否需要归一化)

归一化:

当某个属性的取值跨度远大于其他属性时,不利于真实反映真实的相异度,为了解决这个问题,一般要对属性值进行规格化。所谓规格化就是将各个属性值按比例映射到相同的取值区间,这样是为了平衡各个属性对距离的影响。通常将各个属性均映射到[0,1]区间,映射公式为:

 x'=x-集合最小值/集合最大值-集合最小值


2、从D中随机取k个元素,作为k个簇的各自的中心。

3、分别计算剩下的元素到k个簇中心的相异度,将这些元素分别划归到相异度最低的簇。

4、根据聚类结果,重新计算k个簇各自的中心,计算方法是取簇中所有元素各自维度的算术平均数。

5、将D中全部元素按照新的中心重新聚类。

6、重复第4步,直到聚类结果收敛到不再变化。

7、将结果输出。




我找了一些资料  发现 聚类的运用 一般有三种: 数值聚类(例如成绩聚类)   文本的聚类    坐标点的聚类


数值聚类:

数值聚类是比较简单的  因为它们能直接求均值而不用做其他的一些处理 

步骤是:

一: 随机产生是三个不重复的数值 作为 质心 

二:计算每一个数值到质心的距离  公式 :     Math.Sqrt((x-质心)*(x-质心))   数值减去质心平方后开方

三:把数值归入到距离最小的 质心所代表的类中 

四:计算每个类的均值作为质心,跟旧的质心做对比,如果不相等,则从步骤二开始 迭代。 直到质心值不再变化,这样类就分好了。


下面记录几段比较重要的代码;

1.生成不重复的随机数值

[csharp]  view plain  copy
  1. /// <summary>  
  2. /// get different random  
  3. /// </summary>  
  4. /// <param name="arrNum"></param>  
  5. /// <param name="tmp"></param>  
  6. /// <param name="minValue"></param>  
  7. /// <param name="maxValue"></param>  
  8. /// <param name="ra"></param>  
  9. /// <returns></returns>  
  10. public int[] getNum(int count, int total)  
  11. {  
  12.     int[] index = new int[total];  
  13.     for (int i = 0; i < total; i++)  
  14.     {  
  15.         index[i] = i;  
  16.     }  
  17.     Random r = new Random();  
  18.     //用来保存随机生成的不重复的count个数    
  19.     int[] result = new int[count];  
  20.     //int site = total;//设置下限    
  21.     int id;  
  22.     for (int j = 0; j < count; j++)  
  23.     {  
  24.         id = r.Next(0, total - 1);  
  25.         //在随机位置取出一个数,保存到结果数组    
  26.         result[j] = index[id];  
  27.         //最后一个数复制到当前位置    
  28.         index[id] = index[total - 1];  
  29.         //位置的下限减少一    
  30.         total--;  
  31.     }  
  32.   
  33.     return result;  
  34.   
  35. }  

判断新旧质心是否相等

[csharp]  view plain  copy
  1. /// <summary>  
  2. /// judge the value of center  
  3. /// </summary>  
  4. /// <param name="center"></param>  
  5. /// <param name="newcenter"></param>  
  6. /// <param name="ok"></param>  
  7. /// <returns></returns>  
  8. private static bool judge(double[] center, double[] newcenter, bool ok)  
  9. {  
  10.     int count = 0;  
  11.     for (int i = 0; i < newcenter.Length; i++)  
  12.     {  
  13.         if (center[i] == newcenter[i])  
  14.         { count++; }  
  15.   
  16.   
  17.     }  
  18.     if (count == newcenter.Length)  
  19.     {  
  20.         ok = true;  
  21.     }  
  22.     return ok;  
  23. }  


当去重后集合的元素仍大于k时 聚类的过程 迭代 用一个标志 和while()

[csharp]  view plain  copy
  1. if (price_all.Count >= k)  
  2.                {  
  3.                    //cluster the list building element  
  4.                    Random Rd = new Random();  //make a  random example  
  5.   
  6.   
  7.   
  8.                    double[] center = new double[k];  
  9.                    double[] oldcenter = new double[k];  
  10.                    int[] ran = new int[k];  
  11.                    int temp_c = price_all.Count;  
  12.                    ran = getNum(k, temp_c);  
  13.                    for (int i = 0; i < center.Length; i++)  
  14.                    {  
  15.   
  16.   
  17.                        center[i] = price_all[ran[i]];  
  18.   
  19.   
  20.                    }  
  21.   
  22.   
  23.   
  24.                    for (int i = 0; i < oldcenter.Length; i++)  
  25.                    {  
  26.                        oldcenter[i] = 0.0;  
  27.                    }  
  28.   
  29.                    bool ok = false;  
  30.   
  31.                    ok = judge(center, oldcenter, ok);  
  32.   
  33.   
  34.   
  35.                    int ireation = 0;  
  36.                    while (!ok)  
  37.                    {  
  38.   
  39.                        for (int i = 0; i < building_element.Count; i++)  
  40.                        {  
  41.   
  42.                            //repeat cluster  
  43.                            double temp_price = building_element[i].get_price();  
  44.                            double[] distance = new double[k];  
  45.                            for (int j = 0; j < center.Length; j++)  
  46.                            {  
  47.                                double v = temp_price - center[j];  
  48.                                distance[j] = Math.Sqrt(v * v); // distance  
  49.   
  50.                            }  
  51.                            //get the min distance  
  52.                            double temp_min = 999999999999999999;  
  53.                            int min_index = 999;  
  54.                            for (int j = 0; j < center.Length; j++)  
  55.                            {  
  56.   
  57.                                if (distance[j] <= temp_min)  
  58.                                {  
  59.                                    temp_min = distance[j];  
  60.                                    min_index = j + 1;  
  61.                                }  
  62.   
  63.                            }  
  64.                            building_element[i].set_type(min_index);  
  65.   
  66.   
  67.   
  68.                        }  
  69.   
  70.                        for (int n = 0; n < k; n++)  
  71.                        {  
  72.                            oldcenter[n] = center[n];  
  73.                        }  
  74.   
  75.   
  76.                        //get averange to  be center   
  77.                        double[] total = new double[k];  
  78.                        int[] element_countoftype = new int[k];  
  79.                        for (int n = 0; n < k; n++)  
  80.                        {  
  81.   
  82.                            for (int i = 0; i < building_element.Count; i++)  
  83.                            {  
  84.                                if (building_element[i].get_type() == n + 1)  
  85.                                {  
  86.                                    total[n] += building_element[i].get_price();  
  87.                                    element_countoftype[n]++;  
  88.                                }  
  89.   
  90.                            }  
  91.   
  92.                        }  
  93.   
  94.   
  95.                        int count_no_zero = 0;  
  96.                        for (int n = 0; n < k; n++)  
  97.                        {  
  98.                            if (total[n] != 0.0)  
  99.                            {  
  100.                                count_no_zero++;  
  101.                            }  
  102.   
  103.                        }  
  104.                        if (count_no_zero == k)  
  105.                        {  
  106.                            for (int n = 0; n < k; n++)  
  107.                            {  
  108.                                center[n] = total[n] / element_countoftype[n];  
  109.                            }  
  110.                        }  
  111.                        else  
  112.                        {  
  113.                            ran = new int[k];  
  114.                            temp_c = price_all.Count;  
  115.                            ran = getNum(k, temp_c);  
  116.                            for (int i = 0; i < center.Length; i++)  
  117.                            {  
  118.   
  119.   
  120.                                center[i] = price_all[ran[i]];  
  121.   
  122.   
  123.                            }  
  124.   
  125.                        }  
  126.   
  127.   
  128.   
  129.                        ok = judge(center, oldcenter, ok);  
  130.                        ireation++;  
  131.                        this.Invoke(new setStatusDelegate(setStatus), building_name_all[m], count, ireation);  
  132.                    }  
  133.                }  



文本聚类:

文本分类跟数值不同在于 要先对文本进行分词,并用TFIDF计算它们的权重 然后用权重向量进行计算。

思路:计算两篇文档的相似度,最简单的做法就是用提取文档的TF/IDF权重,然后用余弦定理计算两个多维向量的距离。能计算两个文本间的距离后,用标准的k-means算法就可以实现文本聚类了。


完整项目下载:

http://download.youkuaiyun.com/detail/q383965374/5960053



下面是一个控制台聚类器的代码:

Program.cs

[csharp]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Text;  
  5. using WawaSoft.Search.Common;  
  6.   
  7. namespace WawaSoft.Search.Test  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             //1、获取文档输入  
  14.             string[] docs = getInputDocs("input.txt");  
  15.             if (docs.Length < 1)  
  16.             {  
  17.                 Console.WriteLine("没有文档输入");  
  18.                 Console.Read();  
  19.                 return;  
  20.             }  
  21.   
  22.             //2、初始化TFIDF测量器,用来生产每个文档的TFIDF权重  
  23.             TFIDFMeasure tf = new TFIDFMeasure(docs, new Tokeniser());  
  24.   
  25.             int K = 3; //聚成3个聚类  
  26.   
  27.             //3、生成k-means的输入数据,是一个联合数组,第一维表示文档个数,  
  28.             //第二维表示所有文档分出来的所有词  
  29.             double[][] data = new double[docs.Length][];  
  30.             int docCount = docs.Length; //文档个数  
  31.             int dimension = tf.NumTerms;//所有词的数目  
  32.             for (int i = 0; i < docCount; i++)  
  33.             {  
  34.                 for (int j = 0; j < dimension; j++)  
  35.                 {  
  36.                     data[i] = tf.GetTermVector2(i); //获取第i个文档的TFIDF权重向量  
  37.                 }  
  38.             }  
  39.   
  40.             //4、初始化k-means算法,第一个参数表示输入数据,第二个参数表示要聚成几个类  
  41.             WawaKMeans kmeans = new WawaKMeans(data, K);  
  42.             //5、开始迭代  
  43.             kmeans.Start();  
  44.   
  45.             //6、获取聚类结果并输出  
  46.             WawaCluster[] clusters = kmeans.Clusters;  
  47.             foreach (WawaCluster cluster in clusters)  
  48.             {  
  49.                 List<int> members = cluster.CurrentMembership;  
  50.                 Console.WriteLine("-----------------");  
  51.                 foreach (int i in members)  
  52.                 {  
  53.                     Console.WriteLine(docs[i]);  
  54.                 }  
  55.   
  56.             }  
  57.             Console.Read();  
  58.         }  
  59.   
  60.         /// <summary>  
  61.         /// 获取文档输入  
  62.         /// </summary>  
  63.         /// <returns></returns>  
  64.         private static string[] getInputDocs(string file)  
  65.         {  
  66.             List<string> ret = new List<string>();  
  67.             try  
  68.             {  
  69.                 using (StreamReader sr = new StreamReader(file, Encoding.Default))  
  70.                 {  
  71.                     string temp;  
  72.                     while ((temp = sr.ReadLine()) != null)  
  73.                     {  
  74.                         ret.Add(temp);  
  75.                     }  
  76.                 }  
  77.             }  
  78.             catch (Exception ex)  
  79.             {  
  80.                 Console.WriteLine(ex);  
  81.             }  
  82.             return ret.ToArray();  
  83.         }  
  84.     }  
  85. }  


input.txt内容

奥运 拳击 入场券 基本 分罄 邹市明 夺冠 对手 浮出 水面
股民 要 清楚 自己 的 目的
印花税 之 股民 四季
杭州 股民 放 鞭炮 庆祝 印花税 下调 
残疾 女 青年 入围 奥运 游泳 比赛 创 奥运 历史 两 项 第一
介绍 一 个 ASP.net MVC 系列 教程
在 asp.net 中 实现 观察者 模式 ,或 有 更 好 的 方法 (续)
输 大钱 的 股民 给 我们 启迪
Asp.Net 页面 执行 流程 分析
运动员 行李 将 “后 上 先 下” 奥运 相关 人员 行李 实名制
asp.net 控件 开发 显示 控件 内容
奥运 票务 网上 成功 订票 后 应 及时 到 银行 代售 网点 付款
某 心理 健康 站 开张 后 首 个 咨询 者 是 位 新 股民
ASP.NET 自定义 控件 复杂 属性 声明 持久性 浅析


ITokeniser.cs

[csharp]  view plain  copy
  1. using System.Collections.Generic;  
  2.   
  3. namespace WawaSoft.Search.Common  
  4. {  
  5.     /// <summary>  
  6.     /// 分词器接口  
  7.     /// </summary>  
  8.     public interface ITokeniser  
  9.     {  
  10.         IList<string> Partition(string input);  
  11.     }  
  12. }  

StopWordsHandler.cs

[csharp]  view plain  copy
  1. using System;  
  2. using System.Collections;  
  3.   
  4. namespace WawaSoft.Search.Common  
  5. {  
  6.   
  7.     /// <summary>  
  8.     /// 用于移除停止词  
  9.     /// </summary>  
  10.     public class StopWordsHandler  
  11.     {         
  12.         public static string[] stopWordsList=new string[] {"的",  
  13.             "我们","要","自己","之","将","“","”",",","(",")","后","应","到","某","后",  
  14.             "个","是","位","新","一","两","在","中","或","有","更","好"  
  15.         } ;  
  16.   
  17.         private static readonly Hashtable _stopwords=null;  
  18.   
  19.         public static object AddElement(IDictionary collection,Object key, object newValue)  
  20.         {  
  21.             object element = collection[key];  
  22.             collection[key] = newValue;  
  23.             return element;  
  24.         }  
  25.   
  26.         public static bool IsStopword(string str)  
  27.         {  
  28.               
  29.             //int index=Array.BinarySearch(stopWordsList, str)  
  30.             return _stopwords.ContainsKey(str.ToLower());  
  31.         }  
  32.       
  33.   
  34.         static StopWordsHandler()  
  35.         {  
  36.             if (_stopwords == null)  
  37.             {  
  38.                 _stopwords = new Hashtable();  
  39.                 double dummy = 0;  
  40.                 foreach (string word in stopWordsList)  
  41.                 {  
  42.                     AddElement(_stopwords, word, dummy);  
  43.                 }  
  44.             }  
  45.         }  
  46.     }  
  47. }  



TermVector.cs

[csharp]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4.   
  5. namespace WawaSoft.Search.Common  
  6. {  
  7.     public class TermVector  
  8.     {  
  9.         public static double ComputeCosineSimilarity(double[] vector1, double[] vector2)  
  10.         {  
  11.             if (vector1.Length != vector2.Length)  
  12.                 throw new Exception("DIFER LENGTH");  
  13.   
  14.   
  15.             double denom = (VectorLength(vector1) * VectorLength(vector2));  
  16.             if (denom == 0D)  
  17.                 return 0D;  
  18.             else  
  19.                 return (InnerProduct(vector1, vector2) / denom);  
  20.   
  21.         }  
  22.   
  23.         public static double InnerProduct(double[] vector1, double[] vector2)  
  24.         {  
  25.   
  26.             if (vector1.Length != vector2.Length)  
  27.                 throw new Exception("DIFFER LENGTH ARE NOT ALLOWED");  
  28.   
  29.   
  30.             double result = 0D;  
  31.             for (int i = 0; i < vector1.Length; i++)  
  32.                 result += vector1[i] * vector2[i];  
  33.   
  34.             return result;  
  35.         }  
  36.   
  37.         public static double VectorLength(double[] vector)  
  38.         {  
  39.             double sum = 0.0D;  
  40.             for (int i = 0; i < vector.Length; i++)  
  41.                 sum = sum + (vector[i] * vector[i]);  
  42.   
  43.             return (double)Math.Sqrt(sum);  
  44.         }  
  45.   
  46.     }  
  47. }  


TFIDFMeasure.cs

[csharp]  view plain  copy
  1. /* 
  2.  * tf/idf implementation  
  3.  * Author: Thanh Dao, thanh.dao@gmx.net 
  4.  */  
  5. using System;  
  6. using System.Collections;  
  7. using System.Collections.Generic;  
  8. using WawaSoft.Search.Common;  
  9.   
  10.   
  11. namespace WawaSoft.Search.Common  
  12. {  
  13.     /// <summary>  
  14.     /// Summary description for TF_IDFLib.  
  15.     /// </summary>  
  16.     public class TFIDFMeasure  
  17.     {  
  18.         private string[] _docs;  
  19.         private string[][] _ngramDoc;  
  20.         private int _numDocs=0;  
  21.         private int _numTerms=0;  
  22.         private ArrayList _terms;  
  23.         private int[][] _termFreq;  
  24.         private float[][] _termWeight;  
  25.         private int[] _maxTermFreq;  
  26.         private int[] _docFreq;  
  27.   
  28.         ITokeniser _tokenizer = null;  
  29.   
  30.   
  31.   
  32.   
  33.   
  34.         private IDictionary _wordsIndex=new Hashtable() ;  
  35.   
  36.         public TFIDFMeasure(string[] documents,ITokeniser tokeniser)  
  37.         {  
  38.             _docs=documents;  
  39.             _numDocs=documents.Length ;  
  40.             _tokenizer = tokeniser;  
  41.             MyInit();  
  42.         }  
  43.   
  44.         public int NumTerms  
  45.         {  
  46.             get { return _numTerms; }  
  47.             set { _numTerms = value; }  
  48.         }  
  49.   
  50.         private void GeneratNgramText()  
  51.         {  
  52.               
  53.         }  
  54.   
  55.         private ArrayList GenerateTerms(string[] docs)  
  56.         {  
  57.             ArrayList uniques=new ArrayList() ;  
  58.             _ngramDoc=new string[_numDocs][] ;  
  59.             for (int i=0; i < docs.Length ; i++)  
  60.             {  
  61.                 IList<string> words=_tokenizer.Partition(docs[i]);          
  62.   
  63.                 for (int j=0; j < words.Count; j++)  
  64.                     if (!uniques.Contains(words[j]) )                 
  65.                         uniques.Add(words[j]) ;  
  66.                                   
  67.             }  
  68.             return uniques;  
  69.         }  
  70.           
  71.   
  72.   
  73.         private static object AddElement(IDictionary collection, object key, object newValue)  
  74.         {  
  75.             object element=collection[key];  
  76.             collection[key]=newValue;  
  77.             return element;  
  78.         }  
  79.   
  80.         private int GetTermIndex(string term)  
  81.         {  
  82.             object index=_wordsIndex[term];  
  83.             if (index == nullreturn -1;  
  84.             return (int) index;  
  85.         }  
  86.   
  87.         private void MyInit()  
  88.         {  
  89.             _terms=GenerateTerms (_docs );  
  90.             NumTerms=_terms.Count ;  
  91.   
  92.             _maxTermFreq=new int[_numDocs] ;  
  93.             _docFreq=new int[NumTerms] ;  
  94.             _termFreq =new int[NumTerms][] ;  
  95.             _termWeight=new float[NumTerms][] ;  
  96.   
  97.             for(int i=0; i < _terms.Count ; i++)           
  98.             {  
  99.                 _termWeight[i]=new float[_numDocs] ;  
  100.                 _termFreq[i]=new int[_numDocs] ;  
  101.   
  102.                 AddElement(_wordsIndex, _terms[i], i);            
  103.             }  
  104.               
  105.             GenerateTermFrequency ();  
  106.             GenerateTermWeight();             
  107.                   
  108.         }  
  109.           
  110.         private float Log(float num)  
  111.         {  
  112.             return (float) Math.Log(num) ;//log2  
  113.         }  
  114.   
  115.         private void GenerateTermFrequency()  
  116.         {  
  117.             for(int i=0; i < _numDocs  ; i++)  
  118.             {                                 
  119.                 string curDoc=_docs[i];  
  120.                 IDictionary freq=GetWordFrequency(curDoc);  
  121.                 IDictionaryEnumerator enums=freq.GetEnumerator() ;  
  122.                 _maxTermFreq[i]=int.MinValue ;  
  123.                 while (enums.MoveNext())  
  124.                 {  
  125.                     string word=(string)enums.Key;  
  126.                     int wordFreq=(int)enums.Value ;  
  127.                     int termIndex=GetTermIndex(word);  
  128.                     if(termIndex == -1)  
  129.                         continue;  
  130.                     _termFreq [termIndex][i]=wordFreq;  
  131.                     _docFreq[termIndex] ++;  
  132.   
  133.                     if (wordFreq > _maxTermFreq[i]) _maxTermFreq[i]=wordFreq;                      
  134.                 }  
  135.             }  
  136.         }  
  137.           
  138.   
  139.         private void GenerateTermWeight()  
  140.         {             
  141.             for(int i=0; i < NumTerms   ; i++)  
  142.             {  
  143.                 for(int j=0; j < _numDocs ; j++)               
  144.                     _termWeight[i][j]=ComputeTermWeight (i, j);               
  145.             }  
  146.         }  
  147.   
  148.         private float GetTermFrequency(int term, int doc)  
  149.         {             
  150.             int freq=_termFreq [term][doc];  
  151.             int maxfreq=_maxTermFreq[doc];            
  152.               
  153.             return ( (float) freq/(float)maxfreq );  
  154.         }  
  155.   
  156.         private float GetInverseDocumentFrequency(int term)  
  157.         {  
  158.             int df=_docFreq[term];  
  159.             return Log((float) (_numDocs) / (float) df );  
  160.         }  
  161.   
  162.         private float ComputeTermWeight(int term, int doc)  
  163.         {  
  164.             float tf=GetTermFrequency (term, doc);  
  165.             float idf=GetInverseDocumentFrequency(term);  
  166.             return tf * idf;  
  167.         }  
  168.           
  169.         private  float[] GetTermVector(int doc)  
  170.         {  
  171.             float[] w=new float[NumTerms] ;   
  172.             for (int i=0; i < NumTerms; i++)                                           
  173.                 w[i]=_termWeight[i][doc];  
  174.               
  175.                   
  176.             return w;  
  177.         }  
  178.         public double [] GetTermVector2(int doc)  
  179.         {  
  180.             double [] ret = new double[NumTerms];  
  181.             float[] w = GetTermVector(doc);  
  182.             for (int i = 0; i < ret.Length; i++ )  
  183.             {  
  184.                 ret[i] = w[i];  
  185.             }  
  186.             return ret;  
  187.         }  
  188.   
  189.         public double GetSimilarity(int doc_i, int doc_j)  
  190.         {  
  191.             double [] vector1=GetTermVector2 (doc_i);  
  192.             double [] vector2=GetTermVector2 (doc_j);  
  193.   
  194.             return TermVector.ComputeCosineSimilarity(vector1, vector2) ;  
  195.   
  196.         }  
  197.           
  198.         private IDictionary GetWordFrequency(string input)  
  199.         {  
  200.             string convertedInput=input.ToLower() ;  
  201.                       
  202.             List<string> temp = new List<string>(_tokenizer.Partition(convertedInput));  
  203.             string[] words= temp.ToArray();       
  204.               
  205.             Array.Sort(words);  
  206.               
  207.             String[] distinctWords=GetDistinctWords(words);  
  208.                           
  209.             IDictionary result=new Hashtable();  
  210.             for (int i=0; i < distinctWords.Length; i++)  
  211.             {  
  212.                 object tmp;  
  213.                 tmp=CountWords(distinctWords[i], words);  
  214.                 result[distinctWords[i]]=tmp;  
  215.                   
  216.             }  
  217.               
  218.             return result;  
  219.         }                 
  220.                   
  221.         private static string[] GetDistinctWords(String[] input)  
  222.         {                 
  223.             if (input == null)            
  224.                 return new string[0];             
  225.             else  
  226.             {  
  227.                 List<string> list = new List<string>();  
  228.                   
  229.                 for (int i=0; i < input.Length; i++)  
  230.                     if (!list.Contains(input[i])) // N-GRAM SIMILARITY?               
  231.                         list.Add(input[i]);  
  232.                   
  233.                 return list.ToArray();  
  234.             }  
  235.         }  
  236.           
  237.   
  238.           
  239.         private int CountWords(string word, string[] words)  
  240.         {  
  241.             int itemIdx=Array.BinarySearch(words, word);  
  242.               
  243.             if (itemIdx > 0)           
  244.                 while (itemIdx > 0 && words[itemIdx].Equals(word))                 
  245.                     itemIdx--;                
  246.                           
  247.             int count=0;  
  248.             while (itemIdx < words.Length && itemIdx >= 0)  
  249.             {  
  250.                 if (words[itemIdx].Equals(word)) count++;                 
  251.                   
  252.                 itemIdx++;  
  253.                 if (itemIdx < words.Length)                
  254.                     if (!words[itemIdx].Equals(word)) break;                      
  255.                   
  256.             }  
  257.               
  258.             return count;  
  259.         }                 
  260.     }  
  261. }  

Tokeniser.cs

[csharp]  view plain  copy
  1. /* 
  2. Tokenization 
  3. Author: Thanh Ngoc Dao - Thanh.dao@gmx.net 
  4. Copyright (c) 2005 by Thanh Ngoc Dao. 
  5. */  
  6.   
  7. using System;  
  8. using System.Collections;  
  9. using System.Collections.Generic;  
  10. using System.Text.RegularExpressions;  
  11. using WawaSoft.Search.Common;  
  12.   
  13.   
  14. namespace WawaSoft.Search.Common  
  15. {  
  16.     /// <summary>  
  17.     /// Summary description for Tokeniser.  
  18.     /// Partition string into SUBwords  
  19.     /// </summary>  
  20.     internal class Tokeniser : ITokeniser  
  21.     {  
  22.   
  23.         /// <summary>  
  24.         /// 以空白字符进行简单分词,并忽略大小写,  
  25.         /// 实际情况中可以用其它中文分词算法  
  26.         /// </summary>  
  27.         /// <param name="input"></param>  
  28.         /// <returns></returns>  
  29.         public IList<string> Partition(string input)  
  30.         {  
  31.             Regex r=new Regex("([ \\t{}():;. \n])");      
  32.             input=input.ToLower() ;  
  33.   
  34.             String [] tokens=r.Split(input);                                      
  35.   
  36.             List<string> filter=new  List<string>() ;  
  37.   
  38.             for (int i=0; i < tokens.Length ; i++)  
  39.             {  
  40.                 MatchCollection mc=r.Matches(tokens[i]);  
  41.                 if (mc.Count <= 0 && tokens[i].Trim().Length > 0                     
  42.                     && !StopWordsHandler.IsStopword (tokens[i]) )                                 
  43.                     filter.Add(tokens[i]) ;  
  44.             }  
  45.               
  46.             return filter.ToArray();  
  47.         }  
  48.   
  49.   
  50.         public Tokeniser()  
  51.         {  
  52.         }  
  53.   
  54.     }  
  55. }  


WawaCluster.cs

[csharp]  view plain  copy
  1. using System.Collections.Generic;  
  2.   
  3. namespace WawaSoft.Search.Common  
  4. {  
  5.     internal class WawaCluster  
  6.     {  
  7.         public WawaCluster(int dataindex,double[] data)  
  8.         {  
  9.             CurrentMembership.Add(dataindex);  
  10.             Mean = data;  
  11.         }  
  12.   
  13.         /// <summary>  
  14.         /// 该聚类的数据成员索引  
  15.         /// </summary>  
  16.         internal List<int> CurrentMembership = new List<int>();  
  17.         /// <summary>  
  18.         /// 该聚类的中心  
  19.         /// </summary>  
  20.         internal double[] Mean;  
  21.         /// <summary>  
  22.         /// 该方法计算聚类对象的均值   
  23.         /// </summary>  
  24.         /// <param name="coordinates"></param>  
  25.         public void UpdateMean(double[][] coordinates)  
  26.         {  
  27.             // 根据 mCurrentMembership 取得原始资料点对象 coord ,该对象是 coordinates 的一个子集;  
  28.             //然后取出该子集的均值;取均值的算法很简单,可以把 coordinates 想象成一个 m*n 的距阵 ,  
  29.             //每个均值就是每个纵向列的取和平均值 , //该值保存在 mCenter 中  
  30.   
  31.             for (int i = 0; i < CurrentMembership.Count; i++)  
  32.             {  
  33.                 double[] coord = coordinates[CurrentMembership[i]];  
  34.                 for (int j = 0; j < coord.Length; j++)  
  35.                 {  
  36.                     Mean[j] += coord[j]; // 得到每个纵向列的和;  
  37.                 }  
  38.                 for (int k = 0; k < Mean.Length; k++)  
  39.                 {  
  40.                     Mean[k] /= coord.Length; // 对每个纵向列取平均值  
  41.                 }  
  42.             }  
  43.         }  
  44.     }  
  45. }  

WawaKMeans.cs

[csharp]  view plain  copy
  1. using System;  
  2.   
  3. namespace WawaSoft.Search.Common  
  4. {  
  5.   
  6.     public class WawaKMeans  
  7.     {  
  8.         /// <summary>  
  9.         /// 数据的数量  
  10.         /// </summary>  
  11.         readonly int _coordCount;  
  12.         /// <summary>  
  13.         /// 原始数据  
  14.         /// </summary>  
  15.         readonly double[][] _coordinates;  
  16.         /// <summary>  
  17.         /// 聚类的数量  
  18.         /// </summary>  
  19.         readonly int _k;  
  20.         /// <summary>  
  21.         /// 聚类  
  22.         /// </summary>  
  23.         private readonly WawaCluster[] _clusters;  
  24.   
  25.         internal WawaCluster[] Clusters  
  26.         {  
  27.             get { return _clusters; }  
  28.         }   
  29.   
  30.         /// <summary>  
  31.         /// 定义一个变量用于记录和跟踪每个资料点属于哪个群聚类  
  32.         /// _clusterAssignments[j]=i;// 表示第 j 个资料点对象属于第 i 个群聚类  
  33.         /// </summary>  
  34.         readonly int[] _clusterAssignments;  
  35.         /// <summary>  
  36.         /// 定义一个变量用于记录和跟踪每个资料点离聚类最近  
  37.         /// </summary>  
  38.         private readonly int[] _nearestCluster;  
  39.         /// <summary>  
  40.         /// 定义一个变量,来表示资料点到中心点的距离,  
  41.         /// 其中—_distanceCache[i][j]表示第i个资料点到第j个群聚对象中心点的距离;  
  42.         /// </summary>  
  43.         private readonly double[,] _distanceCache;  
  44.         /// <summary>  
  45.         /// 用来初始化的随机种子  
  46.         /// </summary>  
  47.         private static readonly Random _rnd = new Random(1);  
  48.   
  49.         public WawaKMeans(double[][] data, int K)  
  50.         {  
  51.             _coordinates = data;  
  52.             _coordCount = data.Length;  
  53.             _k = K;  
  54.             _clusters = new WawaCluster[K];  
  55.             _clusterAssignments = new int[_coordCount];  
  56.             _nearestCluster = new int[_coordCount];  
  57.             _distanceCache = new double[_coordCount,data.Length];  
  58.             InitRandom();  
  59.         }  
  60.   
  61.         public void Start()  
  62.         {  
  63.             int iter = 0;  
  64.             while (true)  
  65.             {  
  66.                 Console.WriteLine("Iteration " + (iter++) + "...");  
  67.                 //1、重新计算每个聚类的均值  
  68.                 for (int i = 0; i < _k; i++)  
  69.                 {  
  70.                     _clusters[i].UpdateMean(_coordinates);  
  71.                 }  
  72.   
  73.                 //2、计算每个数据和每个聚类中心的距离  
  74.                 for (int i = 0; i < _coordCount; i++)  
  75.                 {  
  76.                     for (int j = 0; j < _k; j++)  
  77.                     {  
  78.                         double dist = getDistance(_coordinates[i], _clusters[j].Mean);  
  79.                         _distanceCache[i,j] = dist;  
  80.                     }  
  81.                 }  
  82.   
  83.                 //3、计算每个数据离哪个聚类最近  
  84.                 for (int i = 0; i < _coordCount; i++)  
  85.                 {  
  86.                     _nearestCluster[i] = nearestCluster(i);  
  87.                 }  
  88.   
  89.                 //4、比较每个数据最近的聚类是否就是它所属的聚类  
  90.                 //如果全相等表示所有的点已经是最佳距离了,直接返回;  
  91.                 int k = 0;  
  92.                 for (int i = 0; i < _coordCount; i++)  
  93.                 {  
  94.                     if (_nearestCluster[i] == _clusterAssignments[i])  
  95.                         k++;  
  96.   
  97.                 }  
  98.                 if (k == _coordCount)  
  99.                     break;  
  100.   
  101.                 //5、否则需要重新调整资料点和群聚类的关系,调整完毕后再重新开始循环;  
  102.                 //需要修改每个聚类的成员和表示某个数据属于哪个聚类的变量  
  103.                 for (int j = 0; j < _k; j++)  
  104.                 {  
  105.                     _clusters[j].CurrentMembership.Clear();  
  106.                 }  
  107.                 for (int i = 0; i < _coordCount; i++)  
  108.                 {  
  109.                     _clusters[_nearestCluster[i]].CurrentMembership.Add(i);  
  110.                     _clusterAssignments[i] = _nearestCluster[i];  
  111.                 }  
  112.                   
  113.             }  
  114.   
  115.         }  
  116.   
  117.         /// <summary>  
  118.         /// 计算某个数据离哪个聚类最近  
  119.         /// </summary>  
  120.         /// <param name="ndx"></param>  
  121.         /// <returns></returns>  
  122.         int nearestCluster(int ndx)  
  123.         {  
  124.             int nearest = -1;  
  125.             double min = Double.MaxValue;  
  126.             for (int c = 0; c < _k; c++)  
  127.             {  
  128.                 double d = _distanceCache[ndx,c];  
  129.                 if (d < min)  
  130.                 {  
  131.                     min = d;  
  132.                     nearest = c;  
  133.                 }  
  134.             
  135.             }  
  136.             if(nearest==-1)  
  137.             {  
  138.                 ;  
  139.             }  
  140.             return nearest;  
  141.         }  
  142.         /// <summary>  
  143.         /// 计算某数据离某聚类中心的距离  
  144.         /// </summary>  
  145.         /// <param name="coord"></param>  
  146.         /// <param name="center"></param>  
  147.         /// <returns></returns>  
  148.         static double getDistance(double[] coord, double[] center)  
  149.         {  
  150.             //int len = coord.Length;  
  151.             //double sumSquared = 0.0;  
  152.             //for (int i = 0; i < len; i++)  
  153.             //{  
  154.             //    double v = coord[i] - center[i];  
  155.             //    sumSquared += v * v; //平方差  
  156.             //}  
  157.             //return Math.Sqrt(sumSquared);  
  158.   
  159.             //也可以用余弦夹角来计算某数据离某聚类中心的距离  
  160.             return 1- TermVector.ComputeCosineSimilarity(coord, center);  
  161.   
  162.         }   
  163.         /// <summary>  
  164.         /// 随机初始化k个聚类  
  165.         /// </summary>  
  166.         private void InitRandom()  
  167.         {  
  168.             for (int i = 0; i < _k; i++)  
  169.             {  
  170.                 int temp = _rnd.Next(_coordCount);  
  171.                 _clusterAssignments[temp] = i; //记录第temp个资料属于第i个聚类  
  172.                 _clusters[i] = new WawaCluster(temp,_coordinates[temp]);  
  173.             }  
  174.         }  
  175.     }  
  176. }  


3.点的聚类:


例子如下:

使用你所学到的k均值聚类算法分别按照欧拉距离(平面直角坐标系里的两点间距离公式)和曼哈顿距离(两个点上在标准坐标系上的绝对轴距总和,将下面的点分成三类:

 

坐标X

坐标Y

1

0

0

2

2

3

3

4

2

4

0

6

5

14

             3

6

13

5

7

3

10

8

4

11

9

6

9

10

8

10

11

12

6

12

17

3

13

14

6

14

7

9

15

9

12

 

 

基于欧拉距离的程序代码(C语言)

[plain]  view plain  copy
  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #define N 15  
  4. #define k 3  
  5.    
  6. int min(float d[k])                                                 
  7. {  
  8.       inti=0;                                                  /*定义最短距离下标*/  
  9.       if(d[1]<d[i])  
  10.            i=1;  
  11.       if(d[2]<d[i])  
  12.            i=2;  
  13.       returni;                                                /*返回最短距离下标*/  
  14. }  
  15.    
  16. int main()  
  17. {  
  18.       floata[N][2]={{0,0},{2,3},{4,2},{0,6},{14,3},  
  19.            {13,5},{3,10},{4,11},{6,9},{8,10},{12,6},  
  20.            {17,3},{14,6},{7,9},{9,12}};             /*N个点,坐标*/  
  21.    
  22.    
  23.       inti,j,m;                                                      
  24.    
  25.       inticounter[k],n=0;           /*各簇元素个数,聚类次数*/  
  26.    
  27.       floatc[k][2];                                                      /*聚类中心*/ float c1[k][2];                                                    /*新聚类中心*/  
  28.       floats[k][2];                                              /*各簇元素坐标和*/  
  29.        
  30.       floatd[k];                                                              /*距离*/  
  31.    
  32.       intitype;                                                          /*元素所在的簇*/  
  33.       floattype[k][N][2];       /*初始化,K簇,每簇含N个元素*/  
  34.    
  35.    
  36.       for(j=0;j<k;j++)  
  37.       {  
  38.            c1[j][0]=a[j][0];                             /*初始化聚类中心*/  
  39.            c1[j][1]=a[j][1];                                          
  40.       }  
  41.    
  42.       do  
  43.       {  
  44.            n++;  
  45.     for(i=0;i<k;i++)  
  46.            {  
  47.                  icounter[i]=0;                      /*每次聚类计数器归零*/         
  48.                  for(m=0;m<2;m++)  
  49.                  {  
  50.            s[i][m]=0;                    /*各簇元素坐标和归零*/  
  51.                         c[i][m]=c1[i][m];           
  52. /*新聚类中心赋值给原聚类中心*/  
  53.                  }  
  54.            }  
  55.        
  56.            for(i=0;i<N;i++)                                        /*遍历数组*/  
  57.            {  
  58.                  for(j=0;j<k;j++)  
  59.                       d[j]=fabs(a[i][0]-c[j][0])+fabs(a[i][1]-c[j][1]);   
  60. /*欧拉距离*/  
  61.                   
  62.                  itype=min(d);                                  /*调用min函数*/  
  63.                  for(m=0;m<2;m++)  
  64.                  {  
  65.                       type[itype][icounter[itype]][m]=a[i][m];                   
  66.                       s[itype][m]+=a[i][m];  
  67.                  }  
  68.    
  69.                  icounter[itype]++;                     
  70.            }  
  71.    
  72.            for(i=0;i<k;i++)  
  73.            {     
  74.                  c1[i][0]=s[i][0]/icounter[i];                 /*新聚类中心*/  
  75.                  c1[i][1]=s[i][1]/icounter[i];  
  76.            }  
  77. /*输出每次聚类得到的结果*/  
  78.            printf("第%d次基于欧拉距离聚类结果:\n",n);          
  79.            for(j=0;j<k;j++)  
  80.            {  
  81.                  printf("聚类中心(%f,%f):\t",c[j][0],c[j][1]);  
  82.    
  83.                  for(i=0;i<icounter[j];i++)  
  84.                  {  
  85.                       printf("(%.f,%.f)",type[j][i][0],type[j][i][1]);  
  86.                  }  
  87.                  printf("\n");  
  88.            }  
  89.            printf("\n");  
  90.    
  91.       }while((fabs(c1[0][0]-c[0][0])>1e-5) ||  
  92.             (fabs(c1[1][0]-c[1][0])>1e-5) ||  
  93.            (fabs(c1[2][0]-c[2][0])>1e-5));                      
  94. /*聚类结果收敛时跳出循环*/  
  95.    
  96. /*打印最终聚类结果*/  
  97.       printf("\n基于欧拉距离%d次聚类后结果收敛,最终聚类结果:\n",n);  
  98.       for(j=0;j<k;j++)                                    
  99.       {  
  100.            printf("聚类中心(%.2f,%.2f):\t",c1[j][0],c1[j][1]);  
  101.            for(i=0;i<icounter[j];i++)  
  102.            {  
  103.                  printf("(%.f,%.f)",type[j][i][0],type[j][i][1]);  
  104.            }  
  105.            printf("\n");  
  106.       }  
  107.    
  108.       return0;  
  109. }  
  110.    


 

运行结果

基于欧拉距离

 

 


聚类中心

元素

( 1.5,  2.75)

(0,0)   (2,3)   (4,2)   (0,6)

( 6.17, 10.17)

(3,10)  (4,11)  (6,9)   (7,9)   (9,12)

( 14,   4.6)

(14,3)  (13,5)  (12,6)  (17,3)  (14,6)

 

基于曼哈顿距离

 

聚类中心

元素

( 1.5,  2.75)

(0,0)   (2,3)   (4,2)   (0,6)

( 6.17, 10.17)

(3,10)  (4,11)  (6,9)   (7,9)   (9,12)

( 14,   4.6)

(14,3)  (13,5)  (12,6)  (17,3)  (14,6)

 





c#的例子代码:

[csharp]  view plain  copy
  1. k均值算法是模式识别的聚分类问题,这是用C#实现其算法  
  2. 以下是程序源代码:  
  3. using System;  
  4. using System.Drawing;  
  5. using System.Collections;  
  6. using System.ComponentModel;  
  7. using System.Windows.Forms;  
  8. using System.Data;  
  9. namespace KMean_win  
  10. {  
  11.      ///   
  12.      /// Form1 的摘要说明。  
  13.      ///   
  14.      public class Form1 : System.Windows.Forms.Form  
  15.      {  
  16.          ///   
  17.          /// 必需的设计器变量。  
  18.          ///   
  19.          private System.ComponentModel.Container components = null;  
  20.          private static int k = 2;                          //类数,此例题为2类  
  21.          private static int total = 20;                      //点个数  
  22.          private int test = 0;  
  23.          private PointF[] unknown = new PointF[total];  //点数组  
  24.          private int[] type = new int[total];           //每个点暂时的类  
  25.          public PointF[] z = new PointF[k];                 //保存新的聚类中心  
  26.          public PointF[] z0 = new PointF[k];                //保存上一次的聚类中心  
  27.          private PointF sum;  
  28.          private int temp = 0;  
  29.          private System.Windows.Forms.TextBox textBox1;  
  30.          private int l = 0;          //迭代次数  
  31. //构造函数,初始化  
  32.          public Form1()  
  33.          {  
  34.               unknown[0]=new Point(0,0);  
  35.               unknown[1]=new Point(1,0);  
  36.               unknown[2]=new Point(0,1);  
  37.               unknown[3]=new Point(1,1);  
  38.               unknown[4]=new Point(2,1);  
  39.               unknown[5]=new Point(1,2);  
  40.               unknown[6]=new Point(2,2);  
  41.               unknown[7]=new Point(3,2);  
  42.               unknown[8]=new Point(6,6);  
  43.               unknown[9]=new Point(7,6);  
  44.               unknown[10]=new Point(8,6);  
  45.               unknown[11]=new Point(6,7);  
  46.               unknown[12]=new Point(7,7);  
  47.               unknown[13]=new Point(8,7);  
  48.               unknown[14]=new Point(9,7);  
  49.               unknown[15]=new Point(7,8);  
  50.               unknown[16]=new Point(8,8);  
  51.               unknown[17]=new Point(9,8);  
  52.               unknown[18]=new Point(8,9);  
  53.               unknown[19]=new Point(9,9);  
  54.                 
  55.               InitializeComponent();  
  56.                 
  57.               test = 0;  
  58.               //选k个初始聚类中心    z[i]       
  59.               for(int i=0;i                   z[i] = unknown[i];  
  60.               for(int i=0;i                   type[i] = 0;  
  61.          }  
  62. //计算新的聚类中心  
  63.          public PointF newCenter(int m)  
  64.          {  
  65.               int N = 0;  
  66.               for(int i=0;i              {  
  67.                    if(type[i] == m)  
  68.                    {  
  69.                        sum.X = unknown[i].X+sum.X;  
  70.                        sum.Y = unknown[i].Y+sum.Y;  
  71.                        N += 1;  
  72.                    }  
  73.               }  
  74.               sum.X=sum.X/N;  
  75.               sum.Y=sum.Y/N;  
  76.               return sum;  
  77.          }  
  78. //比较两个聚类中心的是否相等  
  79.          private bool compare(PointF a,PointF b)  
  80.          {  
  81.               if(((int)(a.X*10) == (int)(b.X*10)) && ((int)(a.X*10) == (int)(b.X*10)))  
  82.                    return true;  
  83.               else  
  84.                    return false;  
  85.          }  
  86. //进行迭代,对total个样本根据聚类中心进行分类  
  87.          private void order()  
  88.          {  
  89.               int temp = 0;//记录unknown[i]暂时在哪个类中  
  90.               for(int i=0;i              {  
  91.                    for(int j=0;j                   {  
  92.                        if(distance(unknown[i],z[temp]) > distance(unknown[i],z[j]))  
  93.                             temp = j;  
  94.                    }  
  95.                    type[i] = temp;  
  96.                    Console.WriteLine("经比较后,{0}归为{1}类",unknown[i],temp);  
  97.               }  
  98.          }  
  99. //计算两个点的欧式距离  
  100.          private float distance(PointF p1,PointF p2)  
  101.          {  
  102.               return((p1.X-p2.X)*(p1.X-p2.X)+ (p1.Y-p2.Y)*(p1.Y-p2.Y));  
  103.          }  
  104.          ///   
  105.          /// 清理所有正在使用的资源。  
  106.          ///   
  107.          protected override void Dispose( bool disposing )  
  108.          {  
  109.               if( disposing )  
  110.               {  
  111.                    if (components != null)   
  112.                    {  
  113.                        components.Dispose();  
  114.                    }  
  115.               }  
  116.               base.Dispose( disposing );  
  117.          }  
  118. //程序结构  
  119.          public void main()  
  120.          {  
  121.               Console.WriteLine("共有如下个未知样本:");  
  122.               for(int i=0;i              {  
  123.                    Console.WriteLine(unknown[i]);  
  124.               }  
  125. /*            for(int i=0;i                  Console.WriteLine("初始时,第{0}类中心{1}",i,z[i]); 
  126.               order(); 
  127.               for(int i=0;i              { 
  128.                    z[i] = newCenter(i); 
  129.                    Console.WriteLine("第{0}类新中心{1}",i,z[i]); 
  130.                    if(z[i].Equals(z0[i]) ) 
  131.                        test = test+1; 
  132.                    else 
  133.                        z0[i] = z[i]; 
  134.               } 
  135. */            for(int i=0;i                  Console.WriteLine("初始时,第{0}类中心{1}",i,z[i]);   
  136.               while( test!=k )  
  137.               {  
  138.                    order();  
  139.                    for(int i=0;i                   {  
  140.                        z[i] = newCenter(i);  
  141.                        Console.WriteLine("第{0}类新中心{1}",i,z[i]);  
  142.                        if(compare(z[i],z0[i]))  
  143.                             test = test+1;  
  144.                        else  
  145.                             z0[i] = z[i];  
  146.                    }  
  147.                    l = l+1;  
  148.                    Console.WriteLine("******已完成第{0}次迭代*******",l);  
  149.                      
  150.               Console.Write("{0}","分类后:");  
  151.               for(int j=0;j              {  
  152.                    Console.Write("第{0}类有:",j);  
  153.                    for(int i=0;i                   {  
  154.                        if(type[i] == j)  
  155.                             Console.WriteLine("{0},{1}",unknown[i].X,unknown[i].Y);  
  156.                    }  
  157.               }  
  158.               }  
  159.                 
  160.      }  
  161.          #region Windows 窗体设计器生成的代码  
  162.          ///   
  163.          /// 设计器支持所需的方法 - 不要使用代码编辑器修改  
  164.          /// 此方法的内容。  
  165.          ///   
  166.          private void InitializeComponent()  
  167.          {  
  168.               this.textBox1 = new System.Windows.Forms.TextBox();  
  169.               this.SuspendLayout();  
  170.               //   
  171.               // textBox1  
  172.               //   
  173.               this.textBox1.Location = new System.Drawing.Point(0, 0);  
  174.               this.textBox1.Multiline = true;  
  175.               this.textBox1.Name = "textBox1";  
  176.               this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;  
  177.               this.textBox1.Size = new System.Drawing.Size(296, 272);  
  178.               this.textBox1.TabIndex = 0;  
  179.               this.textBox1.Text = "";  
  180.               //   
  181.               // Form1  
  182.               //   
  183.               this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);  
  184.               this.ClientSize = new System.Drawing.Size(292, 271);  
  185.               this.Controls.Add(this.textBox1);  
  186.               this.Name = "Form1";  
  187.               this.Text = "Form1";  
  188.               this.ResumeLayout(false);  
  189.          }  
  190.          #endregion  
  191.      }  
  192.      class entrance  
  193.      {        ///   
  194.          /// 应用程序的主入口点。  
  195.          ///   
  196.          [STAThread]  
  197.          static void Main()   
  198.          {               
  199.               Form1 my = new Form1();  
  200.               my.main();  
  201.               Application.Run(new Form1());  
  202.          }  
  203.      }  
  204. }   
转载地址



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值