Github user lins05 commented on a diff in the pull request:
https://github.com/apache/spark/pull/13248#discussion_r70183009
--- Diff: python/pyspark/ml/stat/distribution.py ---
@@ -0,0 +1,267 @@
+#
+# 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.
+#
+
+from pyspark.ml.linalg import DenseVector, DenseMatrix, Vector
+import numpy as np
+
+__all__ = ['MultivariateGaussian']
+
+
+
+class MultivariateGaussian():
+ """
+ This class provides basic functionality for a Multivariate Gaussian
(Normal) Distribution. In
+ the event that the covariance matrix is singular, the density will be
computed in a
+ reduced dimensional subspace under which the distribution is supported.
+ (see
[[http://en.wikipedia.org/wiki/Multivariate_normal_distribution#Degenerate_case]])
+
+ mu The mean vector of the distribution
+ sigma The covariance matrix of the distribution
+
+
+ >>> mu = Vectors.dense([0.0, 0.0])
+ >>> sigma= DenseMatrix(2, 2, [1.0, 1.0, 1.0, 1.0])
+ >>> x = Vectors.dense([1.0, 1.0])
+ >>> m = MultivariateGaussian(mu, sigma)
+ >>> m.pdf(x)
+ 0.0682586811486
+
+ """
+
+ def __init__(self, mu, sigma):
+ """
+ __init__(self, mu, sigma)
+
+ mu The mean vector of the distribution
+ sigma The covariance matrix of the distribution
+
+ mu and sigma must be instances of DenseVector and DenseMatrix
respectively.
+
+ """
+
+
+ assert (isinstance(mu, DenseVector)), "mu must be a DenseVector
Object"
+ assert (isinstance(sigma, DenseMatrix)), "sigma must be a
DenseMatrix Object"
+
+ sigma_shape=sigma.toArray().shape
+ assert (sigma_shape[0]==sigma_shape[1]) , "Covariance matrix must
be square"
+ assert (sigma_shape[0]==mu.size) , "Mean vector length must match
covariance matrix size"
+
+ # initialize eagerly precomputed attributes
+
+ self.mu=mu
+
+ # storing sigma as numpy.ndarray
+ # furthur calculations are done ndarray only
+ self.sigma=sigma.toArray()
+
+
+ # initialize attributes to be computed later
+
+ self.prec_U = None
+ self.log_det_cov = None
+
+ # compute distribution dependent constants
+ self.__calculateCovarianceConstants()
+
+
+ def pdf(self,x):
+ """
+ Returns density of this multivariate Gaussian at a point given by
Vector x
+ """
+ assert (isinstance(x, Vector)), "x must be of Vector Type"
+ return float(self.__pdf(x))
+
+ def logpdf(self,x):
+ """
+ Returns the log-density of this multivariate Gaussian at a point
given by Vector x
+ """
+ assert (isinstance(x, Vector)), "x must be of Vector Type"
+ return float(self.__logpdf(x))
+
+ def __calculateCovarianceConstants(self):
+ """
+ Calculates distribution dependent components used for the density
function
+ based on scipy multivariate library
+ refer
https://github.com/scipy/scipy/blob/master/scipy/stats/_multivariate.py
+ tested with precision of 9 significant digits(refer testcase)
+
+
+ """
+
+ try :
+ # pre-processing input parameters
+ # throws ValueError with invalid inputs
+ self.dim, self.mu, self.sigma =
self.__process_parameters(None, self.mu, self.sigma)
+
+ # return the eigenvalues and eigenvectors
+ # of a Hermitian or symmetric matrix.
+ # s = eigen values
+ # u = eigen vectors
+ s, u = np.linalg.eigh(self.sigma)
+
+ #Singular values are considered to be non-zero only if
+ #they exceed a tolerance based on machine precision, matrix
size, and
+ #relation to the maximum singular value (same tolerance used
by, e.g., Octave).
+
+ # calculation for machine precision
+ t = u.dtype.char.lower()
+ factor = {'f': 1E3, 'd': 1E6}
+ cond = factor[t] * np.finfo(t).eps
+
+ eps = cond * np.max(abs(s))
+
+ # checkng whether covariance matrix has any non-zero singular
values
+ if np.min(s) < -eps:
+ raise ValueError
+
+ #computing the pseudoinverse
+ s_pinv = self.__pinv_1d(s, eps)
+
+ # prec_U ndarray
+ # A decomposition such that np.dot(prec_U, prec_U.T)
+ # is the precision matrix, i.e. inverse of the covariance
matrix.
+ self.prec_U = np.multiply(u, np.sqrt(s_pinv))
+
+ #log_det_cov : float
+ #Logarithm of the determinant of the covariance matrix
+ self.log_det_cov = np.sum(np.log(s[s > eps]))
+
+ except ValueError :
+ raise ValueError("Covariance matrix has no non-zero singular
values")
+
+ def __pdf(self,x):
+ """
+ Calculates density at point x using precomputed Constants
+ """
+ return np.exp(self.__logpdf(x))
+
+ def __logpdf(self,x) :
+ """
+ Calculates log-density at point x using precomputed Constants
+
+ x Points at which to evaluate the log of the probability
+ density function
+ log_det_cov : float
+ Logarithm of the determinant of the covariance matrix
+
+ prec_U ndarray
+ A decomposition such that np.dot(prec_U, prec_U.T)
+ is the precision matrix, i.e. inverse of the covariance matrix.
+
--- End diff --
The docstring is inconsistent with the method signature.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]