GaussianProcess.java 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. package de.jplag.clustering.algorithm;
  2. import java.text.MessageFormat;
  3. import java.util.List;
  4. import java.util.OptionalInt;
  5. import java.util.function.DoubleToIntFunction;
  6. import java.util.stream.DoubleStream;
  7. import java.util.stream.IntStream;
  8. import org.apache.commons.math3.linear.Array2DRowRealMatrix;
  9. import org.apache.commons.math3.linear.ArrayRealVector;
  10. import org.apache.commons.math3.linear.CholeskyDecomposition;
  11. import org.apache.commons.math3.linear.DiagonalMatrix;
  12. import org.apache.commons.math3.linear.RealMatrix;
  13. import org.apache.commons.math3.linear.RealVector;
  14. import org.apache.commons.math3.stat.StatUtils;
  15. public class GaussianProcess {
  16. private List<RealVector> X;
  17. private RealVector weight;
  18. private double mean;
  19. private double standardDeviation;
  20. private CholeskyDecomposition cholesky;
  21. private RealVector lengthScale;
  22. private GaussianProcess(List<RealVector> X, RealVector weight, double mean, double standardDeviation, CholeskyDecomposition cholesky,
  23. RealVector lengthScale) {
  24. this.X = X;
  25. this.weight = weight;
  26. this.mean = mean;
  27. this.standardDeviation = standardDeviation;
  28. this.cholesky = cholesky;
  29. this.lengthScale = lengthScale;
  30. }
  31. /**
  32. * @param x position to predict at
  33. * @return mean prediction at x
  34. */
  35. public double predict(RealVector x) {
  36. RealVector k = maternKernel(X, x, lengthScale);
  37. double mu = weight.dotProduct(k);
  38. return mu * this.standardDeviation + this.mean;
  39. }
  40. /**
  41. * @param x position to predict at
  42. * @return array containing the predicted [mean, std] at x.
  43. */
  44. public double[] predictWidthStd(RealVector x) {
  45. RealVector k = maternKernel(X, x, lengthScale);
  46. RealVector Kx = cholesky.getSolver().solve(k);
  47. double mu = weight.dotProduct(k);
  48. double sd = Math.sqrt(maternKernel(x, x, lengthScale) - Kx.dotProduct(k));
  49. double[] out = new double[2];
  50. out[0] = mu * this.standardDeviation + this.mean;
  51. out[1] = sd * this.standardDeviation;
  52. if (Double.isNaN(out[1])) {
  53. out[1] = 0;
  54. }
  55. return out;
  56. }
  57. private static final double SQRT_5 = Math.sqrt(5);
  58. /**
  59. * Identical to {@link GaussianProcess#fit(List, double[], double, boolean, double[])} but using a one vector as length
  60. * scale.
  61. * @param X
  62. * @param Y expected to have zero mean, unit variance if normalize is false
  63. * @param noise variance of noise in Y
  64. * @param normalize for Y
  65. */
  66. public static GaussianProcess fit(List<RealVector> X, double[] Y, double noise, boolean normalize) {
  67. return fit(X, Y, noise, normalize, new ArrayRealVector(X.get(0).getDimension(), 1).toArray());
  68. }
  69. /**
  70. * Fit Gaussian Process using a matern kernel.
  71. * @param X
  72. * @param Y expected to have zero mean, unit variance if normalize is false
  73. * @param noise variance of noise in Y
  74. * @param normalize if Y should be normalized
  75. * @param lengthScale X values are divided by these values before calculating their euclidean distance. If all entries
  76. * are equal the kernel is isometric.
  77. */
  78. public static GaussianProcess fit(List<RealVector> X, double[] Y, double noise, boolean normalize, double[] lengthScale) {
  79. if (X.size() != Y.length) {
  80. throw new IllegalArgumentException(MessageFormat.format("X and Y are of different dimensions {0} and {1}", X.size(), Y.length));
  81. }
  82. OptionalInt brokenXIndex = IntStream.range(1, X.size()).filter(i -> X.get(i).getDimension() != X.get(i - 1).getDimension()).findFirst();
  83. brokenXIndex.ifPresent(brokenIndex -> {
  84. throw new IllegalArgumentException(MessageFormat.format("X has different dimensions at index {0} ({2}) and index {1} ({3})",
  85. brokenIndex - 1, brokenXIndex, X.get(brokenIndex - 1).getDimension(), X.get(brokenIndex).getDimension()));
  86. });
  87. if (noise <= 0) {
  88. throw new IllegalArgumentException(MessageFormat.format("noise must be strictly positive, got {0}", noise));
  89. }
  90. if (lengthScale.length != X.get(0).getDimension()) {
  91. throw new IllegalArgumentException(
  92. MessageFormat.format("lengthScale is of different dimension {0} than X values {1}", lengthScale.length, X.get(0).getDimension()));
  93. }
  94. double mean = 0;
  95. double standardDeviation = 1;
  96. if (normalize) {
  97. mean = StatUtils.mean(Y);
  98. standardDeviation = Math.sqrt(StatUtils.variance(Y, mean));
  99. for (int i = 0; i < Y.length; i++) {
  100. Y[i] = (Y[i] - mean) / standardDeviation;
  101. }
  102. }
  103. RealVector yVector = new ArrayRealVector(Y);
  104. RealVector scaleV = new ArrayRealVector(lengthScale);
  105. RealMatrix k = maternKernel(X, scaleV);
  106. k = k.add(new DiagonalMatrix(DoubleStream.generate(() -> noise).limit(X.size()).toArray(), false));
  107. CholeskyDecomposition choDec = new CholeskyDecomposition(k);
  108. RealVector w = choDec.getSolver().solve(yVector);
  109. return new GaussianProcess(X, w, mean, standardDeviation, choDec, scaleV);
  110. }
  111. /**
  112. * Matern kernel for nu=2.5 (we get a twice differentiable gp)
  113. */
  114. private static RealMatrix maternKernel(List<RealVector> X, RealVector lengthScale) {
  115. RealMatrix k = new Array2DRowRealMatrix(X.size(), X.size());
  116. for (int i = 0; i < X.size(); i++) {
  117. RealVector left = X.get(i);
  118. for (int j = i; j < X.size(); j++) {
  119. RealVector right = X.get(j);
  120. double maternVal = maternKernel(left, right, lengthScale);
  121. k.setEntry(i, j, maternVal);
  122. k.setEntry(j, i, maternVal);
  123. }
  124. }
  125. return k;
  126. }
  127. private static RealVector maternKernel(List<RealVector> X, RealVector v, RealVector lengthScale) {
  128. RealVector out = new ArrayRealVector(X.size());
  129. for (int i = 0; i < X.size(); i++) {
  130. out.setEntry(i, maternKernel(X.get(i), v, lengthScale));
  131. }
  132. return out;
  133. }
  134. private static double maternKernel(RealVector left, RealVector right, RealVector lengthScale) {
  135. double dist = left.ebeDivide(lengthScale).getDistance(right.ebeDivide(lengthScale));
  136. dist *= SQRT_5;
  137. return (1 + dist) * Math.exp(-dist);
  138. }
  139. /**
  140. * ascii graph for debugging
  141. */
  142. public String toString(RealVector min, RealVector max, int width, int height, double minY) {
  143. char[][] out = new char[height][width];
  144. for (int i = 0; i < height; i++) {
  145. for (int j = 0; j < width; j++) {
  146. out[i][j] = ' ';
  147. }
  148. }
  149. double[] mean = new double[width];
  150. double[] std = new double[width];
  151. for (int i = 0; i < width; i++) {
  152. double t = (i + 0.5) / width;
  153. RealVector x = min.add(max.subtract(min).mapMultiplyToSelf(t));
  154. double[] meanStd = predictWidthStd(x);
  155. mean[i] = meanStd[0];
  156. std[i] = meanStd[1];
  157. }
  158. double[] upperBorder = IntStream.range(0, width).mapToDouble(i -> mean[i] + std[i]).toArray();
  159. double[] lowerBorder = IntStream.range(0, width).mapToDouble(i -> mean[i] - std[i]).toArray();
  160. double minVal = Math.max(DoubleStream.of(lowerBorder).min().orElseThrow(), minY);
  161. double maxVal = DoubleStream.of(upperBorder).max().orElseThrow();
  162. double range = maxVal - minVal;
  163. DoubleToIntFunction toCharPos = x -> (int) Math.round(height - height * (x - minVal) / range);
  164. int[] upperCharPos = DoubleStream.of(upperBorder).mapToInt(toCharPos).toArray();
  165. int[] lowerCharPos = DoubleStream.of(lowerBorder).mapToInt(toCharPos).toArray();
  166. int[] mindCharPos = DoubleStream.of(mean).mapToInt(toCharPos).toArray();
  167. for (int x = 0; x < width; x++) {
  168. if (upperCharPos[x] > 0 && upperCharPos[x] < height)
  169. out[upperCharPos[x]][x] = '-';
  170. if (lowerCharPos[x] > 0 && lowerCharPos[x] < height)
  171. out[lowerCharPos[x]][x] = '-';
  172. if (mindCharPos[x] > 0 && mindCharPos[x] < height)
  173. out[mindCharPos[x]][x] = '+';
  174. }
  175. StringBuilder sb = new StringBuilder();
  176. for (int i = 0; i < height; i++) {
  177. sb.append(out[i]);
  178. if (i < 98) {
  179. sb.append('\n');
  180. }
  181. }
  182. return sb.toString();
  183. }
  184. }