numpy.linalg.inv

Here are the examples of the python api numpy.linalg.inv taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: lfd
Source File: PR2.py
View license
    def get_pose_matrix(self, ref_frame, targ_frame):
        self.pr2.update_rave()

        worldFromRef = self.pr2.robot.GetLink(ref_frame).GetTransform()
        worldFromTarg = self.pr2.robot.GetLink(targ_frame).GetTransform()
        refFromTarg = dot(inv(worldFromRef), worldFromTarg)

        return refFromTarg

Example 2

Project: pele
Source File: test_rotations.py
View license
    def test_invert3x3(self):
        q = rotations.random_q()
        mx = rotations.q2mx(q)
        mxi1 = invert3x3(mx)
        mxi2 = np.linalg.inv(mx)
        self.assertEqual(mxi1.shape, mxi2.shape)
        for v1, v2 in izip(mxi1.reshape(-1), mxi2.reshape(-1)):
            self.assertAlmostEqual(v1, v2, places=5)

Example 3

Project: chainer
Source File: det.py
View license
    def backward_cpu(self, x, gy):
        x, = x
        gy, = gy
        try:
            inv_x = numpy.linalg.inv(x.transpose((0, 2, 1)))
        except numpy.linalg.LinAlgError:
            raise ValueError('Input has singular matrices.')
        grad = gy[:, None, None] * self.detx[:, None, None] * inv_x
        return utils.force_array(grad),

Example 4

Project: seisflows
Source File: math.py
View license
def gauss2(X, Y, mu, sigma, normalize=True):
    """ Evaluates Gaussian over points of X,Y
    """
    # evaluates Gaussian over X,Y
    D = sigma[0, 0]*sigma[1, 1] - sigma[0, 1]*sigma[1, 0]
    B = np.linalg.inv(sigma)
    X = X - mu[0]
    Y = Y - mu[1]
    Z = B[0, 0]*X**2. + B[0, 1]*X*Y + B[1, 0]*X*Y + B[1, 1]*Y**2.
    Z = np.exp(-0.5*Z)

    if normalize:
        Z *= (2.*np.pi*np.sqrt(D))**(-1.)

    return Z

Example 5

Project: python-qinfer
Source File: utils.py
View license
def ellipsoid_volume(A=None, invA=None):
    """
    Returns the volume of an ellipsoid given either its
    matrix or the inverse of its matrix.
    """
    
    if invA is None and A is None:
        raise ValueError("Must pass either inverse(A) or A.")
        
    if invA is None and A is not None:
        invA = la.inv(A)
    
    # Find the unit sphere volume.
    # http://en.wikipedia.org/wiki/Unit_sphere#General_area_and_volume_formulas
    n  = invA.shape[0]
    Vn = (np.pi ** (n/2)) / gamma(1 + (n/2))
    
    return Vn * la.det(sqrtm(invA))

Example 6

Project: QuantEcon.py
Source File: test_kalman.py
View license
    def test_stationarity(self):
        A, Q, G, R = self.A, self.Q, self.G, self.R
        kf = self.kf

        sig_inf, kal_gain = kf.stationary_values()

        mat_inv = np.linalg.inv(G.dot(sig_inf).dot(G.T) + R)

        # Compute the kalmain gain and sigma infinity according to the
        # recursive equations and compare
        kal_recursion = np.dot(A, sig_inf).dot(G.T).dot(mat_inv)
        sig_recursion = (A.dot(sig_inf).dot(A.T) -
                            kal_recursion.dot(G).dot(sig_inf).dot(A.T) + Q)

        assert_allclose(kal_gain, kal_recursion, rtol=1e-4, atol=1e-2)
        assert_allclose(sig_inf, sig_recursion, rtol=1e-4, atol=1e-2)

Example 7

Project: tfdeploy
Source File: tfdeploy.py
View license
@Operation.factory(types=("MatrixInverse", "BatchMatrixInverse"))
def MatrixInverse(a):
    """
    Matrix inversion op.
    """
    return np.linalg.inv(a),

Example 8

Project: lfd
Source File: PR2.py
View license
    def look_at(self, xyz_target, reference_frame, camera_frame):
        self.pr2.update_rave()

        worldFromRef = self.pr2.robot.GetLink(reference_frame).GetTransform()
        worldFromCam = self.pr2.robot.GetLink(camera_frame).GetTransform()
        refFromCam = dot(inv(worldFromRef), worldFromCam)        

        xyz_cam = refFromCam[:3,3]
        ax = xyz_target - xyz_cam # pointing axis
        pan = np.arctan(ax[1]/ax[0])
        tilt = np.arcsin(-ax[2] / norm(ax))
        self.set_pan_tilt(pan,tilt)

Example 9

Project: lfd
Source File: util.py
View license
    def inverse(self):
        """
        Returns transformation matrix that is the inverse of this one
        """
        if self.matrix_inv == None:
            self.matrix_inv =  numpy.linalg.inv(self.matrix)
        return Transform(self.matrix_inv)

Example 10

Project: scipy
Source File: _solvers.py
View license
def _solve_discrete_lyapunov_bilinear(a, q):
    """
    Solves the discrete Lyapunov equation using a bilinear transformation.

    This function is called by the `solve_discrete_lyapunov` function with
    `method=bilinear`. It is not supposed to be called directly.
    """
    eye = np.eye(a.shape[0])
    aH = a.conj().transpose()
    aHI_inv = inv(aH + eye)
    b = np.dot(aH - eye, aHI_inv)
    c = 2*np.dot(np.dot(inv(a + eye), q), aHI_inv)
    return solve_lyapunov(b.conj().transpose(), -c)

Example 11

Project: scipy
Source File: test_nonlin.py
View license
    def test_broyden2_update(self):
        # Check that BroydenSecond update works as for a dense matrix
        jac = nonlin.BroydenSecond(alpha=0.1)
        jac.setup(self.xs[0], self.fs[0], None)

        H = np.identity(5) * (-0.1)

        for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])):
            df = f - self.fs[last_j]
            dx = x - self.xs[last_j]
            H += (dx - dot(H, df))[:,None] * df[None,:] / dot(df, df)
            jac.update(x, f)
            assert_(np.allclose(jac.todense(), inv(H), rtol=1e-10, atol=1e-13))

Example 12

Project: scot
Source File: connectivity.py
View license
    @memoize
    def Cinv(self):
        """Inverse of the noise covariance."""
        try:
            return np.linalg.inv(self.c)
        except np.linalg.linalg.LinAlgError:
            print('Warning: non-invertible noise covariance matrix c.')
            return np.eye(self.c.shape[0])

Example 13

Project: sfepy
Source File: shell10x.py
View license
def lock_drilling_rotations(mtx, ebs, coefs):
    """
    Lock the drilling rotations in the stiffness matrix.
    """
    mtx_drl = create_drl_transform(ebs)
    mtx_idrl = nm.linalg.inv(mtx_drl)
    mtx_tr = ddot(ddot(mtx_drl, mtx), mtx_idrl)

    idrl = nm.arange(20, 24)
    mtx_tr[:, idrl, idrl] = coefs[:, None]

    mtx2 = ddot(ddot(mtx_idrl, mtx_tr), mtx_drl)

    return mtx2

Example 14

Project: GPy
Source File: mocap.py
View license
    def set_rotation_matrices(self):
        """Set the meta information at each vertex to contain the correct matrices C and Cinv as prescribed by the rotations and rotation orders."""
        for i in range(len(self.vertices)):
            self.vertices[i].meta['C'] = rotation_matrix(self.vertices[i].meta['axis'][0], 
                                                         self.vertices[i].meta['axis'][1], 
                                                         self.vertices[i].meta['axis'][2], 
                                                         self.vertices[i].meta['axis_order'],
                                                         degrees=True)
            # Todo: invert this by applying angle operations in reverse order
            self.vertices[i].meta['Cinv'] = np.linalg.inv(self.vertices[i].meta['C'])

Example 15

Project: skggm
Source File: estimator_suite.py
View license
def sk_ledoit_wolf(X):
    '''Estimate inverse covariance via scikit-learn ledoit_wolf function.
    '''
    print 'Ledoit-Wolf (sklearn)'
    lw_cov_, _ = ledoit_wolf(X)
    lw_prec_ = np.linalg.inv(lw_cov_)
    return lw_cov_, lw_prec_

Example 16

Project: skggm
Source File: model_average.py
View license
    @property
    def covariance_(self):
        '''Convenience property to make compatible with AdaptiveGraphLasso.
        This is not a very good covariance estimate.
        '''
        return np.linalg.inv(self.support_)

Example 17

Project: skggm
Source File: average_error.py
View license
def _new_graph(n_features, alpha):
    global prng
    prec = make_sparse_spd_matrix(n_features,
                                  alpha=alpha, # prob that a coeff is zero
                                  smallest_coef=0.7,
                                  largest_coef=0.7,
                                  random_state=prng)
    cov = np.linalg.inv(prec)
    d = np.sqrt(np.diag(cov))
    cov /= d
    cov /= d[:, np.newaxis]
    prec *= d
    prec *= d[:, np.newaxis]
    return cov, prec

Example 18

Project: statsmodels
Source File: svar_model.py
View license
    def irf(self, periods=10, var_order=None):
        """
        Analyze structural impulse responses to shocks in system

        Parameters
        ----------
        periods : int

        Returns
        -------
        irf : IRAnalysis
        """
        A = self.A
        B= self.B
        P = np.dot(npl.inv(A), B)

        return IRAnalysis(self, P=P, periods=periods, svar=True)

Example 19

Project: opticspy
Source File: proj3d.py
View license
def inv_transform(xs, ys, zs, M):
    iM = linalg.inv(M)
    vec = vec_pad_ones(xs, ys, zs)
    vecr = np.dot(iM, vec)
    try:
        vecr = vecr/vecr[3]
    except OverflowError:
        pass
    return vecr[0], vecr[1], vecr[2]

Example 20

Project: opticspy
Source File: transferMatrix.py
View license
    def invert(self):
        """
        Inverts matrix

        """
        self.matrix = numpy.linalg.inv(self.matrix)

Example 21

Project: pyNastran
Source File: run_spline.py
View license
def get_WA(nodeList, C, wS, mesh, aero_points):
    log.info('---starting get_WA---')
    #print printMatrix(C)

    C = inv(C) * wS  # Cws matrix, P matrix
    #P = solve(C, wS)
    #C*P=wS
    #P = C^-1*wS

    wA = getXK_Matrix(C, nodeList, mesh, aero_points)
    #wA = xK*C*wS
    log.info('---finished get_WA---')
    sys.stdout.flush()
    return wA

Example 22

Project: control
Source File: ArmBase.py
View license
    def gen_Mx(self, JEE=None, q=None, **kwargs):
        """Generate the mass matrix in operational space"""
        if q is None:
            q = self.q

        Mq = self.gen_Mq(q=q, **kwargs)

        if JEE is None:
            JEE = self.gen_jacEE(q=q)
        Mx_inv = np.dot(JEE, np.dot(np.linalg.inv(Mq), JEE.T))
        u, s, v = np.linalg.svd(Mx_inv)
        # cut off any singular values that could cause control problems
        for i in range(len(s)):
            s[i] = 0 if s[i] < self.singularity_thresh else 1./float(s[i])
        # numpy returns U,S,V.T, so have to transpose both here
        Mx = np.dot(v.T, np.dot(np.diag(s), u.T))

        return Mx

Example 23

Project: svviz
Source File: kde.py
View license
    def _compute_covariance(self):
        self.factor = self.scotts_factor()
        # Cache covariance and inverse covariance of the data
        if not hasattr(self, '_data_inv_cov'):
            self._data_covariance = atleast_2d(np.cov(self.dataset, rowvar=1,
                                               bias=False))
            self._data_inv_cov = linalg.inv(self._data_covariance)

        self.covariance = self._data_covariance * self.factor**2
        self.inv_cov = self._data_inv_cov / self.factor**2
        self._norm_factor = sqrt(linalg.det(2*pi*self.covariance)) * self.n

Example 24

Project: deep_recommend_system
Source File: mvn_test.py
View license
def _compute_non_batch_kl(mu_a, sigma_a, mu_b, sigma_b):
  """Non-batch KL for N(mu_a, sigma_a), N(mu_b, sigma_b)."""
  # Check using numpy operations
  # This mostly repeats the tensorflow code _kl_mvn_mvn(), but in numpy.
  # So it is important to also check that KL(mvn, mvn) = 0.
  sigma_b_inv = np.linalg.inv(sigma_b)

  t = np.trace(sigma_b_inv.dot(sigma_a))
  q = (mu_b - mu_a).dot(sigma_b_inv).dot(mu_b - mu_a)
  k = mu_a.shape[0]
  l = np.log(np.linalg.det(sigma_b) / np.linalg.det(sigma_a))

  return 0.5 * (t + q - k + l)

Example 25

Project: deep_recommend_system
Source File: mvn_test.py
View license
def _compute_non_batch_kl(mu_a, sigma_a, mu_b, sigma_b):
  """Non-batch KL for N(mu_a, sigma_a), N(mu_b, sigma_b)."""
  # Check using numpy operations
  # This mostly repeats the tensorflow code _kl_mvn_mvn(), but in numpy.
  # So it is important to also check that KL(mvn, mvn) = 0.
  sigma_b_inv = np.linalg.inv(sigma_b)

  t = np.trace(sigma_b_inv.dot(sigma_a))
  q = (mu_b - mu_a).dot(sigma_b_inv).dot(mu_b - mu_a)
  k = mu_a.shape[0]
  l = np.log(np.linalg.det(sigma_b) / np.linalg.det(sigma_a))

  return 0.5 * (t + q - k + l)

Example 26

Project: pyBAST
Source File: background.py
View license
def distance(M,N):
    """ Computes Bhattacharyya distance between two distributions
    """
    S = 0.5 * (N.sigma + M.sigma)
    #da = (1./8.) * np.dot( (N.mu-M.mu), solve(S, (N.mu-M.mu).T) )
    da = (1./8.) * np.dot( (N.mu-M.mu), inv(S) ).dot( (N.mu-M.mu).T )
    db = (1./2.) * np.log( det(S) / np.sqrt( N.det*M.det ) )
    return da + db

Example 27

Project: mystic
Source File: scemtools.py
View license
def multinormal_pdf(mean, var):
    """var must be symmetric positive definite """
    import numpy
    vinv = numpy.linalg.inv(var)
    mu = numpy.array(mean).flatten()
    n = len(mu)

    # check that var is properly sized
    dum = numpy.dot(mu,var) - numpy.dot(var,mu)

    prefactor = 1./numpy.sqrt((2 * numpy.pi)**n  * numpy.linalg.det(var))
    def _(x):
        xm = numpy.array(x) - mu
        return prefactor *  numpy.exp(-0.5 * numpy.dot(xm,numpy.dot(vinv,xm)) )
    return _

Example 28

Project: tracer
Source File: boundary_shape.py
View license
    def bounding_rect_for_plane(self, transform):
        """
        Find a rectangle on the xy plane of a given frame, which contains the
        intersection of the boundary shape and the plane.

        Arguments:
        transform - a 4x4 array, the homog. transf. matrix from the global
            coordinates to the frame whose xy plane intersects the boundary
            shape.

        Returns:
        xmin, xmax, ynin, ymax - of the rect, in the xy plane of the frame,
        """
        cent_proj = N.dot(N.linalg.inv(transform), N.append(self._temp_loc, 1))
        Reff = N.sqrt(self._radius**2 - (self._temp_loc[2] - cent_proj[2])**2)
        return cent_proj[0] - Reff, cent_proj[0] + Reff, \
            cent_proj[1] - Reff, cent_proj[1] + Reff

Example 29

Project: tracer
Source File: boundary_shape.py
View license
    def in_bounds(self, vertices):
        """
        Returns a boolean array for whether or not a ray intersection is on the
        positive local Z side of the plane defined by this object's XY plane.

        Arguments:
        vertices - an array of the points to check for inclusion, (n,3)
        """
        local_z = N.dot(N.linalg.inv(self._temp_frame)[2], 
            N.vstack((vertices.T, N.ones(vertices.shape[0]))))
        return local_z >= 0

Example 30

Project: tracer
Source File: cylinder.py
View license
    def _normals(self, verts, dirs):
        # Move to local coordinates
        hit = N.dot(N.linalg.inv(self._working_frame),
            N.vstack((verts.T, N.ones(verts.shape[0]))))
        dir_loc = N.dot(self._working_frame[:3,:3].T, dirs.T)
        
        # The local normal is made from the X,Y components of the vertex:
        local_norm = N.vstack((hit[:2], N.zeros(hit.shape[1])))
        local_norm /= N.sqrt(N.sum(hit[:2]**2, axis=0))
        
        # Choose whether the normal is inside or outside:
        local_norm[:, N.sum(local_norm[:2] * dir_loc[:2], axis=0) > 0] *= -1
        
        # Back to global coordinates:
        return N.dot(self._working_frame[:3,:3], local_norm)

Example 31

Project: gizeh
Source File: gizeh.py
View license
    def draw(self,surface):
        """ Draws the group to a new context of the given Surface """

        for e in self.elements:
            m = self.matrix
            mi = np.linalg.inv(m)
            new_matrix = m.dot(e.matrix)
            e.set_matrix(new_matrix).draw(surface)

Example 32

Project: pyvision
Source File: Affine.py
View license
    def __init__(self,matrix,new_size,interpolate=BILINEAR):
        '''
        Constructor for the AffineTransform.  See also the affine transform factories.
        
        @param matrix: a 3-by-3 matrix that defines the transformation.
        @param new_size: the size of any new images created by this affine transform.
        @param interpolate: the image filtering function used for interpolating between pixels.
        @returns: an AffineTransform object
        '''
        self.matrix = matrix
        self.inverse = inv(matrix)
        self.size = int(new_size[0]),int(new_size[1])
        self.interpolate = interpolate

Example 33

Project: aracna
Source File: SVMStrategy.py
View license
def dummyObjectiveGauss(X, center, ranges):
    '''A Dummy objective that can be used to test learning strategies.

    fitness is 100 * GaussianPdf(mean, cov)
    '''

    covar = diag([((x[1]-x[0])*.2) ** 2 for x in ranges])
    
    cinv = linalg.inv(covar)
    return 100. * exp(-dot(dot((X-center), cinv), (X-center)))

Example 34

Project: refinery
Source File: GaussDistr.py
View license
  def get_covar(self):
    try:
      return self.Cache['invL']
    except KeyError:
      self.Cache['invL'] = np.linalg.inv( self.L )
      return self.Cache['invL']

Example 35

Project: PyIBP
Source File: PyIBP.py
View license
    @staticmethod
    def fromInfo(infoA,hA):
        """ Calculate mean/covar from information """
        covarA = NP.linalg.inv(infoA)
        meanA = NP.dot(covarA,hA)
        return (meanA,covarA)

Example 36

Project: PyIBP
Source File: PyIBP.py
View license
    @staticmethod
    def toInfo(meanA,covarA):
        """ Calculate information from mean/covar """
        infoA = NP.linalg.inv(covarA)
        hA = NP.dot(infoA,meanA)        
        return (infoA,hA)

Example 37

Project: deap
Source File: tools.py
View license
    def __init__(self, matrix):
        if not numpy:
            raise RuntimeError("Numpy is required for using the rotation "
                "decorator")
        # The inverse is taken since the rotation is applied to the individual
        # and not the function which is the inverse
        self.matrix = numpy.linalg.inv(matrix)

Example 38

Project: deap
Source File: tools.py
View license
    def rotate(self, matrix):
        """Set the current rotation to *matrix*. After decorating the
        evaluation function, this function will be available directly from
        the function object. ::
            
            # Create a random orthogonal matrix
            A = numpy.random.random((n,n))
            Q, _ = numpy.linalg.qr(A)
            
            @rotate(Q)
            def evaluate(individual):
                return sum(individual),
            
            # This will reset rotation to identity
            evaluate.rotate(numpy.identity(n))
        """
        self.matrix = numpy.linalg.inv(matrix)

Example 39

Project: tract_querier
Source File: tract_operations.py
View license
def each_tract_in_ijk(image, tractography):
    ijk_tracts = []
    for tract in tractography.tracts():
        ijk_tracts.append(numpy.dot(numpy.linalg.inv(image.get_affine()), numpy.hstack((
            tract,
            numpy.ones((len(tract), 1))
        )).T).T[:, :-1])
    return ijk_tracts

Example 40

Project: tractor
Source File: ellipses.py
View license
    def getTensor(self, cd):
        # G takes unit vectors (in r_e) to degrees (~intermediate world coords)
        G = self.getRaDecBasis()
        # "cd" takes pixels to degrees (intermediate world coords)
        # T takes pixels to unit vectors.
        T = np.dot(np.linalg.inv(G), cd)
        return T

Example 41

Project: tractor
Source File: galaxy.py
View license
    def getTensor(self, cd):
        # G takes unit vectors (in r_e) to degrees (~intermediate world coords)
        G = self.getRaDecBasis()
        # "cd" takes pixels to degrees (intermediate world coords)
        # T takes pixels to unit vectors.
        T = np.dot(np.linalg.inv(G), cd)
        return T

Example 42

Project: tractor
Source File: galaxy.py
View license
    def _getAffineProfile(self, img, px, py):
        ''' Returns a MixtureOfGaussians profile that has been
        affine-transformed into the pixel space of the image.
        '''
        # shift and squash
        cd = img.getWcs().cdAtPixel(px, py)
        galmix = self.getProfile()
        Tinv = np.linalg.inv(self.shape.getTensor(cd))
        amix = galmix.apply_affine(np.array([px,py]), Tinv.T)
        amix.symmetrize()
        return amix

Example 43

Project: conceptors
Source File: feature_net.py
View license
  def compute_conceptor(self,
                        feature_states,
                        ap_N,
                        norm_size):
    """
    @param feature_states: a class of training state
    @param R_all: Correlation matrix for all training states
    @param norm_size: norm size for R_orther_norm;
    """
    
    R=feature_states.dot(feature_states.T);
    R_norm=R/float(feature_states.shape[1]);
    
    C_pos_class=[];
    
    for ap_i in xrange(ap_N):
      C_pos_class.append(R_norm.dot(np.linalg.inv(R_norm+(2**float(ap_i))**(-2)*self.I)));
      
    return C_pos_class, R;

Example 44

Project: conceptors
Source File: feature_net.py
View license
  def compute_pos_conceptor(self,
                            R,
                            ap_pos,
                            norm_size):
    """
    compute positive conceptor
    
    @param R: correlation matrix for the class
    @param ap_pos: learning rate for positive conceptor
    @param norm_size: normalization fator (may not be needed)
    
    @return: positive conceptors 
    """
    R_norm=R/float(norm_size);
    c_pos=R_norm.dot(np.linalg.inv(R_norm + ap_pos ** (-2) * self.I));
    
    return c_pos;

Example 45

Project: conceptors
Source File: logic.py
View license
def conceptor_AND(C, B):
  """
  Logic AND, compute C and B
  
  @param C: a conceptor
  @param B: a conceptor
  """
  
  return np.linalg.inv(np.linalg.inv(C)+np.linalg.inv(B)-np.eye(C.shape[0]));

Example 46

Project: gpustats
Source File: pdfs.py
View license
def mvnpdf(data, means, covs):
    '''
    Compute multivariate normal log pdf

    Parameters
    ----------

    Returns
    -------

    '''
    logdets = [np.log(np.linalg.det(c)) for c in covs]
    ichol_sigmas = [inv(chol(c)) for c in covs]

    packed_params = util.pack_params(means, ichol_sigmas, logdets)
    packed_data = util.pad_data(data)
    return testmod.mvn_call(packed_data, packed_params,
                            data.shape[1])

Example 47

Project: EyeTab
Source File: fit_ellipse_numpy.py
View license
def fit_ellipse_get_coeffs(x,y):
    x = x[:, np.newaxis]
    y = y[:, np.newaxis]
    D = np.hstack((x * x, x * y, y * y, x, y, np.ones_like(x)))
    S = np.dot(D.T, D)
    C = np.zeros([6, 6])
    C[0, 2] = C[2, 0] = 2; C[1, 1] = -1
    E, V = eig(np.dot(inv(S), C))
    n = np.argmax(np.abs(E))
    mat = V[:, n]
    
    return get_coeffs(mat), get_rotated_rect(mat)

Example 48

Project: EyeTab
Source File: fit_ellipse_numpy.py
View license
def fitEllipse(x, y):
    x = x[:, np.newaxis]
    y = y[:, np.newaxis]
    D = np.hstack((x * x, x * y, y * y, x, y, np.ones_like(x)))
    S = np.dot(D.T, D)
    C = np.zeros([6, 6])
    C[0, 2] = C[2, 0] = 2; C[1, 1] = -1
    E, V = eig(np.dot(inv(S), C))
    n = np.argmax(np.abs(E))
    mat = V[:, n]
    
    # make it look like OpenCV rotated rect
    return get_rotated_rect(mat)

Example 49

Project: distributions
Source File: random.py
View license
def score_student_t(x, nu, mu, sigma):
    """
    multivariate score_student_t

    \cite{murphy2007conjugate}, Eq. 313
    """
    p = len(mu)
    z = x - mu
    S = inner(inner(z, inv(sigma)), z)
    score = (
        gammaln(0.5 * (nu + p))
        - gammaln(0.5 * nu)
        - 0.5 * (
            p * log(nu * pi)
            + log(det(sigma))
            + (nu + p) * log(1 + S / nu)
        )
    )
    return score

Example 50

Project: metric-learn
Source File: base_metric.py
View license
  def transformer(self):
    """Computes the transformation matrix from the Mahalanobis matrix.

    L = inv(cholesky(M))

    Returns
    -------
    L : (d x d) matrix
    """
    return inv(cholesky(self.metric()))