當前位置: 首頁>>代碼示例>>Python>>正文


Python numpy.fill_diagonal方法代碼示例

本文整理匯總了Python中numpy.fill_diagonal方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.fill_diagonal方法的具體用法?Python numpy.fill_diagonal怎麽用?Python numpy.fill_diagonal使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在numpy的用法示例。


在下文中一共展示了numpy.fill_diagonal方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _calc_score

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def _calc_score(self, X):

        if isinstance(self.criterion, str):

            if self.criterion == "maxmin":
                D = cdist(X, X)
                np.fill_diagonal(D, np.inf)
                return np.min(D)

            elif self.criterion == "correlation":
                M = np.corrcoef(X.T, rowvar=True)
                return -np.sum(np.tril(M, -1) ** 2)

            else:
                raise Exception("Unknown criterion.")
        elif callable(self.criterion):
            return self.criterion(X)

        else:
            raise Exception("Either provide a str or a function as a criterion!") 
開發者ID:msu-coinlab,項目名稱:pymoo,代碼行數:22,代碼來源:latin_hypercube_sampling.py

示例2: geometric_mean_var

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def geometric_mean_var(z):
    for row in np.eye(z.shape[1]):
        if not np.any(np.all(row == z, axis=1)):
            z = np.row_stack([z, row])
    n_points, n_dim = z.shape

    D = vectorized_cdist(z, z)
    np.fill_diagonal(D, np.inf)

    k = n_dim - 1
    I = D.argsort(axis=1)[:, :k]

    first = np.column_stack([np.arange(n_points) for _ in range(k)])

    val = gmean(D[first, I], axis=1)

    return val.var() 
開發者ID:msu-coinlab,項目名稱:pymoo,代碼行數:19,代碼來源:performance.py

示例3: pyeeg_samp_entropy

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def pyeeg_samp_entropy(X, M, R):
    N = len(X)

    Em = pyeeg_embed_seq(X, 1, M)[:-1]
    A = np.tile(Em, (len(Em), 1, 1))
    B = np.transpose(A, [1, 0, 2])
    D = np.abs(A - B)  # D[i,j,k] = |Em[i][k] - Em[j][k]|
    InRange = np.max(D, axis=2) <= R
    np.fill_diagonal(InRange, 0)  # Don't count self-matches

    Cm = InRange.sum(axis=0)  # Probability that random M-sequences are in range
    Dp = np.abs(np.tile(X[M:], (N - M, 1)) - np.tile(X[M:], (N - M, 1)).T)

    Cmp = np.logical_and(Dp <= R, InRange).sum(axis=0)

    # Avoid taking log(0)
    Samp_En = np.log(np.sum(Cm + 1e-100) / np.sum(Cmp + 1e-100))

    return Samp_En


# =============================================================================
# Entropy
# ============================================================================= 
開發者ID:neuropsychology,項目名稱:NeuroKit,代碼行數:26,代碼來源:tests_complexity.py

示例4: _fit

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def _fit(self):

        # Versions using sparse matrices
        # adj = nx.adjacency_matrix(self._G)
        # ident = sparse.identity(len(self._G.nodes)).tocsc()
        # sim = inv(ident - adj.multiply(self.beta).T) - ident
        # adj = nx.adjacency_matrix(self._G)
        # aux = adj.multiply(-self.beta).T
        # aux.setdiag(1+aux.diagonal(), k=0)
        # sim = inv(aux)
        # sim.setdiag(sim.diagonal()-1)
        # print(sim.nnz)
        # print(adj.nnz)

        # Version using dense matrices
        adj = nx.adjacency_matrix(self._G)
        aux = adj.T.multiply(-self.beta).todense()
        np.fill_diagonal(aux, 1+aux.diagonal())
        sim = np.linalg.inv(aux)
        np.fill_diagonal(sim, sim.diagonal()-1)
        return sim 
開發者ID:Dru-Mara,項目名稱:EvalNE,代碼行數:23,代碼來源:katz.py

示例5: generate_neg_edges

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def generate_neg_edges(G, testing_edges_num, seed=42):
    nnodes = len(G.nodes)
    # Make a full graph (matrix of 1)
    negG = np.ones((nnodes, nnodes))
    np.fill_diagonal(negG, 0.)
    # Substract existing edges from full graph
    # generates negative graph
    original_graph = nx.adj_matrix(G).todense()
    negG = negG - original_graph
    # get negative edges (nonzero entries)
    neg_edges = np.where(negG > 0)
    random.seed(seed) # replicability!
    rng_edges = random.sample(range(neg_edges[0].size), testing_edges_num)
    # return edges in (src, dst) tuple format
    return list(zip(
        neg_edges[0][rng_edges],
        neg_edges[1][rng_edges]
    )) 
開發者ID:VHRanger,項目名稱:nodevectors,代碼行數:20,代碼來源:link_pred.py

示例6: add_noise

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def add_noise(cor, epsilon=None, m=None):
    if isinstance(cor, pd.DataFrame):
        cor = cor.values
    elif isinstance(cor, np.ndarray) is False:
        cor = np.array(cor)

    n = cor.shape[1]

    if epsilon is None:
        epsilon = 0.05
    if m is None:
        m = 2

    np.fill_diagonal(cor, 1 - epsilon)

    cor = SimulateCorrelationMatrix._generate_noise(cor, n, m, epsilon)

    return cor 
開發者ID:aschleg,項目名稱:hypothetical,代碼行數:20,代碼來源:descriptive.py

示例7: constant

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def constant(self):
        delta = np.min(self.rho) - 0.01
        cormat = np.full((self.nkdim, self.nkdim), delta)

        epsilon = 0.99 - np.max(self.rho)
        for i in np.arange(self.k):
            cor = np.full((self.nk[i], self.nk[i]), self.rho[i])

            if i == 0:
                cormat[0:self.nk[0], 0:self.nk[0]] = cor
            if i != 0:
                cormat[np.sum(self.nk[0:i]):np.sum(self.nk[0:i + 1]),
                np.sum(self.nk[0:i]):np.sum(self.nk[0:i + 1])] = cor

        np.fill_diagonal(cormat, 1 - epsilon)

        cormat = self._generate_noise(cormat, self.nkdim, self.M, epsilon)

        return cormat 
開發者ID:aschleg,項目名稱:hypothetical,代碼行數:21,代碼來源:descriptive.py

示例8: toepz

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def toepz(self):
        cormat = np.zeros((self.nkdim, self.nkdim))

        epsilon = (1 - np.max(self.rho)) / (1 + np.max(self.rho)) - .01

        for i in np.arange(self.k):
            t = np.insert(np.power(self.rho[i], np.arange(1, self.nk[i])), 0, 1)
            cor = toeplitz(t)
            if i == 0:
                cormat[0:self.nk[0], 0:self.nk[0]] = cor
            if i != 0:
                cormat[np.sum(self.nk[0:i]):np.sum(self.nk[0:i + 1]),
                np.sum(self.nk[0:i]):np.sum(self.nk[0:i + 1])] = cor

        np.fill_diagonal(cormat, 1 - epsilon)

        cormat = self._generate_noise(cormat, self.nkdim, self.M, epsilon)

        return cormat 
開發者ID:aschleg,項目名稱:hypothetical,代碼行數:21,代碼來源:descriptive.py

示例9: hub

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def hub(self):
        cormat = np.zeros((self.nkdim, self.nkdim))

        for i in np.arange(self.k):
            cor = toeplitz(self._fill_hub_matrix(self.rho[i, 0], self.rho[i, 1], self.power, self.nk[i]))
            if i == 0:
                cormat[0:self.nk[0], 0:self.nk[0]] = cor
            if i != 0:
                cormat[np.sum(self.nk[0:i]):np.sum(self.nk[0:i + 1]),
                np.sum(self.nk[0:i]):np.sum(self.nk[0:i + 1])] = cor
            tau = (np.max(self.rho[i]) - np.min(self.rho[i])) / (self.nk[i] - 2)

        epsilon = 0.08 #(1 - np.min(rho) - 0.75 * np.min(tau)) - 0.01

        np.fill_diagonal(cormat, 1 - epsilon)

        cormat = self._generate_noise(cormat, self.nkdim, self.M, epsilon)

        return cormat 
開發者ID:aschleg,項目名稱:hypothetical,代碼行數:21,代碼來源:descriptive.py

示例10: grad

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def grad(self, inp, cost_grad):
        """
        Notes
        -----
        The gradient is currently implemented for matrices only.

        """
        a, val = inp
        grad = cost_grad[0]
        if (a.dtype.startswith('complex')):
            return [None, None]
        elif a.ndim > 2:
            raise NotImplementedError('%s: gradient is currently implemented'
                                      ' for matrices only' %
                                      self.__class__.__name__)
        wr_a = fill_diagonal(grad, 0)  # valid for any number of dimensions
        # diag is only valid for matrices
        wr_val = theano.tensor.nlinalg.diag(grad).sum()
        return [wr_a, wr_val] 
開發者ID:muhanzhang,項目名稱:D-VAE,代碼行數:21,代碼來源:extra_ops.py

示例11: test_perform

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def test_perform(self):
        x = tensor.matrix()
        y = tensor.scalar()
        f = function([x, y], fill_diagonal(x, y))
        for shp in [(8, 8), (5, 8), (8, 5)]:
            a = numpy.random.rand(*shp).astype(config.floatX)
            val = numpy.cast[config.floatX](numpy.random.rand())
            out = f(a, val)
            # We can't use numpy.fill_diagonal as it is bugged.
            assert numpy.allclose(numpy.diag(out), val)
            assert (out == val).sum() == min(a.shape)

        # test for 3d tensor
        a = numpy.random.rand(3, 3, 3).astype(config.floatX)
        x = tensor.tensor3()
        y = tensor.scalar()
        f = function([x, y], fill_diagonal(x, y))
        val = numpy.cast[config.floatX](numpy.random.rand() + 10)
        out = f(a, val)
        # We can't use numpy.fill_diagonal as it is bugged.
        assert out[0, 0, 0] == val
        assert out[1, 1, 1] == val
        assert out[2, 2, 2] == val
        assert (out == val).sum() == min(a.shape) 
開發者ID:muhanzhang,項目名稱:D-VAE,代碼行數:26,代碼來源:test_extra_ops.py

示例12: perform

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def perform(self, node, inputs, outputs):
        # Kalbfleisch and Lawless, J. Am. Stat. Assoc. 80 (1985) Equation 3.4
        # Kind of... You need to do some algebra from there to arrive at
        # this expression.
        (A, gA) = inputs
        (out,) = outputs
        w, V = scipy.linalg.eig(A, right=True)
        U = scipy.linalg.inv(V).T

        exp_w = numpy.exp(w)
        X = numpy.subtract.outer(exp_w, exp_w) / numpy.subtract.outer(w, w)
        numpy.fill_diagonal(X, exp_w)
        Y = U.dot(V.T.dot(gA).dot(U) * X).dot(V.T)

        with warnings.catch_warnings():
            warnings.simplefilter("ignore", numpy.ComplexWarning)
            out[0] = Y.astype(A.dtype) 
開發者ID:muhanzhang,項目名稱:D-VAE,代碼行數:19,代碼來源:slinalg.py

示例13: test_cov_nearest_factor_homog_sparse

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def test_cov_nearest_factor_homog_sparse(self):

        d = 100

        for dm in 1,2:

            # Construct a test matrix with exact factor structure
            X = np.zeros((d,dm), dtype=np.float64)
            x = np.linspace(0, 2*np.pi, d)
            for j in range(dm):
                X[:,j] = np.sin(x*(j+1))
            mat = np.dot(X, X.T)
            np.fill_diagonal(mat, np.diag(mat) + 3.1)

            # Fit to dense
            rslt = cov_nearest_factor_homog(mat, dm)
            mat1 = rslt.to_matrix()

            # Fit to sparse
            smat = sparse.csr_matrix(mat)
            rslt = cov_nearest_factor_homog(smat, dm)
            mat2 = rslt.to_matrix()

            assert_allclose(mat1, mat2, rtol=0.25, atol=1e-3) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:26,代碼來源:test_corrpsd.py

示例14: __init__

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def __init__(self, one_body, two_body, constant=0.):
        if two_body.dtype != numpy.float:
            raise ValueError('Two-body tensor has invalid dtype. Expected {} '
                             'but was {}'.format(numpy.float, two_body.dtype))
        if not numpy.allclose(two_body, two_body.T):
            raise ValueError('Two-body tensor must be symmetric.')
        if not numpy.allclose(one_body, one_body.T.conj()):
            raise ValueError('One-body tensor must be Hermitian.')

        # Move the diagonal of two_body to one_body
        diag_indices = numpy.diag_indices(one_body.shape[0])
        one_body[diag_indices] += two_body[diag_indices]
        numpy.fill_diagonal(two_body, 0.)

        self.one_body = one_body
        self.two_body = two_body
        self.constant = constant 
開發者ID:quantumlib,項目名稱:OpenFermion,代碼行數:19,代碼來源:_diagonal_coulomb_hamiltonian.py

示例15: LagrangeGaussLobatto

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import fill_diagonal [as 別名]
def LagrangeGaussLobatto(C,xi):
    
    from Florence.QuadratureRules import GaussLobattoQuadrature

    n = C+2
    ranger = np.arange(n)

    eps = GaussLobattoQuadrature(n)[0][:,0]

    A = np.zeros((n,n))
    A[:,0] = 1.
    for i in range(1,n):
        A[:,i] = eps**i
    # A1[:,1:] = np.array([eps**i for i in range(1,n)]).T[0,:,:]


    RHS = np.zeros((n,n))
    np.fill_diagonal(RHS,1)
    coeff = np.linalg.solve(A,RHS)
    xis = np.ones(n)*xi**ranger
    N = np.dot(coeff.T,xis)
    # dN = np.einsum('i,ij,i',1+ranger[:-1],coeff[1:,:],xis[:-1])
    dN = np.dot(coeff[1:,:].T,xis[:-1]*(1+ranger[:-1]))

    return (N,dN,eps) 
開發者ID:romeric,項目名稱:florence,代碼行數:27,代碼來源:Line.py


注:本文中的numpy.fill_diagonal方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。