Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GaussianProcessTuning/ILNumerics.2.14.4735.573/Algorithms/MachineLearning/kmeansclustMT.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: 10.7 KB
RevLine 
[9102]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.Threading;
43using System.Text;
44using ILNumerics.Exceptions;
45
46namespace ILNumerics {
47   
48   
49    public partial class ILMath {
50
51        /// <summary>
52        /// find clusters for data matrix X
53        /// </summary>
54        /// <param name="X">data matrix, data points are given as columns</param>
55        /// <param name="k">initial number of clusters expected</param>
56        /// <param name="centerInitRandom">false: pick the first k data points as initial centers, true: pick random datapoints</param>
57        /// <param name="maxIterations">maximum number of iterations, the computation will exit after that many iterations.</param>
58        /// <returns>vector of length n with with indices of clusters assigned to each datapoint</returns>
59        public static ILRetArray<double> kMeansClustMT(ILInArray<double> X, ILBaseArray k, int maxIterations, bool centerInitRandom) {
60            return kMeansClustMT(X, k, maxIterations, centerInitRandom, null);
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> kMeansClustMT (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                int maxNTSetting = Settings.MaxNumberThreads, workerCount = 1, workItemLen = 0;
120                int workItemCount = maxNTSetting;
121                int wi = 0;
122                Settings.MaxNumberThreads = 1;
123                Action<object> loopOverN = data => {
124                        Tuple<ILInArray<double>, ILInArray<double>, ILOutArray<double>> rng
125                            = (Tuple<ILInArray<double>, ILInArray<double>, ILOutArray<double>>)data;
126                        try {
127                            using (ILScope.Enter(rng.Item1, rng.Item2)) {
128                                ILArray<double> Xl = rng.Item1;
129                                ILArray<double> centersl = rng.Item2;
130                                for (int i = Xl.D[1]; i-- > 0; ) {
131                                    ILArray<double> minDistIdx = empty();
132                                    min(sum(abs(centersl - repmat(Xl[full, i], 1, iK))), minDistIdx, 1).Dispose();
133                                    rng.Item3[i] = minDistIdx[0];
134                                }
135                            }
136                        } finally {
137                            Interlocked.Decrement(ref workerCount);
138                        }
139                };
140                List<ILArray<double>> classesSplit = new List<ILArray<double>>(workItemCount);
141                List<ILArray<double>> XSplit = new List<ILArray<double>>(workItemCount);
142               
143                while (maxIterations --> 0) {
144#if KMEANSVERBOSE
145                    sw.Restart();
146#endif
147                    workItemLen = n / workItemCount;
148                    workerCount = 1;
149                    for (wi = 0; wi < workItemCount - 1; wi++) {
150                        if (classesSplit.Count <= wi) {
151                            classesSplit.Add(zeros<double>(1,workItemLen));
152                        }
153                        if (XSplit.Count <= wi) {
154                            XSplit.Add(X[full,r(wi * workItemLen, (wi + 1) * workItemLen - 1)]);
155                        }
156                        Tuple<ILInArray<double>, ILInArray<double>, ILOutArray<double>> rng
157                            = new Tuple<ILInArray<double>, ILInArray<double>, ILOutArray<double>>(
158                                XSplit[wi], centers.C, classesSplit[wi]);
159                        Interlocked.Increment(ref workerCount);
160                        ThreadPool.QueueUserWorkItem(new WaitCallback(loopOverN), rng);
161                    }
162                    // loop for main thread
163                    ILArray<double> tmpOutClasses = zeros<double>(1,n - wi * workItemLen);
164                    Tuple<ILInArray<double>, ILInArray<double>, ILOutArray<double>> rngL
165                        = new Tuple<ILInArray<double>, ILInArray<double>, ILOutArray<double>>(
166                            X[full, r(wi * workItemLen, n - 1)], centers.C, tmpOutClasses);
167                    loopOverN(rngL);
168                    classes[r(wi * workItemLen, n - 1)] = tmpOutClasses;
169
170                    SpinWait.SpinUntil(() => { return workerCount <= 0; });
171                    Settings.MaxNumberThreads = maxNTSetting;
172                    // resamble
173                    for (wi = 0; wi < workItemCount - 1; wi++)
174                    {
175                        classes[r(wi * workItemLen, (wi + 1)* workItemLen - 1)] = classesSplit[wi];
176              }
177                    System.Diagnostics.Debug.Print("kmeans: 1 of {0} MemoryPool.Info: {1}", maxIterations, ILMemoryPool.Pool.Info(true));
178                    for (int i = 0; i < iK; i++) {
179                        using (EnterScope()) {
180                            ILArray<double> inClass = X[full, find(classes == i)];
181                            if (inClass.IsEmpty) {
182                                centers[full, i] = double.NaN;
183                            } else {
184                                centers[full, i] = mean(inClass, 1);
185                                ILArray<double> inClassDiff = inClass - repmat(centers[full, i], 1, size(inClass, 1));
186                            }
187                        }
188                    }
189#if KMEANSVERBOSE
190                    sw.Stop();
191                    Console.Out.WriteLine("Changed centers: {0} elapsed: {1}ms",(double)sum(any(oldCenters != centers)), sw.ElapsedMilliseconds);
192#endif
193                    if (allall(oldCenters == centers)) break;
194                    oldCenters.a = centers.C;
195                }
196                if (!object.Equals(outCenters, null))
197                    outCenters.a = centers;
198                return classes;
199            }
200        }
201
202    }
203}
Note: See TracBrowser for help on using the repository browser.