Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GaussianProcessTuning/ILNumerics.2.14.4735.573/Algorithms/MachineLearning/kmeansclustLoopUnroll.cs @ 11826

Last change on this file since 11826 was 9102, checked in by gkronber, 12 years ago

#1967: ILNumerics source for experimentation

File size: 11.3 KB
Line 
1///
2///    This file is part of ILNumerics Community Edition.
3///
4///    ILNumerics Community Edition - high performance computing for applications.
5///    Copyright (C) 2006 - 2012 Haymo Kutschbach, http://ilnumerics.net
6///
7///    ILNumerics Community Edition is free software: you can redistribute it and/or modify
8///    it under the terms of the GNU General Public License version 3 as published by
9///    the Free Software Foundation.
10///
11///    ILNumerics Community Edition is distributed in the hope that it will be useful,
12///    but WITHOUT ANY WARRANTY; without even the implied warranty of
13///    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14///    GNU General Public License for more details.
15///
16///    You should have received a copy of the GNU General Public License
17///    along with ILNumerics Community Edition. See the file License.txt in the root
18///    of your distribution package. If not, see <http://www.gnu.org/licenses/>.
19///
20///    In addition this software uses the following components and/or licenses:
21///
22///    =================================================================================
23///    The Open Toolkit Library License
24///   
25///    Copyright (c) 2006 - 2009 the Open Toolkit library.
26///   
27///    Permission is hereby granted, free of charge, to any person obtaining a copy
28///    of this software and associated documentation files (the "Software"), to deal
29///    in the Software without restriction, including without limitation the rights to
30///    use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
31///    the Software, and to permit persons to whom the Software is furnished to do
32///    so, subject to the following conditions:
33///
34///    The above copyright notice and this permission notice shall be included in all
35///    copies or substantial portions of the Software.
36///
37///    =================================================================================
38///   
39
40using System;
41using System.Collections.Generic;
42using System.Text;
43using ILNumerics.Exceptions;
44
45namespace ILNumerics {
46   
47   
48    public partial class ILMath {
49
50        /// <summary>
51        /// find clusters for data matrix X
52        /// </summary>
53        /// <param name="X">data matrix, data points are given as columns</param>
54        /// <param name="k">initial number of clusters expected</param>
55        /// <param name="centerInitRandom">false: pick the first k data points as initial centers, true: pick random datapoints</param>
56        /// <param name="maxIterations">maximum number of iterations, the computation will exit after that many iterations.</param>
57        /// <returns>vector of length n with with indices of clusters assigned to each datapoint</returns>
58        public static ILRetArray<double> kMeansClust(ILInArray<double> X, ILBaseArray k, int maxIterations, bool centerInitRandom) {
59            return kMeansClust(X, k, maxIterations, centerInitRandom, null);
60        }
61
62        /// <summary>
63        /// find clusters for data matrix X
64        /// </summary>
65        /// <param name="X">data matrix, data points are given as columns</param>
66        /// <param name="k">initial number of clusters expected</param>
67        /// <param name="centerInitRandom">false: pick the first k data points as initial centers, true: pick random datapoints</param>
68        /// <param name="maxIterations">maximum number of iterations, the computation will exit after that many iterations.</param>
69        /// <param name="outCenters">return type. if assigned on entry, outCenters will contain the centers of the clusters found.</param>
70        /// <returns>vector of length n with with indices of clusters assigned to each datapoint</returns>
71        public static ILRetArray<double> kMeansClust (ILInArray<double> X, ILBaseArray k, int maxIterations, bool centerInitRandom, ILOutArray<double> outCenters) {
72            using (ILScope.Enter(X, k)) {
73                if (object.Equals(X,null)) {
74                    throw new ILArgumentException("X must be data matrix (not null)");
75                }
76                if (X.IsEmpty) {
77                    if (!object.Equals(outCenters, null)) {
78                        if (X.D[0] > 0) {
79                            outCenters.a = empty<double>(new ILSize(X.D[0], 0));
80                        } else {
81                            outCenters.a = empty<double>(new ILSize(0, X.D[1]));
82                        }
83                        return empty<double>(X.D);
84                    }
85                }
86                if (object.Equals(k,null) || !k.IsScalar || !k.IsNumeric) {
87                    throw new ILArgumentException("number of clusters k must be numeric scalar");
88                }
89                int iK = toint32(k).GetValue(0);
90                if (X.D[1] < iK) {
91                    throw new ILArgumentException("too few datapoints provided for " + iK.ToString() + " clusters");
92                }
93                if (iK < 0) {
94                    throw new ILArgumentException("number of clusters must be positive");
95                }
96                int d = X.D[0], n = X.D[1];
97                if (iK == 0) {
98                    if (!object.Equals(outCenters, null)) {
99                        outCenters.a = empty<double>(new ILSize(d, iK));
100                    }
101                    return empty<double>(new ILSize(0, n));
102                }
103
104                // initialize centers by using random datapoints
105                ILArray<double> centers = empty();
106                if (centerInitRandom) {
107                    ILArray<double> pickIndices = empty();
108                    sort(rand(1,n),pickIndices,1,false).Dispose();
109                    centers.a = X[full,pickIndices[r(0,iK-1)]];
110                } else {
111                    centers.a = X[full,r(0,iK-1)];
112                }
113
114                ILArray<double> classes = zeros(1,n);
115                ILArray<double> oldCenters = centers.C;
116#if KMEANSVERBOSE
117                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
118#endif
119                while (maxIterations --> 0) {
120#if KMEANSVERBOSE
121                    sw.Restart();
122#endif
123                    //ILArray<double> distances = zeros(1, iK);
124
125                    double[] Xarr = X.GetArrayForRead();
126                    double[] Carr = classes.GetArrayForWrite();
127                    double[] CentArr = centers.GetArrayForRead();
128                    double[] Xcur = ILMemoryPool.Pool.New<double>(X.D[0]);
129
130                    for (int i = 0; i < n; i++) {
131                        // copy current X[i]
132                        int startInd = i * X.D[0];
133                        for (int a = X.D[0]; a --> 0; ) {
134                            Xcur[a] = Xarr[startInd + a];
135                        }
136                        // distances to all centers
137                        double dist = double.MaxValue;
138                        for (int c = 0; c < iK; c++) {
139                            double tmp = 0, tmp1 = 0;
140                            startInd = c * X.D[0];
141                            for (int c1 = X.D[0]; c1-->0; ) {
142                                tmp = CentArr[c1 + startInd] -  Xcur[c1];
143                                tmp1 += tmp * tmp;
144                            }
145                            if (tmp1 < dist) {
146                                dist = tmp1;
147                                Carr[i] = c;
148                                if (dist == 0)
149                                    break;
150                            }
151                        }
152                    }
153                    ILMemoryPool.Pool.RegisterObject(Xcur);
154
155                        // find cluster affiliates
156                        //using (ILScope.Enter()) {
157
158                            ////  - for testing a more "similar 2 Fortran" implementation:
159                            //ILArray<double> tmpX = X[full, i];
160                            //for (int j = 0; j < iK; j++) {
161                            //    using (ILScope.Enter()) {
162
163                            //        //! ... find its nearest cluster
164                            //        //do j = 1, K
165                            //        //    distances(j) = sum(                                &
166                            //        //                        abs(                           &
167                            //        //                            X(1:M,i) - centers(1:M,j)))
168                            //        //end do
169
170                            //        //tmpArr = minloc ( distances(1:K) )
171                            //        //classes(i) = tmpArr(1);
172
173                            //        distances[j] = sum(abs(tmpX - centers[full, j]));
174                            //    }
175                            //}
176                            //ILArray<double> minDistIdx = empty();
177                            //min(distances, minDistIdx, 1).Dispose();
178                            //int found = (int)minDistIdx[0];
179                            //classes[i] = found;
180
181                            //ILArray<double> minDistIdx = empty();
182                            //min(sum(apply((a, b) => { return Math.Abs(a - b); }, centers, repmat(X[full, i], 1, iK))), minDistIdx, 1).Dispose();
183                            //int found = (int)minDistIdx[0];
184                            //classes[i] = found;
185
186
187
188                            //ILArray<double> minDistIdx = empty();
189                            //min(sum(abs(centers - repmat(X[full, i], 1, iK))), minDistIdx, 1).Dispose();
190                            //int found = (int)minDistIdx[0];
191                            //classes[i] = found;
192                           
193                            //numInClass[found] = numInClass[found] + 1;
194                        //}
195                    //}
196                    System.Diagnostics.Debug.Print("kmeans: 1 of {0} MemoryPool.Info: {1}",maxIterations, ILMemoryPool.Pool.Info(true));
197                    // update centroids
198                    //centers[full] = 0;
199                    //for (int i = 0; i < n; i++) {
200                    //    centers[full,classes[i]] = centers[full,classes[i]] + X[full,i];
201                    //}
202                    //numInClass[numInClass == 0] = double.NaN;
203                    //centers = centers / repmat(numInClass,d,1);
204
205                    for (int i = 0; i < iK; i++) {
206                        using (EnterScope()) {
207                            ILArray<double> inClass = X[full, find(classes == i)];
208                            if (inClass.IsEmpty) {
209                                centers[full, i] = double.NaN;
210                            } else {
211                                centers[full, i] = mean(inClass, 1);
212                            }
213                        }
214                    }
215#if KMEANSVERBOSE
216                    sw.Stop();
217                    Console.Out.WriteLine("Changed centers: {0} elapsed: {1}ms",(double)sum(any(oldCenters != centers)), sw.ElapsedMilliseconds);
218#endif
219                    if (allall(oldCenters == centers)) break;
220                    oldCenters.a = centers.C;
221                }
222                if (!object.Equals(outCenters, null))
223                    outCenters.a = centers;
224                return classes;
225            }
226        }
227
228    }
229}
Note: See TracBrowser for help on using the repository browser.