File: ClusMog.java

package info (click to toggle)
derby 10.14.2.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 79,056 kB
  • sloc: java: 691,961; sql: 42,686; xml: 20,512; sh: 3,373; sed: 96; makefile: 60
file content (289 lines) | stat: -rw-r--r-- 9,025 bytes parent folder | download | duplicates (4)
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/*
   Derby - Class org.apache.derbyTesting.functionTests.tests.memorydb.ClusMog

   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.
 */

package org.apache.derbyTesting.functionTests.tests.memorydb;

import java.util.Arrays;
import java.util.Random;
import org.apache.derbyTesting.junit.BaseTestCase;

/**
 * Simple utility to compute/recover the parameters of a mixture-of-Gaussian
 * distribution from independent samples.
 */
public class ClusMog
{
  /** default constructor */
  public ClusMog() {}

  /**
   * Compute/recover the parameters of a mixture-of-Gaussian distribution
   * from given independent samples.
   * @param n number of clusters (Gaussian components) to output
   * @param center initial cluster centers for iterative refinement
   * @param ns number of input samples
   * @param sample input samples; will be sorted in ascending order during use
   */
  public void cluster(int n, double center[], int ns, double sample[])
  {
    // Record input parameters.
    setCenters(n, center);
    setSamples(ns, sample);
    // Initialize EM iterations.
    initEM();
    // Perform EM iterations until convergence.
    final double thresh = 1.0e-6;
    double oldmsr = Double.MAX_VALUE;
    for (int it=1;; ++it) {
      // one EM iteration
      expectation();
      maximization();
      // Check for convergence.
      final double msr = measure();
      final double dif = Math.abs(msr - oldmsr);
      final double err = dif / (1.0 + oldmsr);
      oldmsr = msr;
      if (err < thresh) { break; }
    }
    // Compute cluster weights.
    computeWeights();

    // diagnostic messages
    printMog("JAVA-COMPUTED", n, weight, mean, var);
    BaseTestCase.println("msr = (" + oldmsr + ")");
  }

  /**
   * Compute an initial configuration of cluster centers uniformly spaced
   * over the range of the input samples, for subsequent iterative refinement.
   * @param n number of clusters to output
   * @param center initial uniform cluster centers to compute
   * @param ns number of input samples
   * @param sample array of input samples
   */
  public static void uniform(int n, double center[], int ns, double sample[])
  {
    double min_x = Double.MAX_VALUE, max_x = -Double.MAX_VALUE;
    for (int i=0; i<ns; ++i) {
      final double x = sample[i];
      if (min_x > x) { min_x = x; }
      if (max_x < x) { max_x = x; }
    }

    final double length = max_x - min_x;
    final double increment = length / n;
    center[0] = increment / 2;
    for (int i=1; i<n; ++i) { center[i] = center[i-1] + increment; }
  }

  /**
   * Compute an initial configuration of cluster centers uniformly distributed
   * over the range of the input samples, for subsequent iterative refinement.
   * @param n number of clusters to output
   * @param center initial uniform cluster centers to compute
   * @param ns number of input samples
   * @param sample array of input samples
   * @param rng random number generator
   */
  public static void random(int n, double center[], int ns, double sample[],
                            Random rng)
  {
    double min_x = Double.MAX_VALUE, max_x = -Double.MAX_VALUE;
    for (int i=0; i<ns; ++i) {
      final double x = sample[i];
      if (min_x > x) { min_x = x; }
      if (max_x < x) { max_x = x; }
    }

    final double length = max_x - min_x;
    for (int i=0; i<n; ++i) {
      final double r = rng.nextDouble();
      final double x = min_x + r * length;
      center[i] = x;
    }
  }

  /** Initialize cluster centers for EM iterations. */
  void setCenters(int n, double center[])
  {
    if (1 <= n && n <= max_n) {
      this.n = n;
      System.arraycopy(center, 0, mean, 0, n);
    }
    else {
      final String msg =
        "Number of Gaussian components (" + n + ") not in [1, " + max_n + "].";
      throw new IllegalArgumentException(msg);
    }
  }

  /** Specify the input samples to work with. */
  void setSamples(int ns, double sample[])
  {
    final int min_sample_size = n * min_sample_size_per_cluster;
    if (ns >= min_sample_size) {
      this.ns = ns;
      this.sample = sample;
    }
    else {
      final String msg =
        "Insufficient sample size (" + ns + " < " + min_sample_size + ").";
      throw new IllegalArgumentException(msg);
    }
  }

  /** Initialize the EM (expectation-maximization) iterations. */
  void initEM()
  {
    // Sort the input samples in ascending order.
    Arrays.sort(sample, 0, ns);
    // Sort the initial cluster centers in ascending order.
    Arrays.sort(mean, 0, n);
    // Initialize the cluster brackets.
    maximization();
  }

  /** (Re-)compute cluster centers while holding cluster brackets fixed. */
  void expectation()
  {
    // Remove empty clusters.
    for (int i=0, j=1;;) {
      // Examine the value at the current location.
      final int bi = bracket[i];
      // Locate the next larger value.
      for (; j<n; ++j) {
        final int bj = bracket[j];
        if (bi < bj) {
          // Move the larger value up to be adjacent to current value.
          bracket[i+1] = bj;
          // Advance loop variables.
          ++i;  ++j;  break;
        }
      }
      // Check for loop termination.
      if (j >= n) { n = i+1;  break; }
    }

    // Compute cluster parameters.
    for (int i=0; i<n; ++i) {
      final int ini = bracket[i];
      final int lim = bracket[i+1];
      final int nb = (lim - ini);
      // Computer cluster mean.
      double sum = 0.0;
      for (int j=ini; j<lim; ++j) {
        final double x = sample[j];
        sum += x;
      }
      final double m = (sum / nb);
      mean[i] = m;
      // Compute cluster variance.
      sum = 0.0;
      for (int j=ini; j<lim; ++j) {
        final double x = sample[j];
        final double d = x - m;
        sum += d * d;
      }
      final double v = ((nb > 1) ? (sum / (nb-1)) : 0.0);
      var[i] = v;
    }
  }

  /** (Re-)compute cluster brackets while holding cluster centers fixed. */
  void maximization()
  {
    bracket[0] = 0;
    for (int i=1; i<n; ++i) {
      final double mlo = mean[i-1];
      final double mhi = mean[i];
      // Compute the dividing point between clusters (i-1) and (i).
      int lo = bracket[i-1], hi = ns;
      while (lo < (hi-1)) {
        final int mid = (lo + hi) >> 1;
        final double sam = sample[mid];
        final double dlo = Math.abs(sam - mlo);
        final double dhi = Math.abs(mhi - sam);
        if (dlo < dhi) { lo = mid; } else { hi = mid; }
      }
      bracket[i] = hi;
    }
    bracket[n] = ns;
  }

  /** Compute a measure of total quantization error. */
  double measure()
  {
    double sum = 0.0;
    for (int i=0; i<n; ++i) {
      final int ini = bracket[i];
      final int lim = bracket[i+1];
      final int nb = lim - ini;
      final double v = var[i];
      sum += v * (nb-1);
    }
    sum /= ns;
    return sum;
  }

  /** Compute cluster weights. */
  void computeWeights()
  {
    for (int i=0; i<n; ++i) {
      final int ini = bracket[i];
      final int lim = bracket[i+1];
      final int siz = lim - ini;
      final double wt = ((ns > 0) ? ((double) siz / (double) ns) : 0.0);
      weight[i] = wt;
    }
  }

  /** Print out the clustering configuration. */
  void printMog(String label, int n, double weight[], double mean[], double var[])
  {
    BaseTestCase.println(label + ": n = " + n);
    for (int i=0; i<n; ++i) {
      BaseTestCase.println("(w, m, v) = (" +
              weight[i] + ", " + mean[i] + ", " + var[i] + ")");
    }
  }

  /** maximum number of Gaussian components */
  public final static int max_n = 6;

  /** actual number of Gaussian components */
  public int n = 0;
  /** weights associated with the Gaussian components */
  public final double weight[] = new double[max_n];
  /** mean parameters for the Gaussian components */
  public final double mean[] = new double[max_n];
  /** variance parameters for the Gaussian components */
  public final double var[] = new double[max_n];

  /** cluster brackets on the input samples */
  protected int bracket[] = new int[max_n+1];
  /** number of input samples */
  protected int ns = 0;
  /** array of input samples */
  protected double sample[] = null;

  /** minimum sample size per output cluster */
  public static final int min_sample_size_per_cluster = 32;
}