-
Notifications
You must be signed in to change notification settings - Fork 2
/
KmeansCluster.cs
214 lines (189 loc) · 6.98 KB
/
KmeansCluster.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
/*C#下的kmeans实现,主要处理行数比较多的数据,所以采用float省内存,而不是用double;
*代码思路主要来自《机器学习实战》
*
*
**/
namespace KMeansClusterInCS {
class KmeansCluster {
int _N; //聚类数据的维数例如[lng,lat]是二维
int _K; //聚类中心个数,kmeans中的k
private float[][] _centroids; //质心集合
private float[][] _ctsCopy; //质心的一份拷贝
private bool cv = false; //质心不改变时(目前采用逻辑0而不是==)
private List<float[]> allDlst = new List<float[]>();//为省内存不用double
public KmeansCluster () {
_N = 2;
_K = 3;
}
public KmeansCluster (int n, int k) {
_N = n;
_K = k;
}
public N{
get{ return _N;
}
}
#region 公共调用部分
//一键式调用
public void toCluster () {
List<float[]> allTwo = cluster();
listFloatToCsv(allTwo);
}
public void listFloatToCsv (List<float[]> allT) {
string spath = @"D:/python_works/testSet4_out.csv";
StreamWriter swt = new StreamWriter(spath);
foreach (float[] a in allT) {
string outxt = FloatLstToStr(a);
swt.WriteLine(outxt);
}
swt.Close();
}
#endregion
#region 私有函数
public void loadData (string filenm) {
//目前只针对二维的,想改进,之后再说吧
StreamReader csvRder = new StreamReader(filenm);
string csvall = csvRder.ReadToEnd();
string[] csvlst = csvall.Split('\n');
foreach (string c in csvlst) {
string[] curLine = c.Split(',');
if (curLine.Length == 2) {
float[] cline = new float[] {0f,0f,0f };
cline[0] =Convert.ToSingle( curLine[0]);
cline[1] = Convert.ToSingle(curLine[1]);
allDlst.Add(cline);
}
else {
Console.WriteLine(curLine.Length);
}
}
}
public float distEclud (float[] va, float[] vb) {
//要求va vb里面元素个数相等
if (va.Length != vb.Length) {
throw new FormatException("va.Length 需要等于 vb.Length");
}
double sc = 0;
for(int i = 0; i < va.Length; i++) {
sc = sc + Math.Pow((va[i] - vb[i]), 2);
}
return (float)Math.Sqrt(sc);
}
public float[][] rand_center (List<float[]> data, int k) {
//输出为k*n的矩阵;也可以用List<float[]>装,n指原先维数,默认为2
int n = data[0].Length;
float[][] centroids = new float[k][]; //这里填k而不是填n没问题
for (int q = 0; q < k; q++) {
centroids[q] = new float[] { 0, 0, 0 };
}
for (int i = 0; i < n; i++) {
float _max = data[0][i];//or float.MinValue;//
float _min= data[0][i];//循环一次可以获得最大最小值
for(int j = 1; j < data.Count; j++) {
if (data[j][i] > _max) {
_max = data[j][i];
}
if (data[j][i] < _min) {
_min = data[j][i];
}
}
for (int q = 0; q < k; q++) {
var seed = Guid.NewGuid().GetHashCode();
Random ran = new Random(seed);//必须设置随机数种子,否则centroids相同
float rfloat = (float)ran.NextDouble();
centroids[q][i] =_min+(_max - _min)*rfloat;
}
}
return centroids;
}
public bool converged (float[][] c1, float[][] c2) {
//centroids not changed -> true
for (int j = 0; j < c1.Length; j++) { //k
for (int i = 0; i < c1[0].Length; i++) {// n
double a2 = Math.Abs(c1[j][i] - c2[j][i]);//这一句之后去优化
if (a2>0.0001) {
return false;
}
}
}
return true;
}
/// <summary>
/// 更新质心
/// </summary>
/// <returns></returns>
private void updateCentroids () {
for (int i = 0; i < _K; i++) {
}
}
private float meanByAxis2 (int axis,float typec) {
double msun = 0;
int mc = 0;
foreach(float[] a in allDlst) {
if (a[_N - 1] == typec) {
msun = msun + a[axis];//这里特别怕溢出
mc += 1;
}
}
return (float) msun /mc;
}
private float meanByAxis (int axis, float typec) {
double mavg = 0;
int mc = 0;
foreach (float[] a in allDlst) {
if (a[_N - 1] == typec) {
mc += 1;
mavg = mavg + (a[axis]-mavg)/mc;//
}
}
return (float) mavg;
}
private float[] meanAll (float typec) {
float[] newCts = new float[_N];
for (int j = 0; j < _N; j++) {
newCts[j] = meanByAxis(j, typec);
}
return newCts;
}
public List<float[]> cluster () {
string fn = "D:/python_works/testSet3.csv";
loadData(fn);
_centroids = rand_center(allDlst, _K);
int ncount = allDlst.Count;//注意和维度 _N 区分
//目前用不到 assement
while (!cv) {
_ctsCopy = _centroids;
for (int i = 0; i < ncount; i++) {
float minDist = float.MaxValue;
int minIndex = -1;
for (int j = 0; j < _K; j++) {
float dist = distEclud(allDlst[i], _centroids[j]);//注意j索引是否对
if (dist < minDist) {
minDist = dist;
minIndex = j;
allDlst[i][_N] = j;
}
}
}
for (int q = 0; q < _K; q++) { // update centroid
_centroids[q] = meanAll(q);
}
cv = converged(_centroids, _ctsCopy);
}
return allDlst;
}
private string FloatLstToStr (float[] fl) {
string otxt = "";
foreach (float f in fl) {
otxt = otxt + Convert.ToString(f) + ",";
}
return otxt;
}
#endregion
}
}