1 文本格式
using System;
namespace Legalsoft.Truffer
{
/// <summary>
/// K-Means classification
/// </summary>
public class Kmeans
{
private int nn { get; set; }
private int mm { get; set; }
private int kk { get; set; }
private int nchg { get; set; }
private double[,] data { get; set; }
private double[,] means { get; set; }
private int[] assign { get; set; }
private int[] count { get; set; }
public Kmeans(double[,] ddata, double[,] mmeans)
{
this.nn = ddata.GetLength(0);
this.mm = ddata.GetLength(1);
this.kk = mmeans.GetLength(0);
this.data = Globals.CopyFrom(ddata);
this.means = Globals.CopyFrom(mmeans);
this.assign = new int[nn];
this.count = new int[kk];
estep();
mstep();
}
public int estep()
{
int kmin = 0;
nchg = 0;
for (int k = 0; k < kk; k++)
{
count[k] = 0;
}
for (int n = 0; n < nn; n++)
{
double dmin = 9.99e99;
for (int k = 0; k < kk; k++)
{
double d = 0.0;
for (int m = 0; m < mm; m++)
{
d += Globals.SQR(data[n, m] - means[k, m]);
}
if (d < dmin)
{
dmin = d;
kmin = k;
}
}
if (kmin != assign[n])
{
nchg++;
}
assign[n] = kmin;
count[kmin]++;
}
return nchg;
}
public void mstep()
{
for (int k = 0; k < kk; k++)
{
for (int m = 0; m < mm; m++)
{
means[k, m] = 0.0;
}
}
for (int n = 0; n < nn; n++)
{
for (int m = 0; m < mm; m++)
{
means[assign[n], m] += data[n, m];
}
}
for (int k = 0; k < kk; k++)
{
if (count[k] > 0)
{
for (int m = 0; m < mm; m++)
{
means[k, m] /= count[k];
}
}
}
}
}
}
2 代码格式
using System;namespace Legalsoft.Truffer
{/// <summary>/// K-Means classification/// </summary>public class Kmeans{private int nn { get; set; }private int mm { get; set; }private int kk { get; set; }private int nchg { get; set; }private double[,] data { get; set; }private double[,] means { get; set; }private int[] assign { get; set; }private int[] count { get; set; }public Kmeans(double[,] ddata, double[,] mmeans){this.nn = ddata.GetLength(0);this.mm = ddata.GetLength(1);this.kk = mmeans.GetLength(0);this.data = Globals.CopyFrom(ddata);this.means = Globals.CopyFrom(mmeans);this.assign = new int[nn];this.count = new int[kk];estep();mstep();}public int estep(){int kmin = 0;nchg = 0;for (int k = 0; k < kk; k++){count[k] = 0;}for (int n = 0; n < nn; n++){double dmin = 9.99e99;for (int k = 0; k < kk; k++){double d = 0.0;for (int m = 0; m < mm; m++){d += Globals.SQR(data[n, m] - means[k, m]);}if (d < dmin){dmin = d;kmin = k;}}if (kmin != assign[n]){nchg++;}assign[n] = kmin;count[kmin]++;}return nchg;}public void mstep(){for (int k = 0; k < kk; k++){for (int m = 0; m < mm; m++){means[k, m] = 0.0;}}for (int n = 0; n < nn; n++){for (int m = 0; m < mm; m++){means[assign[n], m] += data[n, m];}}for (int k = 0; k < kk; k++){if (count[k] > 0){for (int m = 0; m < mm; m++){means[k, m] /= count[k];}}}}}
}