GVKun编程网logo

Python numpy 模块-linalg() 实例源码(python numpy.linalg)

4

在本文中,我们将给您介绍关于Pythonnumpy模块-linalg()实例源码的详细内容,并且为您解答pythonnumpy.linalg的相关问题,此外,我们还将为您提供关于np.linalg.s

在本文中,我们将给您介绍关于Python numpy 模块-linalg() 实例源码的详细内容,并且为您解答python numpy.linalg的相关问题,此外,我们还将为您提供关于np.linalg.solve 和 scipy.linalg.cho_solve 之间的性能差距、Python numpy.linalg 模块-cholesky() 实例源码、Python numpy.linalg 模块-cond() 实例源码、Python numpy.linalg 模块-det() 实例源码的知识。

本文目录一览:

Python numpy 模块-linalg() 实例源码(python numpy.linalg)

Python numpy 模块-linalg() 实例源码(python numpy.linalg)

Python numpy 模块,linalg() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.linalg()

项目:neurotools    作者:michaelerule    | 项目源码 | 文件源码
  1. def logdet(C,eps=1e-6,safe=0):
  2. ''''''
  3. Logarithm of the determinant of a matrix
  4. Works only with real-valued positive definite matrices
  5. ''''''
  6. try:
  7. return 2.0*np.sum(np.log(np.diag(chol(C))))
  8. except numpy.linalg.linalg.LinAlgError:
  9. if safe: C = check_covmat(C,eps=eps)
  10. w = np.linalg.eigh(C)[0]
  11. w = np.real(w)
  12. w[w<eps]=eps
  13. det = np.sum(np.log(w))
  14. return det
项目:camera_calibration_frontend    作者:groundmelon    | 项目源码 | 文件源码
  1. def _get_skew(corners, board):
  2. """
  3. Get skew for given checkerboard detection.
  4. Scaled to [0,1],which 0 = no skew,1 = high skew
  5. Skew is proportional to the divergence of three outside corners from 90 degrees.
  6. """
  7. # Todo Using three nearby interior corners might be more robust,outside corners occasionally
  8. # get mis-detected
  9. up_left, up_right, down_right, _ = _get_outside_corners(corners, board)
  10.  
  11. def angle(a, b, c):
  12. """
  13. Return angle between lines ab,bc
  14. """
  15. ab = a - b
  16. cb = c - b
  17. return math.acos(numpy.dot(ab,cb) / (numpy.linalg.norm(ab) * numpy.linalg.norm(cb)))
  18.  
  19. skew = min(1.0, 2. * abs((math.pi / 2.) - angle(up_left, down_right)))
  20. return skew
项目:FermiLib    作者:ProjectQ-Framework    | 项目源码 | 文件源码
  1. def get_ground_state(sparse_operator):
  2. """Compute lowest eigenvalue and eigenstate.
  3.  
  4. Returns:
  5. eigenvalue: The lowest eigenvalue,a float.
  6. eigenstate: The lowest eigenstate in scipy.sparse csc format.
  7. """
  8. if not is_hermitian(sparse_operator):
  9. raise ValueError(''sparse_operator must be hermitian.'')
  10.  
  11. values, vectors = scipy.sparse.linalg.eigsh(
  12. sparse_operator, 2, which=''SA'', maxiter=1e7)
  13.  
  14. eigenstate = scipy.sparse.csc_matrix(vectors[:, 0])
  15. eigenvalue = values[0]
  16. return eigenvalue, eigenstate.getH()
项目:maze-builder    作者:kcsaff    | 项目源码 | 文件源码
  1. def __init__(self, mesh, transform_out=None, transform_in=None):
  2. transform_out = numpy.matrix(transform_out) if transform_out is not None else None
  3. transform_in = numpy.matrix(transform_in) if transform_in is not None else None
  4.  
  5. if transform_in is None and transform_out is None:
  6. transform_in = numpy.identity(3)
  7. transform_out = numpy.identity(3)
  8. elif transform_in is None:
  9. try:
  10. transform_in = numpy.linalg.inv(transform_out)
  11. except:
  12. transform_in = None
  13. elif transform_out is None:
  14. try:
  15. transform_out = numpy.linalg.inv(transform_in)
  16. except:
  17. transform_out = None
  18.  
  19. self.transform_out, self.transform_in = transform_out, transform_in
  20.  
  21. super().__init__(
  22. mesh,
  23. warp_in=lambda vertex: self.transform_in.dot(vertex).tolist()[0][:3] if self.transform_in else None,
  24. warp_out=lambda vertex: self.transform_out.dot(vertex).tolist()[0][:3] if self.transform_out else None,
  25. )
项目:gail-driver    作者:sisl    | 项目源码 | 文件源码
  1. def likelihood(x, m=None, Cinv=None, sigma=1, detC=None):
  2. """return likelihood of x for the normal density N(m,sigma**2 * Cinv**-1)"""
  3. # testing: MC integrate must be one: mean(p(x_i)) * volume(where x_i are uniformely sampled)
  4. # for i in xrange(3): print mean([cma.likelihood(20*r-10,dim * [0],
  5. # None,3) for r in rand(10000,dim)]) * 20**dim
  6. if m is None:
  7. dx = x
  8. else:
  9. dx = x - m # array(x) - array(m)
  10. n = len(x)
  11. s2pi = (2 * np.pi)**(n / 2.)
  12. if Cinv is None:
  13. return exp(-sum(dx**2) / sigma**2 / 2) / s2pi / sigma**n
  14. if detC is None:
  15. detC = 1. / np.linalg.linalg.det(Cinv)
  16. return exp(-np.dot(dx, np.dot(Cinv, dx)) / sigma**2 / 2) / s2pi / abs(detC)**0.5 / sigma**n
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_pseudoinverse_correctness():
  2. rng = numpy.random.RandomState(utt.fetch_seed())
  3. d1 = rng.randint(4) + 2
  4. d2 = rng.randint(4) + 2
  5. r = rng.randn(d1, d2).astype(theano.config.floatX)
  6.  
  7. x = tensor.matrix()
  8. xi = pinv(x)
  9.  
  10. ri = function([x], xi)(r)
  11. assert ri.shape[0] == r.shape[1]
  12. assert ri.shape[1] == r.shape[0]
  13. assert ri.dtype == r.dtype
  14. # Note that pseudoinverse can be quite unprecise so I prefer to compare
  15. # the result with what numpy.linalg returns
  16. assert _allclose(ri, numpy.linalg.pinv(r))
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_numpy_compare(self):
  2. rng = numpy.random.RandomState(utt.fetch_seed())
  3.  
  4. M = tensor.matrix("A", dtype=theano.config.floatX)
  5. V = tensor.vector("V", dtype=theano.config.floatX)
  6.  
  7. a = rng.rand(4, 4).astype(theano.config.floatX)
  8. b = rng.rand(4).astype(theano.config.floatX)
  9.  
  10. A = ( [None, ''fro'', ''inf'', ''-inf'', 1, -1, None, 0, -2],
  11. [M, M, V, V],
  12. [a, a, b],
  13. [None, inf, -inf, -2])
  14.  
  15. for i in range(0, 14):
  16. f = function([A[1][i]], norm(A[1][i], A[0][i]))
  17. t_n = f(A[2][i])
  18. n_n = numpy.linalg.norm(A[2][i], A[3][i])
  19. assert _allclose(n_n, t_n)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_eval(self):
  2. A = self.A
  3. Ai = tensorinv(A)
  4. n_ainv = numpy.linalg.tensorinv(self.a)
  5. tf_a = function([A], [Ai])
  6. t_ainv = tf_a(self.a)
  7. assert _allclose(n_ainv, t_ainv)
  8.  
  9. B = self.B
  10. Bi = tensorinv(B)
  11. Bi1 = tensorinv(B, ind=1)
  12. n_binv = numpy.linalg.tensorinv(self.b)
  13. n_binv1 = numpy.linalg.tensorinv(self.b1, ind=1)
  14. tf_b = function([B], [Bi])
  15. tf_b1 = function([B], [Bi1])
  16. t_binv = tf_b(self.b)
  17. t_binv1 = tf_b1(self.b1)
  18. assert _allclose(t_binv, n_binv)
  19. assert _allclose(t_binv1, n_binv1)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_perform(self):
  2. if not imported_scipy:
  3. raise SkipTest(''kron tests need the scipy package to be installed'')
  4.  
  5. for shp0 in [(2,), (2, 3), 3, 4), 4, 5)]:
  6. x = tensor.tensor(dtype=''floatX'',
  7. broadcastable=(False,) * len(shp0))
  8. a = numpy.asarray(self.rng.rand(*shp0)).astype(config.floatX)
  9. for shp1 in [(6, (6, 7), 7, 8), 8, 9)]:
  10. if len(shp0) + len(shp1) == 2:
  11. continue
  12. y = tensor.tensor(dtype=''floatX'',
  13. broadcastable=(False,) * len(shp1))
  14. f = function([x, y], kron(x, y))
  15. b = self.rng.rand(*shp1).astype(config.floatX)
  16. out = f(a, b)
  17. # Newer versions of scipy want 4 dimensions at least,
  18. # so we have to add a dimension to a and flatten the result.
  19. if len(shp0) + len(shp1) == 3:
  20. scipy_val = scipy.linalg.kron(
  21. a[numpy.newaxis, :], b).flatten()
  22. else:
  23. scipy_val = scipy.linalg.kron(a, b)
  24. utt.assert_allclose(out, scipy_val)
项目:neurotools    作者:michaelerule    | 项目源码 | 文件源码
  1. def real_eig(M,eps=1e-9):
  2. ''''''
  3. This code expects a real hermetian matrix
  4. and should throw a ValueError if not.
  5. This is probably redundant to the scipy eigh function.
  6. Do not use.
  7. ''''''
  8. if not (type(M)==np.ndarray):
  9. raise ValueError("Expected array; type is %s"%type(M))
  10. if np.any(np.abs(np.imag(M))>eps):
  11. raise ValueError("Matrix has imaginary values >%0.2e; will not extract real eigenvalues"%eps)
  12. M = np.real(M)
  13. w,v = np.linalg.eig(M)
  14. if np.any(abs(np.imag(w))>eps):
  15. raise ValueError(''Eigenvalues with imaginary part >%0.2e; matrix has complex eigenvalues''%eps)
  16. w = np.real(w)
  17. order = np.argsort(w)
  18. w = w[order]
  19. v = v[:,order]
  20. return w,v
项目:neurotools    作者:michaelerule    | 项目源码 | 文件源码
  1. def _getAplus(A):
  2. ''''''
  3. Please see the documentation for nearPDHigham
  4. ''''''
  5. eigval, eigvec = np.linalg.eig(A)
  6. Q = np.matrix(eigvec)
  7. xdiag = np.matrix(np.diag(np.maximum(eigval, 0)))
  8. return Q*xdiag*Q.T
项目:composability_bench    作者:Intelpython    | 项目源码 | 文件源码
  1. def bench_on(runner, sym, Ns, trials, dtype=None):
  2. global args, kernel, out, mkl_layer
  3. prepare = globals().get("prepare_"+sym, prepare_default)
  4. kernel = globals().get("kernel_"+sym, None)
  5. if not kernel:
  6. kernel = getattr(np.linalg, sym)
  7. out_lvl = runner.__doc__.split(''.'')[0].strip()
  8. func_s = kernel.__doc__.split(''.'')[0].strip()
  9. log.debug(''Preparing input data for %s (%s).. '' % (sym, func_s))
  10. args = [prepare(int(i)) for i in Ns]
  11. it = range(len(Ns))
  12. # pprint(Ns)
  13. out = np.empty(shape=(len(Ns), trials))
  14. b = body(trials)
  15. tic, toc = (0, 0)
  16. log.debug(''Warming up %s (%s).. '' % (sym, func_s))
  17. runner(range(1000), empty_work)
  18. kernel(*args[0])
  19. runner(range(1000), empty_work)
  20. log.debug(''Benchmarking %s on %s: '' % (func_s, out_lvl))
  21. gc_old = gc.isenabled()
  22. # gc.disable()
  23. tic = time.time()
  24. runner(it, b)
  25. toc = time.time() - tic
  26. if gc_old:
  27. gc.enable()
  28. if ''reused_pool'' in globals():
  29. del globals()[''reused_pool'']
  30.  
  31. #calculate average time and min time and also keep track of outliers (max time in the loop)
  32. min_time = np.amin(out)
  33. max_time = np.amax(out)
  34. mean_time = np.mean(out)
  35. stdev_time = np.std(out)
  36.  
  37. #print("Min = %.5f,Max = %.5f,Mean = %.5f,stdev = %.5f " % (min_time,max_time,mean_time,stdev_time))
  38. #final_times = [min_time,stdev_time]
  39.  
  40. print(''## %s: Outter:%s,Inner:%s,Wall seconds:%f\\n'' % (sym, out_lvl, mkl_layer, float(toc)))
  41. return out
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
  1. def get_whitening_matrix(X, fudge=1E-18):
  2. from numpy.linalg import eigh
  3. Xcov = numpy.dot(X.T, X)/X.shape[0]
  4. d,V = eigh(Xcov)
  5. D = numpy.diag(1./numpy.sqrt(d+fudge))
  6. W = numpy.dot(numpy.dot(V,D), V.T)
  7. return W
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
  1. def get_precision(self):
  2. """Compute data precision matrix with the generative model.
  3. Equals the inverse of the covariance but computed with
  4. the matrix inversion lemma for efficiency.
  5. Returns
  6. -------
  7. precision : array,shape=(n_features,n_features)
  8. Estimated precision of data.
  9. """
  10. n_features = self.components_.shape[1]
  11.  
  12. # handle corner cases first
  13. if self.n_components_ == 0:
  14. return np.eye(n_features) / self.noise_variance_
  15. if self.n_components_ == n_features:
  16. return linalg.inv(self.get_covariance())
  17.  
  18. # Get precision using matrix inversion lemma
  19. components_ = self.components_
  20. exp_var = self.explained_variance_
  21. exp_var_diff = np.maximum(exp_var - self.noise_variance_, 0.)
  22. precision = np.dot(components_, components_.T) / self.noise_variance_
  23. precision.flat[::len(precision) + 1] += 1. / exp_var_diff
  24. precision = np.dot(components_.T,
  25. np.dot(linalg.inv(precision), components_))
  26. precision /= -(self.noise_variance_ ** 2)
  27. precision.flat[::len(precision) + 1] += 1. / self.noise_variance_
  28. return precision
项目:pycma    作者:CMA-ES    | 项目源码 | 文件源码
  1. def __init__(self, dimension,
  2. lazy_update_gap=0,
  3. constant_trace='''',
  4. randn=np.random.randn,
  5. eigenmethod=np.linalg.eigh):
  6. try:
  7. self.dimension = len(dimension)
  8. standard_deviations = np.asarray(dimension)
  9. except TypeError:
  10. self.dimension = dimension
  11. standard_deviations = np.ones(dimension)
  12. assert len(standard_deviations) == self.dimension
  13.  
  14. # prevent equal eigenvals,a hack for np.linalg:
  15. self.C = np.diag(standard_deviations**2
  16. * np.exp((1e-4 / self.dimension) *
  17. np.arange(self.dimension)))
  18. "covariance matrix"
  19. self.lazy_update_gap = lazy_update_gap
  20. self.constant_trace = constant_trace
  21. self.randn = randn
  22. self.eigenmethod = eigenmethod
  23. self.B = np.eye(self.dimension)
  24. "columns,B.T[i] == B[:,i],are eigenvectors of C"
  25. self.D = np.diag(self.C)**0.5 # we assume that C is yet diagonal
  26. idx = self.D.argsort()
  27. self.D = self.D[idx]
  28. self.B = self.B[:, idx]
  29. "axis lengths,roots of eigenvalues,sorted"
  30. self._inverse_root_C = None # see transform_inv...
  31. self.last_update = 0
  32. self.count_tell = 0
  33. self.count_eigen = 0
项目:SLP-Annotator    作者:PhonologicalCorpusTools    | 项目源码 | 文件源码
  1. def rotation_from_matrix(matrix):
  2. """Return rotation angle and axis from rotation matrix.
  3.  
  4. >>> angle = (random.random() - 0.5) * (2*math.pi)
  5. >>> direc = numpy.random.random(3) - 0.5
  6. >>> point = numpy.random.random(3) - 0.5
  7. >>> R0 = rotation_matrix(angle,direc,point)
  8. >>> angle,point = rotation_from_matrix(R0)
  9. >>> R1 = rotation_matrix(angle,point)
  10. >>> is_same_transform(R0,R1)
  11. True
  12.  
  13. """
  14. R = numpy.array(matrix, dtype=numpy.float64, copy=False)
  15. R33 = R[:3, :3]
  16. # direction: unit eigenvector of R33 corresponding to eigenvalue of 1
  17. w, W = numpy.linalg.eig(R33.T)
  18. i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
  19. if not len(i):
  20. raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
  21. direction = numpy.real(W[:, i[-1]]).squeeze()
  22. # point: unit eigenvector of R33 corresponding to eigenvalue of 1
  23. w, Q = numpy.linalg.eig(R)
  24. i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
  25. if not len(i):
  26. raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
  27. point = numpy.real(Q[:, i[-1]]).squeeze()
  28. point /= point[3]
  29. # rotation angle depending on direction
  30. cosa = (numpy.trace(R33) - 1.0) / 2.0
  31. if abs(direction[2]) > 1e-8:
  32. sina = (R[1, 0] + (cosa-1.0)*direction[0]*direction[1]) / direction[2]
  33. elif abs(direction[1]) > 1e-8:
  34. sina = (R[0, 2] + (cosa-1.0)*direction[0]*direction[2]) / direction[1]
  35. else:
  36. sina = (R[2, 1] + (cosa-1.0)*direction[1]*direction[2]) / direction[0]
  37. angle = math.atan2(sina, cosa)
  38. return angle, direction, point
  39.  
  40. # Function to translate handshape coding to degrees of rotation,adduction,flexion
项目:SLP-Annotator    作者:PhonologicalCorpusTools    | 项目源码 | 文件源码
  1. def vector_norm(data, axis=None, out=None):
  2. """Return length,i.e. Euclidean norm,of ndarray along axis.
  3.  
  4. >>> v = numpy.random.random(3)
  5. >>> n = vector_norm(v)
  6. >>> numpy.allclose(n,numpy.linalg.norm(v))
  7. True
  8. >>> v = numpy.random.rand(6,5,3)
  9. >>> n = vector_norm(v,axis=-1)
  10. >>> numpy.allclose(n,numpy.sqrt(numpy.sum(v*v,axis=2)))
  11. True
  12. >>> n = vector_norm(v,axis=1)
  13. >>> numpy.allclose(n,axis=1)))
  14. True
  15. >>> v = numpy.random.rand(5,4,3)
  16. >>> n = numpy.empty((5,3))
  17. >>> vector_norm(v,axis=1,out=n)
  18. >>> numpy.allclose(n,axis=1)))
  19. True
  20. >>> vector_norm([])
  21. 0.0
  22. >>> vector_norm([1])
  23. 1.0
  24.  
  25. """
  26. data = numpy.array(data, copy=True)
  27. if out is None:
  28. if data.ndim == 1:
  29. return math.sqrt(numpy.dot(data, data))
  30. data *= data
  31. out = numpy.atleast_1d(numpy.sum(data, axis=axis))
  32. numpy.sqrt(out, out)
  33. return out
  34. else:
  35. data *= data
  36. numpy.sum(data, axis=axis, out=out)
  37. numpy.sqrt(out, out)
项目:SLP-Annotator    作者:PhonologicalCorpusTools    | 项目源码 | 文件源码
  1. def rotation_from_matrix(matrix):
  2. """Return rotation angle and axis from rotation matrix.
  3.  
  4. >>> angle = (random.random() - 0.5) * (2*math.pi)
  5. >>> direc = numpy.random.random(3) - 0.5
  6. >>> point = numpy.random.random(3) - 0.5
  7. >>> R0 = rotation_matrix(angle,flexion
项目:third_person_im    作者:bstadie    | 项目源码 | 文件源码
  1. def expms(A, eig=np.linalg.eigh):
  2. """matrix exponential for a symmetric matrix"""
  3. # Todo: check that this works reliably for low rank matrices
  4. # first: symmetrize A
  5. D, B = eig(A)
  6. return np.dot(B, (np.exp(D) * B).T)
项目:third_person_im    作者:bstadie    | 项目源码 | 文件源码
  1. def likelihood(x,None,dim)]) * 20**dim
  2. if m is None:
  3. dx = x
  4. else:
  5. dx = x - m # array(x) - array(m)
  6. n = len(x)
  7. s2pi = (2 * np.pi)**(n / 2.)
  8. if Cinv is None:
  9. return exp(-sum(dx**2) / sigma**2 / 2) / s2pi / sigma**n
  10. if detC is None:
  11. detC = 1. / np.linalg.linalg.det(Cinv)
  12. return exp(-np.dot(dx, dx)) / sigma**2 / 2) / s2pi / abs(detC)**0.5 / sigma**n
项目:CSB    作者:csb-toolBox    | 项目源码 | 文件源码
  1. def rmsd(X, Y):
  2. """
  3. Calculate the root mean squared deviation (RMSD) using Kabsch'' formula.
  4.  
  5. @param X: (n,d) input vector
  6. @type X: numpy array
  7.  
  8. @param Y: (n,d) input vector
  9. @type Y: numpy array
  10.  
  11. @return: rmsd value between the input vectors
  12. @rtype: float
  13. """
  14.  
  15. from numpy import sum, dot, sqrt, clip, average
  16. from numpy.linalg import svd, det
  17.  
  18. X = X - X.mean(0)
  19. Y = Y - Y.mean(0)
  20.  
  21. R_x = sum(X ** 2)
  22. R_y = sum(Y ** 2)
  23.  
  24. V, L, U = svd(dot(Y.T, X))
  25.  
  26. if det(dot(V, U)) < 0.:
  27. L[-1] *= -1
  28.  
  29. return sqrt(clip(R_x + R_y - 2 * sum(L), 0., 1e300) / len(X))
项目:CSB    作者:csb-toolBox    | 项目源码 | 文件源码
  1. def wrmsd(X, Y, w):
  2. """
  3. Calculate the weighted root mean squared deviation (wRMSD) using Kabsch''
  4. formula.
  5.  
  6. @param X: (n,d) input vector
  7. @type Y: numpy array
  8.  
  9. @param w: input weights
  10. @type w: numpy array
  11.  
  12. @return: rmsd value between the input vectors
  13. @rtype: float
  14. """
  15.  
  16. from numpy import sum, average
  17. from numpy.linalg import svd
  18.  
  19. ## normalize weights
  20.  
  21. w = w / w.sum()
  22.  
  23. X = X - dot(w, X)
  24. Y = Y - dot(w, Y)
  25.  
  26. R_x = sum(X.T ** 2 * w)
  27. R_y = sum(Y.T ** 2 * w)
  28.  
  29. L = svd(dot(Y.T * w, X))[1]
  30.  
  31. return sqrt(clip(R_x + R_y - 2 * sum(L), 1e300))
项目:CSB    作者:csb-toolBox    | 项目源码 | 文件源码
  1. def is_mirror_image(X, Y):
  2. """
  3. Check if two configurations X and Y are mirror images
  4. (i.e. their optimal superposition involves a reflection).
  5.  
  6. @param X: n x 3 input vector
  7. @type X: numpy array
  8. @param Y: n x 3 input vector
  9. @type Y: numpy array
  10.  
  11. @rtype: bool
  12. """
  13. from numpy.linalg import det, svd
  14.  
  15. ## center configurations
  16.  
  17. X = X - numpy.mean(X, 0)
  18. Y = Y - numpy.mean(Y, 0)
  19.  
  20. ## SVD of correlation matrix
  21.  
  22. V, U = svd(numpy.dot(numpy.transpose(X), Y)) #@UnusedVariable
  23.  
  24. R = numpy.dot(V, U)
  25.  
  26. return det(R) < 0
项目:rllabplusplus    作者:shaneshixiang    | 项目源码 | 文件源码
  1. def expms(A, (np.exp(D) * B).T)
项目:rllabplusplus    作者:shaneshixiang    | 项目源码 | 文件源码
  1. def likelihood(x, dx)) / sigma**2 / 2) / s2pi / abs(detC)**0.5 / sigma**n
项目:cma    作者:hardmaru    | 项目源码 | 文件源码
  1. def expms(A, (np.exp(D) * B).T)
项目:cma    作者:hardmaru    | 项目源码 | 文件源码
  1. def likelihood(x, dx)) / sigma**2 / 2) / s2pi / abs(detC)**0.5 / sigma**n
项目:Deep-Subspace-Clustering    作者:tonyabracadabra    | 项目源码 | 文件源码
  1. def eig(a):
  2. u,v = np.linalg.eig(a)
  3. return u.T
项目:FermiLib    作者:ProjectQ-Framework    | 项目源码 | 文件源码
  1. def sparse_eigenspectrum(sparse_operator):
  2. """Perform a dense diagonalization.
  3.  
  4. Returns:
  5. eigenspectrum: The lowest eigenvalues in a numpy array.
  6. """
  7. dense_operator = sparse_operator.todense()
  8. if is_hermitian(sparse_operator):
  9. eigenspectrum = numpy.linalg.eigvalsh(dense_operator)
  10. else:
  11. eigenspectrum = numpy.linalg.eigvals(dense_operator)
  12. return numpy.sort(eigenspectrum)
项目:FermiLib    作者:ProjectQ-Framework    | 项目源码 | 文件源码
  1. def get_gap(sparse_operator):
  2. """Compute gap between lowest eigenvalue and first excited state.
  3.  
  4. Returns: A real float giving eigenvalue gap.
  5. """
  6. if not is_hermitian(sparse_operator):
  7. raise ValueError(''sparse_operator must be hermitian.'')
  8.  
  9. values, _ = scipy.sparse.linalg.eigsh(
  10. sparse_operator, maxiter=1e7)
  11.  
  12. gap = abs(values[1] - values[0])
  13. return gap
项目:SamuROI    作者:samuroi    | 项目源码 | 文件源码
  1. def perpedndicular1(v):
  2. """calculate the perpendicular unit vector"""
  3. return numpy.array((-v[1], v[0])) / numpy.linalg.norm((-v[1], v[0]))
项目:SamuROI    作者:samuroi    | 项目源码 | 文件源码
  1. def normalize(v):
  2. return v / numpy.linalg.norm(v)
项目:gail-driver    作者:sisl    | 项目源码 | 文件源码
  1. def expms(A, (np.exp(D) * B).T)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_qr_modes():
  2. rng = numpy.random.RandomState(utt.fetch_seed())
  3.  
  4. A = tensor.matrix("A", dtype=theano.config.floatX)
  5. a = rng.rand(4, 4).astype(theano.config.floatX)
  6.  
  7. f = function([A], qr(A))
  8. t_qr = f(a)
  9. n_qr = numpy.linalg.qr(a)
  10. assert _allclose(n_qr, t_qr)
  11.  
  12. for mode in ["reduced", "r", "raw"]:
  13. f = function([A], qr(A, mode))
  14. t_qr = f(a)
  15. n_qr = numpy.linalg.qr(a, mode)
  16. if isinstance(n_qr, (list, tuple)):
  17. assert _allclose(n_qr[0], t_qr[0])
  18. assert _allclose(n_qr[1], t_qr[1])
  19. else:
  20. assert _allclose(n_qr, t_qr)
  21.  
  22. try:
  23. n_qr = numpy.linalg.qr(a, "complete")
  24. f = function([A], "complete"))
  25. t_qr = f(a)
  26. assert _allclose(n_qr, t_qr)
  27. except TypeError as e:
  28. assert "name ''complete'' is not defined" in str(e)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_svd():
  2. rng = numpy.random.RandomState(utt.fetch_seed())
  3. A = tensor.matrix("A", dtype=theano.config.floatX)
  4. U, T = svd(A)
  5. fn = function([A], [U, T])
  6. a = rng.rand(4, 4).astype(theano.config.floatX)
  7. n_u, n_v, n_t = numpy.linalg.svd(a)
  8. t_u, t_v, t_t = fn(a)
  9.  
  10. assert _allclose(n_u, t_u)
  11. assert _allclose(n_v, t_v)
  12. assert _allclose(n_t, t_t)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_inverse_singular():
  2. singular = numpy.array([[1, 0]] + [[0, 0]] * 2,
  3. dtype=theano.config.floatX)
  4. a = tensor.matrix()
  5. f = function([a], matrix_inverse(a))
  6. try:
  7. f(singular)
  8. except numpy.linalg.LinAlgError:
  9. return
  10. assert False
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_wrong_coefficient_matrix(self):
  2. x = tensor.vector()
  3. y = tensor.vector()
  4. z = tensor.scalar()
  5. b = theano.tensor.nlinalg.lstsq()(x, y, z)
  6. f = function([x, z], b)
  7. self.assertRaises(numpy.linalg.linalg.LinAlgError, f, [2, 1], 1)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_wrong_rcond_dimension(self):
  2. x = tensor.vector()
  3. y = tensor.vector()
  4. z = tensor.vector()
  5. b = theano.tensor.nlinalg.lstsq()(x, b)
  6. self.assertRaises(numpy.linalg.LinAlgError, 1])
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_numpy_compare(self):
  2. rng = numpy.random.RandomState(utt.fetch_seed())
  3. A = tensor.matrix("A", dtype=theano.config.floatX)
  4. Q = matrix_power(A, 3)
  5. fn = function([A], [Q])
  6. a = rng.rand(4, 4).astype(theano.config.floatX)
  7.  
  8. n_p = numpy.linalg.matrix_power(a, 3)
  9. t_p = fn(a)
  10. assert numpy.allclose(n_p, t_p)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_eigvalsh_grad():
  2. if not imported_scipy:
  3. raise SkipTest("Scipy needed for the geigvalsh op.")
  4. import scipy.linalg
  5.  
  6. rng = numpy.random.RandomState(utt.fetch_seed())
  7. a = rng.randn(5, 5)
  8. a = a + a.T
  9. b = 10 * numpy.eye(5, 5) + rng.randn(5, 5)
  10. tensor.verify_grad(lambda a, b: eigvalsh(a, b).dot([1, 5]),
  11. [a, rng=numpy.random)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_solve_correctness(self):
  2. if not imported_scipy:
  3. raise SkipTest("Scipy needed for the Cholesky and Solve ops.")
  4. rng = numpy.random.RandomState(utt.fetch_seed())
  5. A = theano.tensor.matrix()
  6. b = theano.tensor.matrix()
  7. y = self.op(A, b)
  8. gen_solve_func = theano.function([A, y)
  9.  
  10. cholesky_lower = Cholesky(lower=True)
  11. L = cholesky_lower(A)
  12. y_lower = self.op(L, b)
  13. lower_solve_func = theano.function([L, y_lower)
  14.  
  15. cholesky_upper = Cholesky(lower=False)
  16. U = cholesky_upper(A)
  17. y_upper = self.op(U, b)
  18. upper_solve_func = theano.function([U, y_upper)
  19.  
  20. b_val = numpy.asarray(rng.rand(5, 1), dtype=config.floatX)
  21.  
  22. # 1-test general case
  23. A_val = numpy.asarray(rng.rand(5, 5), dtype=config.floatX)
  24. # positive definite matrix:
  25. A_val = numpy.dot(A_val.transpose(), A_val)
  26. assert numpy.allclose(scipy.linalg.solve(A_val, b_val),
  27. gen_solve_func(A_val, b_val))
  28.  
  29. # 2-test lower traingular case
  30. L_val = scipy.linalg.cholesky(A_val, lower=True)
  31. assert numpy.allclose(scipy.linalg.solve_triangular(L_val, b_val, lower=True),
  32. lower_solve_func(L_val, b_val))
  33.  
  34. # 3-test upper traingular case
  35. U_val = scipy.linalg.cholesky(A_val, lower=False)
  36. assert numpy.allclose(scipy.linalg.solve_triangular(U_val, lower=False),
  37. upper_solve_func(U_val, b_val))
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_expm():
  2. if not imported_scipy:
  3. raise SkipTest("Scipy needed for the expm op.")
  4. rng = numpy.random.RandomState(utt.fetch_seed())
  5. A = rng.randn(5, 5).astype(config.floatX)
  6.  
  7. ref = scipy.linalg.expm(A)
  8.  
  9. x = tensor.matrix()
  10. m = expm(x)
  11. expm_f = function([x], m)
  12.  
  13. val = expm_f(A)
  14. numpy.testing.assert_array_almost_equal(val, ref)
项目:neurotools    作者:michaelerule    | 项目源码 | 文件源码
  1. def rcond(x):
  2. ''''''
  3. Reciprocal condition number
  4. ''''''
  5. return 1./np.linalg.cond(x)
项目:neurotools    作者:michaelerule    | 项目源码 | 文件源码
  1. def check_covmat_fast(C,N=None,eps=1e-6):
  2. ''''''
  3. Verify that matrix M is a size NxN precision or covariance matirx
  4. ''''''
  5. if not type(C)==np.ndarray:
  6. raise ValueError("Covariance matrix should be a 2D numpy array")
  7. if not len(C.shape)==2:
  8. raise ValueError("Covariance matrix should be a 2D numpy array")
  9. if N is None:
  10. N = C.shape[0]
  11. if not C.shape==(N,N):
  12. raise ValueError("Expected size %d x %d matrix"%(N,N))
  13. if np.any(~np.isreal(C)):
  14. raise ValueError("Covariance matrices should not contain complex numbers")
  15. C = np.real(C)
  16. if np.any(~np.isfinite(C)):
  17. raise ValueError("Covariance matrix contains NaN or ±inf!")
  18. if not np.all(np.abs(C-C.T)<eps):
  19. raise ValueError("Covariance matrix is not symmetric up to precision %0.1e"%eps)
  20. try:
  21. ch = chol(C)
  22. except numpy.linalg.linalg.LinAlgError:
  23. # Check smallest eigenvalue if cholesky fails
  24. mine = np.real(scipy.linalg.decomp.eigh(C,eigvals=(0,0))[0][0])
  25. if np.any(mine<-eps):
  26. raise ValueError(''Covariance matrix contains eigenvalue %0.3e<%0.3e''%(mine,-eps))
  27. if (mine<eps):
  28. C = C + np.eye(N)*(eps-mine)
  29. C = 0.5*(C+C.T)
  30. return C
项目:neurotools    作者:michaelerule    | 项目源码 | 文件源码
  1. def rsolve(a,b):
  2. ''''''
  3. wraps solve,applies to right hand solution
  4. solves system x A = B
  5. ''''''
  6. return scipy.linalg.solve(b.T,a.T).T
项目:rllab    作者:rll    | 项目源码 | 文件源码
  1. def expms(A, (np.exp(D) * B).T)
项目:rllab    作者:rll    | 项目源码 | 文件源码
  1. def likelihood(x, dx)) / sigma**2 / 2) / s2pi / abs(detC)**0.5 / sigma**n
项目:MachineLearningalgorithm    作者:lining0806    | 项目源码 | 文件源码
  1. def lwlr(testPoint, xMat, yMat, k=1.0):
  2. m = np.shape(xMat)[0]
  3. weights = np.matrix(np.eye(m)) # ??????
  4. for j in range(m):
  5. diffMat = testPoint-xMat[j, :]
  6. weights[j, j] = np.exp(diffMat*diffMat.T/(-2.0*k**2)) # ???
  7. print weights
  8. xTx = xMat.T*(weights*xMat)
  9. if np.linalg.det(xTx) == 0.0:
  10. print ''This matrix is singular,cannot do inverse''
  11. return
  12. ws = xTx.I*(xMat.T*(weights*yMat))
  13. return testPoint*ws
项目:MachineLearningalgorithm    作者:lining0806    | 项目源码 | 文件源码
  1. def ridgeRegres(xMat, lam=0.2):
  2. xTx = xMat.T*xMat
  3. denom = xTx+np.eye(np.shape(xMat)[1])*lam
  4. if np.linalg.det(denom) == 0.0:
  5. print ''This matrix is singular,cannot do inverse''
  6. return
  7. ws = denom.I*(xMat.T*yMat)
  8. return ws
项目:maml_rl    作者:cbfinn    | 项目源码 | 文件源码
  1. def expms(A, (np.exp(D) * B).T)

np.linalg.solve 和 scipy.linalg.cho_solve 之间的性能差距

np.linalg.solve 和 scipy.linalg.cho_solve 之间的性能差距

如何解决np.linalg.solve 和 scipy.linalg.cho_solve 之间的性能差距

我试图通过求解两个涉及 Cholesky 分解的线性方程组来找到 alphascipy 有一个特殊的功能来做到这一点。 scipynumpy 之间存在显着的性能差距。我可以通过任何其他方式在 scipy 中获得与 numpy 一样好的性能吗? (假设我不允许使用 scipy)。

  1. import numpy as np
  2. import scipy
  3. def numpy_cho_solve(N,M):
  4. for seed in range(N):
  5. np.random.seed(seed)
  6. x = np.random.rand(M,1)
  7. y = np.random.rand(M,1)
  8. k = x@x.T + np.eye(M)# M*M
  9. L = np.linalg.cholesky(k)
  10. alpha = np.linalg.solve(L.T,np.linalg.solve(L,y))
  11. def scipy_cho_solve(N,1)
  12. k = x@x.T + np.eye(M)# M*M
  13. L = np.linalg.cholesky(k)
  14. alpha = scipy.linalg.cho_solve((L,True),y)
  15. %timeit numpy_cho_solve(100,100)
  16. %timeit scipy_cho_solve(100,100)

输出

  1. 317 ms ± 12.3 ms per loop (mean ± std. dev. of 7 runs,1 loop each)
  2. 76.9 ms ± 3.12 ms per loop (mean ± std. dev. of 7 runs,10 loops each)

解决方法

考虑到您只能使用 numpy,那么 np.linalg.solve 是求解线性方程的最佳函数,因为它给出了准确的结果。您可以使用 numpy 的 invtranspose 函数,但准确的结果将是 solve 函数。

,

Cholesky 分解方法的前向和后向替换步骤非常快但不可向量化,因此 numpy 无济于事。你需要一个编译函数(如 scipy 实现) - 但如果你不能使用 scipy 我怀疑你可以使用 numba (它通常用于制作 c 编译函数numpy)。

np.linalg.solve 试图通过天真地应用 LU 替换来解决简单的前向替换步骤,因此它比专门构建的函数花费的时间长得多(甚至根本不使用 Cholesky)。

Python numpy.linalg 模块-cholesky() 实例源码

Python numpy.linalg 模块-cholesky() 实例源码

Python numpy.linalg 模块,cholesky() 实例源码

我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用numpy.linalg.cholesky()

项目:RecSys    作者:arvidzt    | 项目源码 | 文件源码
  1. def _udpate_item_features(self):
  2. # Gibbs sampling for item features
  3. for item_id in xrange(self.n_item):
  4. indices = self.ratings_csc_[:, item_id].indices
  5. features = self.user_features_[indices, :]
  6. rating = self.ratings_csc_[:, item_id].data - self.mean_rating_
  7. rating = np.reshape(rating, (rating.shape[0], 1))
  8.  
  9. covar = inv(self.alpha_item +
  10. self.beta * np.dot(features.T, features))
  11. lam = cholesky(covar)
  12.  
  13. temp = (self.beta * np.dot(features.T, rating) +
  14. np.dot(self.alpha_item, self.mu_item))
  15.  
  16. mean = np.dot(covar, temp)
  17. temp_feature = mean + np.dot(
  18. lam, self.rand_state.randn(self.n_feature, 1))
  19. self.item_features_[item_id, :] = temp_feature.ravel()
项目:RecSys    作者:arvidzt    | 项目源码 | 文件源码
  1. def _update_user_features(self):
  2. # Gibbs sampling for user features
  3. for user_id in xrange(self.n_user):
  4. indices = self.ratings_csr_[user_id, :].indices
  5. features = self.item_features_[indices, :]
  6. rating = self.ratings_csr_[user_id, :].data - self.mean_rating_
  7. rating = np.reshape(rating, 1))
  8.  
  9. covar = inv(
  10. self.alpha_user + self.beta * np.dot(features.T, features))
  11. lam = cholesky(covar)
  12. # aplha * sum(V_j * R_ij) + LAMBDA_U * mu_u
  13. temp = (self.beta * np.dot(features.T, rating) +
  14. np.dot(self.alpha_user, self.mu_user))
  15. # mu_i_star
  16. mean = np.dot(covar, 1))
  17. self.user_features_[user_id, :] = temp_feature.ravel()
项目:PyMDNet    作者:HungWei-Andy    | 项目源码 | 文件源码
  1. def solve(A, y, delta, method):
  2. if method == ''ridge_reg_chol'':
  3. R = cholesky(dot(A.T, A) + delta*np.identity(A.shape[1]))
  4. z = lstsq(R.T, dot(A.T, y))[0]
  5. x = lstsq(R, z)[0]
  6. elif method == ''ridge_reg_inv'':
  7. x = dot(dot(inv(dot(A.T, A) + delta*np.identity(A.shape[1])), A.T), y)
  8. elif method == ''ls_mldivide'':
  9. if delta > 0:
  10. print(''ignoring lambda; no regularization used'')
  11. x = lstsq(A, y)[0]
  12. loss = 0.5 * (dot(A, x) - y) **2
  13. return x.reshape(-1, 1)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_lapack_endian(self):
  2. # For bug #1482
  3. a = array([[5.7998084, -2.1825367],
  4. [-2.1825367, 9.85910595]], dtype=''>f8'')
  5. b = array(a, dtype=''<f8'')
  6.  
  7. ap = linalg.cholesky(a)
  8. bp = linalg.cholesky(b)
  9. assert_array_equal(ap, bp)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_lapack_endian(self):
  2. # For bug #1482
  3. a = array([[5.7998084, bp)
项目:PyBGMM    作者:junlulocky    | 项目源码 | 文件源码
  1. def rand_k(self, k):
  2. """
  3. Return a random mean vector and covariance matrix from the posterior
  4. NIW distribution for component `k`.
  5. """
  6. k_N = self.prior.k_0 + self.counts[k]
  7. v_N = self.prior.v_0 + self.counts[k]
  8. m_N = self.m_N_numerators[k]/k_N
  9. S_N = self.S_N_partials[k] - k_N*np.outer(m_N, m_N)
  10. sigma = np.linalg.solve(cholesky(S_N).T, np.eye(self.D)) # don''t understand this step
  11. sigma = wishart.iwishrnd(sigma, v_N, sigma)
  12. mu = np.random.multivariate_normal(m_N, sigma/k_N)
  13. return mu, sigma
项目:RecSys    作者:arvidzt    | 项目源码 | 文件源码
  1. def _update_item_params(self):
  2. N = self.n_item
  3. X_bar = np.mean(self.item_features_, 0).reshape((self.n_feature, 1))
  4. # print ''X_bar'',X_bar.shape
  5. S_bar = np.cov(self.item_features_.T)
  6. # print ''S_bar'',S_bar.shape
  7.  
  8. diff_X_bar = self.mu0_item - X_bar
  9.  
  10. # W_{0}_star
  11. WI_post = inv(inv(self.WI_item) +
  12. N * S_bar +
  13. np.dot(diff_X_bar, diff_X_bar.T) *
  14. (N * self.beta_item) / (self.beta_item + N))
  15.  
  16. # Note: WI_post and WI_post.T should be the same.
  17. # Just make sure it is symmertic here
  18. WI_post = (WI_post + WI_post.T) / 2.0
  19.  
  20. # update alpha_item
  21. df_post = self.df_item + N
  22. self.alpha_item = wishart.rvs(df_post, WI_post, 1, self.rand_state)
  23.  
  24. # update mu_item
  25. mu_mean = (self.beta_item * self.mu0_item + N * X_bar) / \\
  26. (self.beta_item + N)
  27. mu_var = cholesky(inv(np.dot(self.beta_item + N, self.alpha_item)))
  28. # print ''lam'',lam.shape
  29. self.mu_item = mu_mean + np.dot(
  30. mu_var, 1))
  31. # print ''mu_item'',self.mu_item.shape
项目:RecSys    作者:arvidzt    | 项目源码 | 文件源码
  1. def _update_user_params(self):
  2. # same as _update_user_params
  3. N = self.n_user
  4. X_bar = np.mean(self.user_features_, 1))
  5. S_bar = np.cov(self.user_features_.T)
  6.  
  7. # mu_{0} - U_bar
  8. diff_X_bar = self.mu0_user - X_bar
  9.  
  10. # W_{0}_star
  11. WI_post = inv(inv(self.WI_user) +
  12. N * S_bar +
  13. np.dot(diff_X_bar, diff_X_bar.T) *
  14. (N * self.beta_user) / (self.beta_user + N))
  15. # Note: WI_post and WI_post.T should be the same.
  16. # Just make sure it is symmertic here
  17. WI_post = (WI_post + WI_post.T) / 2.0
  18.  
  19. # update alpha_user
  20. df_post = self.df_user + N
  21. # LAMBDA_{U} ~ W(W{0}_star,df_post)
  22. self.alpha_user = wishart.rvs(df_post, self.rand_state)
  23.  
  24. # update mu_user
  25. # mu_{0}_star = (beta_{0} * mu_{0} + N * U_bar) / (beta_{0} + N)
  26. mu_mean = (self.beta_user * self.mu0_user + N * X_bar) / \\
  27. (self.beta_user + N)
  28.  
  29. # decomposed inv(beta_{0}_star * LAMBDA_{U})
  30. mu_var = cholesky(inv(np.dot(self.beta_user + N, self.alpha_user)))
  31. # sample multivariate gaussian
  32. self.mu_user = mu_mean + np.dot(
  33. mu_var, 1))
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_lapack_endian(self):
  2. # For bug #1482
  3. a = array([[5.7998084, bp)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_lapack_endian(self):
  2. # For bug #1482
  3. a = array([[5.7998084, bp)
项目:pyrec    作者:gray0302    | 项目源码 | 文件源码
  1. def wishartrand(nu, phi):
  2. dim = phi.shape[0]
  3. chol = cholesky(phi)
  4. foo = np.zeros((dim, dim))
  5.  
  6. for i in range(dim):
  7. for j in range(i + 1):
  8. if i == j:
  9. foo[i, j] = np.sqrt(chi2.rvs(nu - (i + 1) + 1))
  10. else:
  11. foo[i, j] = np.random.normal(0, 1)
  12. return np.dot(chol, np.dot(foo, np.dot(foo.T, chol.T)))
项目:pyrec    作者:gray0302    | 项目源码 | 文件源码
  1. def mv_normalrand(mu, sigma, size):
  2. lamb = cholesky(sigma)
  3. return mu + np.dot(lamb, np.random.randn(size))
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_lapack_endian(self):
  2. # For bug #1482
  3. a = array([[5.7998084, bp)
项目:markowitz-portfolio-optimization    作者:chaitjo    | 项目源码 | 文件源码
  1. def isPD(B):
  2. """Returns true when input is positive-definite,via Cholesky"""
  3. try:
  4. _ = la.cholesky(B)
  5. return True
  6. except la.LinAlgError:
  7. return False
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_lapack_endian(self):
  2. # For bug #1482
  3. a = array([[5.7998084, bp)
项目:icinco-code    作者:jacobnzw    | 项目源码 | 文件源码
  1. def apply(self, f, mean, cov, pars):
  2. mean = mean[:, na]
  3. # form sigma-points from unit sigma-points
  4. x = mean + cholesky(cov).dot(self.unit_sp)
  5. # push sigma-points through non-linearity
  6. fx = np.apply_along_axis(f, 0, x, pars)
  7. # output mean
  8. mean_f = fx.dot(self.wm)
  9. # output covariance
  10. dfx = fx - mean_f[:, na]
  11. cov_f = dfx.dot(self.Wc).dot(dfx.T)
  12. # input-output covariance
  13. cov_fx = dfx.dot(self.Wc).dot((x - mean).T)
  14. return mean_f, cov_f, cov_fx
项目:icinco-code    作者:jacobnzw    | 项目源码 | 文件源码
  1. def apply(self, pars):
  2. # method defined in terms of abstract private functions for computing mean,covariance and cross-covariance
  3. mean = mean[:, na]
  4. x = mean + cholesky(cov).dot(self.unit_sp)
  5. fx = self._fcn_eval(f, pars)
  6. mean_f = self._mean(self.wm, fx)
  7. cov_f = self._covariance(self.Wc, fx, mean_f)
  8. cov_fx = self._cross_covariance(self.Wcc, mean_f, mean)
  9. return mean_f, cov_fx
项目:segmentalist    作者:kamperh    | 项目源码 | 文件源码
  1. def rand_k(self, sigma
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_lapack_endian(self):
  2. # For bug #1482
  3. a = array([[5.7998084, bp)

Python numpy.linalg 模块-cond() 实例源码

Python numpy.linalg 模块-cond() 实例源码

Python numpy.linalg 模块,cond() 实例源码

我们从Python开源项目中,提取了以下37个代码示例,用于说明如何使用numpy.linalg.cond()

项目:anompy    作者:takuti    | 项目源码 | 文件源码
  1. def aryule(c, k):
  2. """Solve Yule-Walker equation.
  3.  
  4. Args:
  5. c (numpy array): Coefficients (i.e. autocorrelation)
  6. k (int): Assuming the AR(k) model
  7.  
  8. Returns:
  9. numpy array: k model parameters
  10. Some formulations solve: C a = -c,
  11. but we actually solve C a = c.
  12.  
  13. """
  14. a = np.zeros(k)
  15.  
  16. # ignore a singular matrix
  17. C = toeplitz(c[:k])
  18. if not np.all(C == 0.0) and np.isfinite(ln.cond(C)):
  19. a = np.dot(ln.inv(C), c[1:])
  20.  
  21. return a
项目:datadog-anomaly-detector    作者:takuti    | 项目源码 | 文件源码
  1. def aryule(c, c[1:])
  2.  
  3. return a
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def do(self, a, b):
  2. c = asarray(a) # a might be a matrix
  3. s = linalg.svd(c, compute_uv=False)
  4. old_assert_almost_equal(
  5. s[..., 0] / s[..., -1], linalg.cond(a), decimal=5)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_stacked_arrays_explicitly(self):
  2. A = np.array([[1., 2., 1.], [0, -2., 0], [6., 3.]])
  3. assert_equal(linalg.cond(A), linalg.cond(A[None, ...])[0])
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def do(self, linalg.cond(a, 2), 3.]])
  2. assert_equal(linalg.cond(A, ...], 2)[0])
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test(self):
  2. A = array([[1., 0, 3.]])
  3. assert_almost_equal(linalg.cond(A, inf), 3.)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def do(self, decimal=5)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_stacked_arrays_explicitly(self):
  2. A = np.array([[1., ...])[0])
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def do(self, 2)[0])
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test(self):
  2. A = array([[1., 3.)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def do(self, decimal=5)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_stacked_arrays_explicitly(self):
  2. A = np.array([[1., ...])[0])
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def do(self, 2)[0])
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test(self):
  2. A = array([[1., 3.)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def do(self, decimal=5)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_stacked_arrays_explicitly(self):
  2. A = np.array([[1., ...])[0])
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def do(self, 2)[0])
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test(self):
  2. A = array([[1., 3.)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def do(self, decimal=5)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_stacked_arrays_explicitly(self):
  2. A = np.array([[1., ...])[0])
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def do(self, 2)[0])
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test(self):
  2. A = array([[1., 3.)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def do(self, decimal=5)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_stacked_arrays_explicitly(self):
  2. A = np.array([[1., ...])[0])
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def do(self, 2)[0])
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test(self):
  2. A = array([[1., 3.)
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def do(self, decimal=5)
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_stacked_arrays_explicitly(self):
  2. A = np.array([[1., ...])[0])
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def do(self, 2)[0])
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test(self):
  2. A = array([[1., 3.)

Python numpy.linalg 模块-det() 实例源码

Python numpy.linalg 模块-det() 实例源码

Python numpy.linalg 模块,det() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.linalg.det()

项目:bayestsa    作者:thalesians    | 项目源码 | 文件源码
  1. def __call__(self, params):
  2. print ''???'', params
  3. sd1 = params[0]
  4. sd2 = params[1]
  5. cor = params[2]
  6.  
  7. if sd1 < 0. or sd1 > 10. or sd2 < 0. or sd2 > 10. or cor < -1. or cor > 1.:
  8. return np.inf
  9.  
  10. bandwidth = maths.stats.choleskysqrt2d(sd1, sd2, cor)
  11. bandwidthdet = la.det(bandwidth)
  12. bandwidthinv = la.inv(bandwidth)
  13.  
  14. diff = sample[self.__iidx] - sample[self.__jidx]
  15. temp = diff.dot(bandwidthinv.T)
  16. temp *= temp
  17. e = np.exp(np.sum(temp, axis=1))
  18. s = np.sum(e**(-.25) - 4 * e**(-.5))
  19.  
  20. cost = self.__n / bandwidthdet + (2. / bandwidthdet) * s
  21. print ''!!!'', cost
  22. return cost / 10000.
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def do(self, a, b):
  2. d = linalg.det(a)
  3. (s, ld) = linalg.slogdet(a)
  4. if asarray(a).dtype.type in (single, double):
  5. ad = asarray(a).astype(double)
  6. else:
  7. ad = asarray(a).astype(cdouble)
  8. ev = linalg.eigvals(ad)
  9. assert_almost_equal(d, multiply.reduce(ev, axis=-1))
  10. assert_almost_equal(s * np.exp(ld), axis=-1))
  11.  
  12. s = np.atleast_1d(s)
  13. ld = np.atleast_1d(ld)
  14. m = (s != 0)
  15. assert_almost_equal(np.abs(s[m]), 1)
  16. assert_equal(ld[~m], -inf)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_byteorder_check():
  2. # Byte order check should pass for native order
  3. if sys.byteorder == ''little'':
  4. native = ''<''
  5. else:
  6. native = ''>''
  7.  
  8. for dtt in (np.float32, np.float64):
  9. arr = np.eye(4, dtype=dtt)
  10. n_arr = arr.newbyteorder(native)
  11. sw_arr = arr.newbyteorder(''S'').byteswap()
  12. assert_equal(arr.dtype.byteorder, ''='')
  13. for routine in (linalg.inv, linalg.det, linalg.pinv):
  14. # normal call
  15. res = routine(arr)
  16. # Native but not ''=''
  17. assert_array_equal(res, routine(n_arr))
  18. # Swapped
  19. assert_array_equal(res, routine(sw_arr))
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def do(self, -inf)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def do(self, -inf)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_byteorder_check():
  2. # Byte order check should pass for native order
  3. if sys.byteorder == ''little'':
  4. native = ''<''
  5. else:
  6. native = ''>''
  7.  
  8. for dtt in (np.float32, routine(sw_arr))
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def do(self, -inf)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_byteorder_check():
  2. # Byte order check should pass for native order
  3. if sys.byteorder == ''little'':
  4. native = ''<''
  5. else:
  6. native = ''>''
  7.  
  8. for dtt in (np.float32, routine(sw_arr))
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def do(self, -inf)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_byteorder_check():
  2. # Byte order check should pass for native order
  3. if sys.byteorder == ''little'':
  4. native = ''<''
  5. else:
  6. native = ''>''
  7.  
  8. for dtt in (np.float32, routine(sw_arr))
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def do(self, -inf)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_byteorder_check():
  2. # Byte order check should pass for native order
  3. if sys.byteorder == ''little'':
  4. native = ''<''
  5. else:
  6. native = ''>''
  7.  
  8. for dtt in (np.float32, routine(sw_arr))
项目:BigbrotherBot-For-UrT43    作者:ptitbigorneau    | 项目源码 | 文件源码
  1. def F_value_multivariate(ER, EF, dfnum, dfden):
  2. """
  3. Returns an F-statistic given the following:
  4. ER = error associated with the null hypothesis (the Restricted model)
  5. EF = error associated with the alternate hypothesis (the Full model)
  6. dfR = degrees of freedom the Restricted model
  7. dfF = degrees of freedom associated with the Restricted model
  8. where ER and EF are matrices from a multivariate F calculation.
  9. """
  10. if type(ER) in [IntType, FloatType]:
  11. ER = N.array([[ER]])
  12. if type(EF) in [IntType, FloatType]:
  13. EF = N.array([[EF]])
  14. n_um = (LA.det(ER) - LA.det(EF)) / float(dfnum)
  15. d_en = LA.det(EF) / float(dfden)
  16. return n_um / d_en
  17.  
  18. #####################################
  19. ####### ASUPPORT FUNCTIONS ########
  20. #####################################
项目:icinco-code    作者:jacobnzw    | 项目源码 | 文件源码
  1. def _int_var_rbf(self, X, hyp, jitter=1e-8):
  2. """
  3. Posterior integral variance of the Gaussian Process quadrature.
  4. X - vector (1,2*xdim**2+xdim)
  5. hyp - kernel hyperparameters [s2,el_1,... el_d]
  6. """
  7. # reshape X to SP matrix
  8. X = np.reshape(X, (self.n, self.d))
  9. # set kernel hyper-parameters
  10. s2, el = hyp[0], hyp[1:]
  11. self.kern.param_array[0] = s2 # variance
  12. self.kern.param_array[1:] = el # lengthscale
  13. K = self.kern.K(X)
  14. L = np.diag(el ** 2)
  15. # posterior variance of the integral
  16. ks = s2 * np.sqrt(det(L + np.eye(self.d))) * multivariate_normal(mean=np.zeros(self.d), cov=L).pdf(X)
  17. postvar = -ks.dot(solve(K + jitter * np.eye(self.n), ks.T))
  18. return postvar
项目:icinco-code    作者:jacobnzw    | 项目源码 | 文件源码
  1. def _int_var_rbf_hyp(self, jitter=1e-8):
  2. """
  3. Posterior integral variance as a function of hyper-parameters
  4. :param hyp: RBF kernel hyper-parameters [s2,...,el_d]
  5. :param X: sigma-points
  6. :param jitter: numerical jitter (for stabilizing computations)
  7. :return: posterior integral variance
  8. """
  9. # reshape X to SP matrix
  10. X = np.reshape(X, el = 1, hyp # sig_var hyper always set to 1
  11. self.kern.param_array[0] = s2 # variance
  12. self.kern.param_array[1:] = el # lengthscale
  13. K = self.kern.K(X)
  14. L = np.diag(el ** 2)
  15. # posterior variance of the integral
  16. ks = s2 * np.sqrt(det(L + np.eye(self.d))) * multivariate_normal(mean=np.zeros(self.d), cov=L).pdf(X)
  17. postvar = s2 * np.sqrt(det(2 * inv(L) + np.eye(self.d))) ** -1 - ks.dot(
  18. solve(K + jitter * np.eye(self.n), ks.T))
  19. return postvar
项目:TVGL    作者:davidhallac    | 项目源码 | 文件源码
  1. def genCovariace(size):
  2. MaxIter = 1e+6
  3. S = np.zeros((size,size))
  4. itn = 0
  5. while(alg.det(S) <= 1e-3 and itn < MaxIter):
  6. itn = itn + 1
  7. #print int(numpy.log2(size))*size
  8. G6 = GenRndGnm(PUNGraph, size, int((size*(size-1))*0.05))
  9. S = np.zeros((size,size))
  10. for EI in G6.Edges():
  11. S[EI.GetSrcNId(), EI.GetDstNId()] = 0.6
  12. S = S + S.T + S.max()*np.matrix(np.eye(size))
  13. if itn == MaxIter:
  14. print ''fail to find an invertible sparse inverse covariance matrix''
  15. S = np.asarray(S)
  16. return S
项目:TVGL    作者:davidhallac    | 项目源码 | 文件源码
  1. def genCovariace(size):
  2. MaxIter = 1e+6
  3. S = np.zeros((size, int((size*(size-1))*0.05))
  4. #G6 = snap.GenRndGnm(snap.PUNGraph,5,5)
  5. S = np.zeros((size, EI.GetDstNId()] = 0.6
  6. S = S + S.T + S.max()*np.matrix(np.eye(size))
  7. if itn == MaxIter:
  8. print ''fail to find an invertible sparse inverse covariance matrix''
  9. S = np.asarray(S)
  10. return S
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def do(self, -inf)
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_byteorder_check():
  2. # Byte order check should pass for native order
  3. if sys.byteorder == ''little'':
  4. native = ''<''
  5. else:
  6. native = ''>''
  7.  
  8. for dtt in (np.float32, routine(sw_arr))
项目:pybot    作者:spillai    | 项目源码 | 文件源码
  1. def F(self, other):
  2. """
  3. Compute the fundamental matrix with respect to other camera
  4. http://www.robots.ox.ac.uk/~vgg/hzbook/code/vgg_multiview/vgg_F_from_P.m
  5.  
  6. The computed fundamental matrix,given by the formula 17.3 (p. 412) in
  7. Hartley & Zisserman book (2nd ed.).
  8.  
  9. Use as:
  10. F_10 = poses[0].F(poses[1])
  11. l_1 = F_10 * x_0
  12.  
  13. """
  14.  
  15. X1 = self.P[[1,2],:]
  16. X2 = self.P[[2,0],:]
  17. X3 = self.P[[0,1],:]
  18. Y1 = other.P[[1,:]
  19. Y2 = other.P[[2,:]
  20. Y3 = other.P[[0,:]
  21.  
  22. F = np.float64([
  23. [det(np.vstack([X1, Y1])), det(np.vstack([X2, det(np.vstack([X3, Y1]))],
  24. [det(np.vstack([X1, Y2])), Y2]))], Y3])), Y3]))]
  25. ])
  26.  
  27. return F # / F[2,2]
项目:bayestsa    作者:thalesians    | 项目源码 | 文件源码
  1. def __init__(self, density, bandwidth):
  2. self.__density = density
  3. self.__bandwidth = bandwidth
  4. self.__bandwidthinv = la.inv(bandwidth)
  5. self.__bandwidthdet = la.det(bandwidth)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_zero(self):
  2. assert_equal(linalg.det([[0.0]]), 0.0)
  3. assert_equal(type(linalg.det([[0.0]])), double)
  4. assert_equal(linalg.det([[0.0j]]), 0.0)
  5. assert_equal(type(linalg.det([[0.0j]])), cdouble)
  6.  
  7. assert_equal(linalg.slogdet([[0.0]]), (0.0, -inf))
  8. assert_equal(type(linalg.slogdet([[0.0]])[0]), double)
  9. assert_equal(type(linalg.slogdet([[0.0]])[1]), double)
  10. assert_equal(linalg.slogdet([[0.0j]]), (0.0j, -inf))
  11. assert_equal(type(linalg.slogdet([[0.0j]])[0]), cdouble)
  12. assert_equal(type(linalg.slogdet([[0.0j]])[1]), double)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_types(self):
  2. def check(dtype):
  3. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  4. assert_equal(np.linalg.det(x).dtype, dtype)
  5. ph, s = np.linalg.slogdet(x)
  6. assert_equal(s.dtype, get_real_dtype(dtype))
  7. assert_equal(ph.dtype, dtype)
  8. for dtype in [single, double, csingle, cdouble]:
  9. yield check, dtype
项目:electrostatics    作者:tomduck    | 项目源码 | 文件源码
  1. def is_left(x0, x1, x2):
  2. """Returns True if x0 is left of the line between x1 and x2,
  3. False otherwise. Ref: https://stackoverflow.com/questions/1560492"""
  4. assert x1.shape == x2.shape == (2,)
  5. matrix = array([x1-x0, x2-x0])
  6. if len(x0.shape) == 2:
  7. matrix = matrix.transpose((1, 2, 0))
  8. return det(matrix) > 0
项目:CSB    作者:csb-toolBox    | 项目源码 | 文件源码
  1. def log_prob(self, x):
  2.  
  3. from numpy.linalg import det
  4.  
  5. mu = self.mu
  6. S = self.sigma
  7. D = len(mu)
  8. q = self.__q(x)
  9. return -0.5 * (D * log(2 * pi) + log(abs(det(S)))) - 0.5 * q ** 2
项目:CSB    作者:csb-toolBox    | 项目源码 | 文件源码
  1. def rmsd(X, Y):
  2. """
  3. Calculate the root mean squared deviation (RMSD) using Kabsch'' formula.
  4.  
  5. @param X: (n,d) input vector
  6. @type X: numpy array
  7.  
  8. @param Y: (n,d) input vector
  9. @type Y: numpy array
  10.  
  11. @return: rmsd value between the input vectors
  12. @rtype: float
  13. """
  14.  
  15. from numpy import sum, dot, sqrt, clip, average
  16. from numpy.linalg import svd, det
  17.  
  18. X = X - X.mean(0)
  19. Y = Y - Y.mean(0)
  20.  
  21. R_x = sum(X ** 2)
  22. R_y = sum(Y ** 2)
  23.  
  24. V, L, U = svd(dot(Y.T, X))
  25.  
  26. if det(dot(V, U)) < 0.:
  27. L[-1] *= -1
  28.  
  29. return sqrt(clip(R_x + R_y - 2 * sum(L), 0., 1e300) / len(X))
项目:Easy_HMM    作者:tostq    | 项目源码 | 文件源码
  1. def gauss2D(x, mean, cov):
  2. # x,mean,cov??numpy.array??
  3. z = -np.dot(np.dot((x-mean).T,inv(cov)),(x-mean))/2.0
  4. temp = pow(sqrt(2.0*pi),len(x))*sqrt(det(cov))
  5. return (1.0/temp)*exp(z)
项目:Easy_HMM    作者:tostq    | 项目源码 | 文件源码
  1. def emit_prob_updated(self, post_state): # ??????
  2. for k in range(self.n_state):
  3. for j in range(self.x_size):
  4. self.emit_means[k][j] = np.sum(post_state[:,k] *X[:,j]) / np.sum(post_state[:,k])
  5.  
  6. X_cov = np.dot((X-self.emit_means[k]).T, (post_state[:,k]*(X-self.emit_means[k]).T).T)
  7. self.emit_covars[k] = X_cov / np.sum(post_state[:,k])
  8. if det(self.emit_covars[k]) == 0: # ????????
  9. self.emit_covars[k] = self.emit_covars[k] + 0.01*np.eye(len(X[0]))
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_zero(self):
  2. assert_equal(linalg.det([[0.0]]), double)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_types(self):
  2. def check(dtype):
  3. x = np.array([[1, dtype
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_byteorder_check():
  2. # Byte order check should pass for native order
  3. if sys.byteorder == ''little'':
  4. native = ''<''
  5. else:
  6. native = ''>''
  7.  
  8. for dtt in (np.float32, routine(sw_arr))
项目:nusa    作者:JorgeDeLosSantos    | 项目源码 | 文件源码
  1. def V(self):
  2. n1,n2,n3,n4 = self.getNodes()
  3. V = np.array([[1, n1.x, n1.y, n1.z],
  4. [1, n2.x, n2.y, n2.z], n3.x, n3.y, n3.z], n4.x, n4.y, n4.z]])
  5. return la.det(V)/6
项目:astrology    作者:mattsgithub    | 项目源码 | 文件源码
  1. def get_gauss_pdf_value(x, mu, cov):
  2. p = len(mu)
  3. xs = x - mu
  4. covi = inv(cov)
  5. arg = -0.5 * (xs.T).dot(covi.dot(xs))
  6.  
  7. # normalization constant
  8. C = (((2.0 * np.pi)**p)*det(cov))**(-0.5)
  9.  
  10. prob = C * np.exp(arg)
  11. return prob
项目:cgpm    作者:probcomp    | 项目源码 | 文件源码
  1. def calc_log_Z(a, b, V_inv):
  2. # Equation 19.
  3. return gammaln(a) + log(sqrt(1./det(V_inv))) - a * np.log(b)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_zero(self):
  2. assert_equal(linalg.det([[0.0]]), double)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_types(self):
  2. def check(dtype):
  3. x = np.array([[1, dtype
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_zero(self):
  2. assert_equal(linalg.det([[0.0]]), double)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_types(self):
  2. def check(dtype):
  3. x = np.array([[1, dtype
项目:HYDROS    作者:dtold    | 项目源码 | 文件源码
  1. def dispersion_relation_analytical(omega,beta,tau,Tpar_Tperp,kperp,kpar,gam,eta,nb,theta,k):
  2. k2=kperp**2+kpar**2
  3. b=0.5*kperp**2/Tpar_Tperp
  4. inv_kpar=1./kpar
  5. inv_kperp=1./kperp
  6. inv_b=1./b
  7. summand=get_sums_analytical(kperp,omega,nb)
  8. M = 1j*eta*k2*inv_kpar + omega - 0.5*inv_kpar*(1j*eta*kperp**2*inv_kpar+omega)*(summand[6]-summand[5]) + 0.5*(Tpar_Tperp-1.)/Tpar_Tperp*inv_kpar*(summand[8]-summand[7]) + 1j*eta*inv_kpar*(summand[2]-summand[3])
  9. N = 1j/beta*k2*inv_kperp + 1j*omega*inv_kperp*(summand[9]+inv_b*summand[10]-0.5*(summand[6]+3*summand[5])) - 1j*inv_kperp*(Tpar_Tperp-1.)/Tpar_Tperp*(summand[11]+inv_b*summand[12]-0.5*(summand[8]+3*summand[7]))
  10. O = 0.5j*gam/tau*(-inv_kperp*(summand[2]-summand[3]) + 0.5*kperp*inv_kpar*(summand[6]-summand[5]))
  11.  
  12. P = 1j*kpar/beta - 1j*inv_kpar*(1j*eta*kperp**2*inv_kpar+omega)*(summand[9]+inv_b*summand[10]+0.5*(summand[6]-summand[5])) + 1j*inv_kpar*(Tpar_Tperp-1.)/Tpar_Tperp*(summand[11]+inv_b*summand[12]+0.5*(summand[8]-summand[7])) + eta*inv_kpar*(summand[2]+summand[3])
  13. Q = -(1j*eta*k2+omega*kpar)*inv_kperp + 0.5*omega*inv_kperp*(summand[6]-summand[5]) - 0.5*(Tpar_Tperp-1.)/Tpar_Tperp*inv_kperp*(summand[8]-summand[7])
  14. R = -0.5*gam/tau*(inv_kperp*(summand[2]+summand[3]) + kperp*inv_kpar*(summand[9] + inv_b*summand[10] + 0.5*(summand[6]-summand[5])))
  15.  
  16. S = -(1j*eta*kperp**2*inv_kpar+omega)*1j*inv_kperp*inv_kpar*Tpar_Tperp*(summand[0]+summand[1]) + 1j*inv_kpar*inv_kperp*(Tpar_Tperp-1)*(summand[2]+summand[3]) + 2*eta*kperp*inv_kpar*summand[4]
  17. T = -Tpar_Tperp*omega*inv_kperp**2*(summand[0]-summand[1]) + inv_kperp**2*(Tpar_Tperp-1)*(summand[2]-summand[3])
  18. U = -1 - 0.5*gam/tau*(2*summand[4]+Tpar_Tperp*inv_kpar*(summand[0]+summand[1]))
  19.  
  20. global mat
  21. mat=[[M,N,O],[P,Q,R],[S,T,U]]
  22. if det(mat)>1: print(summand[6],-summand[5],file=outfile)
  23. return det(mat)
  24.  
  25.  
  26. #wrapper for analytical or numerical dispersion relation
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_zero(self):
  2. assert_equal(linalg.det([[0.0]]), double)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_types(self):
  2. def check(dtype):
  3. x = np.array([[1, dtype
项目:Umog    作者:hsab    | 项目源码 | 文件源码
  1. def update (self):
  2. pass
  3.  
  4. # def execute(self,refholder):
  5.  
  6. # input_matrix = refholder.matrices[self.inputs[0].links[0].from_socket.matrix_ref]
  7. # answer_matrix = np.zeros(16)
  8.  
  9. # if la.det(input_matrix) == 0:
  10. # print("Matrix has no inverse")
  11. # else:
  12. # answer_matrix = la.inv(input_matrix)
  13.  
  14. # self.outputs[0].matrix_ref = refholder.getRefForMatrix(answer_matrix)
项目:dynesty    作者:joshspeagle    | 项目源码 | 文件源码
  1. def __init__(self, ctr, am):
  2. self.n = len(ctr) # dimension
  3. self.ctr = np.array(ctr) # center coordinates
  4. self.am = np.array(am) # precision matrix (inverse of covariance)
  5.  
  6. # Volume of ellipsoid is the volume of an n-sphere divided
  7. # by the (determinant of the) Jacobian associated with the
  8. # transformation,which by deFinition is the precision matrix.
  9. self.vol = vol_prefactor(self.n) / np.sqrt(linalg.det(self.am))
  10.  
  11. # The eigenvalues (l) of `a` are (a^-2,b^-2,...) where
  12. # (a,b,...) are the lengths of principle axes.
  13. # The eigenvectors (v) are the normalized principle axes.
  14. l, v = linalg.eigh(self.am)
  15. if np.all((l > 0.) & (np.isfinite(l))):
  16. self.axlens = 1. / np.sqrt(l)
  17. else:
  18. raise ValueError("The input precision matrix defining the "
  19. "ellipsoid {0} is apparently singular with "
  20. "l={1} and v={2}.".format(self.am, l, v))
  21.  
  22. # Scaled eigenvectors are the axes,where `axes[:,i]` is the
  23. # i-th axis. Multiplying this matrix by a vector will transform a
  24. # point in the unit n-sphere to a point in the ellipsoid.
  25. self.axes = np.dot(v, np.diag(self.axlens))
  26.  
  27. # Amount by which volume was increased after initialization (i.e.
  28. # cumulative factor from `scale_to_vol`).
  29. self.expand = 1.
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_zero(self):
  2. assert_equal(linalg.det([[0.0]]), double)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_types(self):
  2. def check(dtype):
  3. x = np.array([[1, dtype
项目:mht    作者:jonatanolofsson    | 项目源码 | 文件源码
  1. def correct(self, r):
  2. """Perform correction (measurement) update."""
  3. zhat, H = r.mfn(self.x)
  4. dz = r.z - zhat
  5. S = H @ self.P @ H.T + r.R
  6. SI = inv(S)
  7. K = self.P @ H.T @ SI
  8. self.x += K @ dz
  9. self.P -= K @ H @ self.P
  10.  
  11. score = dz.T @ SI @ dz / 2.0 + ln(2 * pi * sqrt(det(S)))
  12.  
  13. self._calc_bBox()
  14.  
  15. return float(score)
项目:mht    作者:jonatanolofsson    | 项目源码 | 文件源码
  1. def nll(self, r):
  2. """Get the nll score of assigning a measurement to the filter."""
  3. zhat, H = r.mfn(self.x)
  4. dz = r.z - zhat
  5. S = H @ self.P @ H.T + r.R
  6. score = dz.T @ inv(S) @ dz / 2.0 + ln(2 * pi * sqrt(det(S)))
  7. return float(score)
项目:pyabc    作者:neuralyzer    | 项目源码 | 文件源码
  1. def _cov_and_inv(self, n, indices):
  2. """
  3. Calculate covariance around local support vector
  4. and also the inverse
  5. """
  6. cov = self._cov(indices, n)
  7. det = la.det(cov)
  8. while det <= 0:
  9. cov += sp.identity(cov.shape[0]) * self.EPS
  10. det = la.det(cov)
  11. inv_cov = la.inv(cov)
  12. return cov, inv_cov, det
项目:icinco-code    作者:jacobnzw    | 项目源码 | 文件源码
  1. def weights_rbf(self, unit_sp, hypers):
  2. # BQ weights for RBF kernel with given hypers,computations adopted from the GP-ADF code [Deisenroth] with
  3. # the following assumptions:
  4. # (A1) the uncertain input is zero-mean with unit covariance
  5. # (A2) one set of hyper-parameters is used for all output dimensions (one GP models all outputs)
  6. d, n = unit_sp.shape
  7. # GP kernel hyper-parameters
  8. alpha, el, jitter = hypers[''sig_var''], hypers[''lengthscale''], hypers[''noise_var'']
  9. assert len(el) == d
  10. # pre-allocation for convenience
  11. eye_d, eye_n = np.eye(d), np.eye(n)
  12. iLam1 = np.atleast_2d(np.diag(el ** -1)) # sqrt(Lambda^-1)
  13. iLam2 = np.atleast_2d(np.diag(el ** -2))
  14.  
  15. inp = unit_sp.T.dot(iLam1) # sigmas / el[:,na] (x - m)^T*sqrt(Lambda^-1) # (numSP,xdim)
  16. K = np.exp(2 * np.log(alpha) - 0.5 * maha(inp, inp))
  17. iK = cho_solve(cho_factor(K + jitter * eye_n), eye_n)
  18. B = iLam2 + eye_d # (D,D)
  19. c = alpha ** 2 / np.sqrt(det(B))
  20. t = inp.dot(inv(B)) # inn*(P + Lambda)^-1
  21. l = np.exp(-0.5 * np.sum(inp * t, 1)) # (N,1)
  22. zet = 2 * np.log(alpha) - 0.5 * np.sum(inp * inp, 1)
  23. inp = inp.dot(iLam1)
  24. R = 2 * iLam2 + eye_d
  25. t = 1 / np.sqrt(det(R))
  26. L = np.exp((zet[:, na] + zet[:, na].T) + maha(inp, -inp, V=0.5 * inv(R)))
  27. q = c * l # evaluations of the kernel mean map (from the viewpoint of RHKS methods)
  28. # mean weights
  29. wm_f = q.dot(iK)
  30. iKQ = iK.dot(t * L)
  31. # covariance weights
  32. wc_f = iKQ.dot(iK)
  33. # cross-covariance "weights"
  34. wc_fx = np.diag(q).dot(iK)
  35. # used for self.D.dot(x - mean).dot(wc_fx).dot(fx)
  36. self.D = inv(eye_d + np.diag(el ** 2)) # S(S+Lam)^-1; for S=I,(I+Lam)^-1
  37. # model variance; to be added to the covariance
  38. # this diagonal form assumes independent GP outputs (cov(f^a,f^b) = 0 for all a,b: a neq b)
  39. self.model_var = np.diag((alpha ** 2 - np.trace(iKQ)) * np.ones((d, 1)))
  40. return wm_f, wc_f, wc_fx
项目:icinco-code    作者:jacobnzw    | 项目源码 | 文件源码
  1. def weights_rbf(self, V=0.5 * inv(R)))
  2. q = c * l # evaluations of the kernel mean map (from the viewpoint of RHKS methods)
  3. # mean weights
  4. wm_f = q.dot(iK)
  5. iKQ = iK.dot(t * L)
  6. # covariance weights
  7. wc_f = iKQ.dot(iK)
  8. # cross-covariance "weights"
  9. wc_fx = np.diag(q).dot(iK)
  10. self.iK = iK
  11. # used for self.D.dot(x - mean).dot(wc_fx).dot(fx)
  12. self.D = inv(eye_d + np.diag(el ** 2)) # S(S+Lam)^-1; for S=I, wc_fx

我们今天的关于Python numpy 模块-linalg() 实例源码python numpy.linalg的分享就到这里,谢谢您的阅读,如果想了解更多关于np.linalg.solve 和 scipy.linalg.cho_solve 之间的性能差距、Python numpy.linalg 模块-cholesky() 实例源码、Python numpy.linalg 模块-cond() 实例源码、Python numpy.linalg 模块-det() 实例源码的相关信息,可以在本站进行搜索。

本文标签: