This repository has been archived by the owner on Nov 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
JointDistribution.cs
648 lines (579 loc) · 22.4 KB
/
JointDistribution.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
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
// Accord Statistics Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2017
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Statistics.Distributions.Multivariate
{
using System;
using Accord.Statistics.Distributions.Fitting;
using Accord.Math;
using System.Linq;
using Accord.Compat;
/// <summary>
/// Joint distribution of multiple discrete univariate distributions.
/// </summary>
///
/// <remarks>
/// <para>
/// This class builds a (potentially huge) lookup table for discrete
/// symbol distributions. For example, given a discrete variable A
/// which may take symbols a, b, c; and a discrete variable B which
/// may assume values x, y, z, this class will build the probability
/// table: </para>
///
/// <code>
/// x y z
/// a p(a,x) p(a,y) p(a,z)
/// b p(b,x) p(b,y) p(b,z)
/// c p(c,x) p(c,y) p(c,z)
/// </code>
///
/// <para>
/// Thus comprising the probabilities for all possible simple combination. This
/// distribution is a generalization of the
/// <see cref="Accord.Statistics.Distributions.Univariate.GeneralDiscreteDistribution"/>
/// for multivariate discrete observations.
/// </para>
/// </remarks>
///
/// <example>
/// <para>
/// The following example should demonstrate how to estimate a joint
/// distribution of two discrete variables. The first variable can
/// take up to three distinct values, whereas the second can assume
/// up to five.</para>
///
/// <code>
/// // Lets create a joint distribution for two discrete variables:
/// // the first of which can assume 3 distinct symbol values: 0, 1, 2
/// // the second which can assume 5 distinct symbol values: 0, 1, 2, 3, 4
///
/// int[] symbols = { 3, 5 }; // specify the symbol counts
///
/// // Create the joint distribution for the above variables
/// JointDistribution joint = new JointDistribution(symbols);
///
/// // Now, suppose we would like to fit the distribution (estimate
/// // its parameters) from the following multivariate observations:
/// //
/// double[][] observations =
/// {
/// new double[] { 0, 0 },
/// new double[] { 1, 1 },
/// new double[] { 2, 1 },
/// new double[] { 0, 0 },
/// };
///
///
/// // Estimate parameters
/// joint.Fit(observations);
///
/// // At this point, we can query the distribution for observations:
/// double p1 = joint.ProbabilityMassFunction(new[] { 0, 0 }); // should be 0.50
/// double p2 = joint.ProbabilityMassFunction(new[] { 1, 1 }); // should be 0.25
/// double p3 = joint.ProbabilityMassFunction(new[] { 2, 1 }); // should be 0.25
///
/// // As it can be seem, indeed {0,0} appeared twice at the data,
/// // and {1,1} and {2,1 appeared one fourth of the data each.
/// </code>
/// </example>
///
/// <see cref="Accord.Statistics.Distributions.Univariate.GeneralDiscreteDistribution"/>
/// <see cref="Independent{TDistribution}"/>
///
[Serializable]
public class JointDistribution : MultivariateDiscreteDistribution,
IFittableDistribution<int[], GeneralDiscreteOptions>,
IFittableDistribution<double[]>
{
// distribution parameters
private double[] probabilities;
private int[] start;
private int[] symbols;
private int[] positions;
// distribution measures
double[] mean;
/// <summary>
/// Gets the frequency of observation of each discrete variable.
/// </summary>
///
public double[] Frequencies
{
get { return probabilities; }
}
/// <summary>
/// Gets the integer value where the
/// discrete distribution starts.
/// </summary>
///
public int[] Minimum
{
get { return start; }
}
/// <summary>
/// Gets the integer value where the
/// discrete distribution ends.
/// </summary>
///
public int[] Maximum
{
get { return start.Add(symbols); }
}
/// <summary>
/// Gets the number of symbols in the distribution.
/// </summary>
///
public int[] Lengths
{
get { return symbols; }
}
/// <summary>
/// Gets the number of symbols for each discrete variable.
/// </summary>
///
[Obsolete("Please use Lengths instead.")]
public int[] Symbols
{
get { return symbols; }
}
/// <summary>
/// Gets the support interval for this distribution.
/// </summary>
///
/// <value>A <see cref="IntRange" /> containing
/// the support interval for this distribution.</value>
///
public override IntRange[] Support
{
get
{
var range = new IntRange[Dimension];
for (int i = 0; i < range.Length; i++)
range[i] = new IntRange(Minimum[i], Maximum[i]);
return range;
}
}
/// <summary>
/// Constructs a new joint discrete distribution.
/// </summary>
///
public JointDistribution(int[] symbols)
: base(symbols.Length)
{
init(new int[symbols.Length], symbols);
}
/// <summary>
/// Constructs a new joint discrete distribution.
/// </summary>
///
public JointDistribution(int[] starts, int[] symbols)
: base(symbols.Length)
{
init(starts, symbols);
}
/// <summary>
/// Constructs a new joint discrete distribution.
/// </summary>
///
public JointDistribution(int[] starts, Array probabilities)
: base(starts.Length)
{
init(starts, probabilities);
}
/// <summary>
/// Constructs a new joint discrete distribution.
/// </summary>
///
public JointDistribution(Array probabilities)
: base(probabilities.Rank)
{
init(new int[probabilities.Rank], probabilities);
}
private void init(int[] starts, int[] symbols)
{
this.symbols = symbols;
this.start = starts;
this.positions = new int[symbols.Length];
positions[positions.Length - 1] = 1;
for (int i = positions.Length - 2; i >= 0; i--)
positions[i] = positions[i + 1] * symbols[i + 1];
int total = 1;
for (int i = 0; i < symbols.Length; i++)
total *= symbols[i];
this.probabilities = new double[total];
for (int i = 0; i < probabilities.Length; i++)
probabilities[i] = 1.0 / total;
}
private void init(int[] starts, Array array)
{
this.symbols = array.GetLength();
this.start = starts;
this.positions = new int[symbols.Length];
this.probabilities = new double[array.Length];
positions[positions.Length - 1] = 1;
for (int i = positions.Length - 2; i >= 0; i--)
positions[i] = positions[i + 1] * symbols[i + 1];
foreach (var idx in array.GetIndices(true))
{
int index = 0;
for (int j = 0; j < idx.Length; j++)
index += idx[j] * positions[j];
probabilities[index] = (double)System.Convert.ChangeType(array.GetValue(true, idx), typeof(double));
}
}
/// <summary>
/// Constructs a new joint discrete distribution.
/// </summary>
///
private JointDistribution(int dimension)
: base(dimension)
{
}
/// <summary>
/// Gets or sets the probability value attached to the given index.
/// </summary>
///
public double this[int[] indices]
{
get
{
int index = ravel(indices);
return probabilities[index];
}
set
{
int index = ravel(indices);
probabilities[index] = value;
}
}
private int ravel(int[] indices)
{
int index = 0;
for (int j = 0; j < indices.Length; j++)
index += (indices[j] - start[j]) * positions[j];
return index;
}
private int ravel(double[] indices)
{
int index = 0;
for (int j = 0; j < indices.Length; j++)
index += ((int)indices[j] - start[j]) * positions[j];
return index;
}
/// <summary>
/// Constructs a new multidimensional uniform discrete distribution.
/// </summary>
///
/// <param name="dimensions">The number of dimensions in the joint distribution.</param>
///
/// <param name="a">
/// The integer value where the distribution starts, also
/// known as <c>a</c>. Default value is 0.</param>
/// <param name="b">
/// The integer value where the distribution ends, also
/// known as <c>b</c>.</param>
///
public static JointDistribution Uniform(int dimensions, int a, int b)
{
if (a > b)
{
throw new ArgumentOutOfRangeException("b",
"The starting number a must be lower than b.");
}
return new JointDistribution(
Vector.Create<int>(dimensions, a),
Vector.Create<int>(dimensions, b - a + 1));
}
/// <summary>
/// Gets the probability mass function (pmf) for
/// this distribution evaluated at point <c>x</c>.
/// </summary>
/// <param name="x">
/// A single point in the distribution range.</param>
/// <remarks>
/// The Probability Mass Function (PMF) describes the
/// probability that a given value <c>x</c> will occur.
/// </remarks>
/// <returns>
/// The probability of <c>x</c> occurring
/// in the current distribution.</returns>
///
protected internal override double InnerProbabilityMassFunction(int[] x)
{
int index = ravel(x);
if (index < 0 || index >= probabilities.Length)
return 0;
return probabilities[index];
}
/// <summary>
/// Gets the log-probability mass function (pmf) for
/// this distribution evaluated at point <c>x</c>.
/// </summary>
/// <param name="x">A single point in the distribution range.</param>
/// <returns>
/// The logarithm of the probability of <c>x</c>
/// occurring in the current distribution.
/// </returns>
/// <remarks>
/// The Probability Mass Function (PMF) describes the
/// probability that a given value <c>x</c> will occur.
/// </remarks>
///
protected internal override double InnerLogProbabilityMassFunction(int[] x)
{
int index = ravel(x);
if (index < 0 || index >= probabilities.Length)
return Math.Log(0);
return Math.Log(probabilities[index]);
}
/// <summary>
/// Gets the mean for this distribution.
/// </summary>
///
/// <value>
/// An array of double-precision values containing
/// the mean values for this distribution.
/// </value>
///
public override double[] Mean
{
get
{
if (mean == null)
{
mean = start.ToDouble();
foreach (int[] idx in Combinatorics.Sequences(symbols))
{
double p = this[idx.Add(start)];
for (int i = 0; i < idx.Length; i++)
mean[i] += idx[i] * p;
}
}
return mean;
}
}
/// <summary>
/// Gets the mean for this distribution.
/// </summary>
///
/// <value>
/// An array of double-precision values containing
/// the variance values for this distribution.
/// </value>
///
public override double[] Variance
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// Gets the variance for this distribution.
/// </summary>
///
/// <value>
/// An multidimensional array of double-precision values
/// containing the covariance values for this distribution.
/// </value>
///
public override double[,] Covariance
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// Gets the cumulative distribution function (cdf) for
/// this distribution evaluated at point <c>x</c>.
/// </summary>
///
/// <param name="x">A single point in the distribution range.</param>
///
/// <remarks>
/// The Cumulative Distribution Function (CDF) describes the cumulative
/// probability that a given value or any value smaller than it will occur.
/// </remarks>
///
protected internal override double InnerDistributionFunction(int[] x)
{
int[] value = x.Subtract(start);
double sum = 0.0;
foreach (int[] idx in Combinatorics.Sequences(symbols))
{
if (lessThanOrEqual(value, idx))
sum += this[idx];
}
return sum;
}
private static bool lessThanOrEqual(int[] x, int[] idx)
{
for (int i = 0; i < x.Length; i++)
{
if (idx[i] > x[i])
return false;
}
return true;
}
/// <summary>
/// Fits the underlying distribution to a given set of observations.
/// </summary>
///
/// <param name="observations">The array of observations to fit the model against. The array
/// elements can be either of type double (for univariate data) or
/// type double[] (for multivariate data).</param>
/// <param name="weights">The weight vector containing the weight for each of the samples.</param>
/// <param name="options">Optional arguments which may be used during fitting, such
/// as regularization constants and additional parameters.</param>
///
public override void Fit(double[][] observations, double[] weights, IFittingOptions options)
{
if (options != null)
throw new ArgumentException("This method does not accept fitting options.");
for (int i = 0; i < probabilities.Length; i++)
probabilities[i] = 0;
if (weights != null)
{
if (observations.Length != weights.Length)
{
throw new DimensionMismatchException("weights",
"The weight vector should have the same size as the observations");
}
for (int i = 0; i < observations.Length; i++)
probabilities[ravel(observations[i])] += weights[i];
}
else
{
for (int i = 0; i < observations.Length; i++)
probabilities[ravel(observations[i])]++;
}
double sum = 0;
for (int i = 0; i < probabilities.Length; i++)
sum += probabilities[i];
if (sum != 0 && sum != 1)
{
// TODO: add the following in a JointOption class:
// avoid locking a parameter in zero.
// if (num == 0) num = 1e-10;
// assert that probabilities sum up to 1.
for (int i = 0; i < probabilities.Length; i++)
probabilities[i] /= sum;
}
}
/// <summary>
/// Fits the underlying distribution to a given set of observations.
/// </summary>
/// <param name="observations">The array of observations to fit the model against. The array
/// elements can be either of type double (for univariate data) or
/// type double[] (for multivariate data).</param>
public void Fit(int[][] observations)
{
Fit(observations, null, null);
}
/// <summary>
/// Fits the underlying distribution to a given set of observations.
/// </summary>
/// <param name="observations">The array of observations to fit the model against. The array
/// elements can be either of type double (for univariate data) or
/// type double[] (for multivariate data).</param>
/// <param name="weights"></param>
public void Fit(int[][] observations, double[] weights)
{
Fit(observations, weights, null);
}
/// <summary>
/// Fits the underlying distribution to a given set of observations.
/// </summary>
/// <param name="observations">The array of observations to fit the model against. The array
/// elements can be either of type double (for univariate data) or
/// type double[] (for multivariate data).</param>
/// <param name="weights">The weight vector containing the weight for each of the samples.</param>
/// <param name="options">Optional arguments which may be used during fitting, such
/// as regularization constants and additional parameters.</param>
/// <exception cref="System.ArgumentException">This method does not accept fitting options.</exception>
/// <exception cref="DimensionMismatchException">weights;The weight vector should have the same size as the observations</exception>
public void Fit(int[][] observations, double[] weights, GeneralDiscreteOptions options)
{
if (options != null)
throw new ArgumentException("This method does not accept fitting options.");
for (int i = 0; i < probabilities.Length; i++)
probabilities[i] = 0;
if (weights != null)
{
if (observations.Length != weights.Length)
{
throw new DimensionMismatchException("weights",
"The weight vector should have the same size as the observations");
}
for (int i = 0; i < observations.Length; i++)
probabilities[ravel(observations[i])] += weights[i];
}
else
{
for (int i = 0; i < observations.Length; i++)
probabilities[ravel(observations[i])]++;
}
double sum = 0;
for (int i = 0; i < probabilities.Length; i++)
sum += probabilities[i];
if (sum != 0 && sum != 1)
{
for (int i = 0; i < probabilities.Length; i++)
probabilities[i] /= sum;
}
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
public override object Clone()
{
JointDistribution d = new JointDistribution(base.Dimension);
d.positions = this.positions.Copy();
d.probabilities = this.probabilities.Copy();
d.symbols = this.symbols.Copy();
d.start = this.start.Copy();
return d;
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
///
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
///
public override string ToString(string format, IFormatProvider formatProvider)
{
return String.Format(formatProvider, "Joint(X)");
}
/// <summary>
/// Estimates a new <see cref="JointDistribution"/> from a given set of observations.
/// </summary>
///
/// <example>
/// Please see <see cref="JointDistribution"/>.
/// </example>
///
public static JointDistribution Estimate(int[][] values)
{
var joint = new JointDistribution(values.DistinctCount());
joint.Fit(values);
return joint;
}
}
}