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


Python numpy.flatnonzero方法代碼示例

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


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

示例1: get_clusters

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def get_clusters(C):
    nonassigned = list(range(len(C)))
    clusters = []
    while nonassigned:
        queue = {nonassigned[0]}
        clusters.append([])
        while queue:
            node = queue.pop()
            clusters[-1].append(node)
            nonassigned.remove(node)
            queue.update(n for n in np.flatnonzero(C[node]) if n in nonassigned)
    C = np.zeros_like(C)
    for cluster in clusters:
        for i in cluster:
            C[i, cluster] = True
    return clusters, C 
開發者ID:jhrmnn,項目名稱:pyberny,代碼行數:18,代碼來源:coords.py

示例2: pinv

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def pinv(A, log=lambda _: None):
    U, D, V = np.linalg.svd(A)
    thre = 1e3
    thre_log = 1e8
    gaps = D[:-1] / D[1:]
    try:
        n = np.flatnonzero(gaps > thre)[0]
    except IndexError:
        n = len(gaps)
    else:
        gap = gaps[n]
        if gap < thre_log:
            log('Pseudoinverse gap of only: {:.1e}'.format(gap))
    D[n + 1 :] = 0
    D[: n + 1] = 1 / D[: n + 1]
    return U.dot(np.diag(D)).dot(V) 
開發者ID:jhrmnn,項目名稱:pyberny,代碼行數:18,代碼來源:Math.py

示例3: _minor_reduce

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def _minor_reduce(self, ufunc):
        """Reduce nonzeros with a ufunc over the minor axis when non-empty

        Warning: this does not call sum_duplicates()

        Returns
        -------
        major_index : array of ints
            Major indices where nonzero

        value : array of self.dtype
            Reduce result for nonzeros in each major_index
        """
        major_index = np.flatnonzero(np.diff(self.indptr))
        value = ufunc.reduceat(self.data,
                               downcast_intp_index(self.indptr[major_index]))
        return major_index, value

    #######################
    # Getting and Setting #
    ####################### 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:23,代碼來源:compressed.py

示例4: test_incidence2

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def test_incidence2():
    # Check that the cumulative incidence functions for all competing
    # risks sum to the complementary survival function.

    np.random.seed(2423)
    n = 200
    time = -np.log(np.random.uniform(size=n))
    status = np.random.randint(0, 3, size=n)
    ii = np.argsort(time)
    time = time[ii]
    status = status[ii]
    ci = CumIncidenceRight(time, status)
    statusa = 1*(status >= 1)
    sf = SurvfuncRight(time, statusa)
    x = 1 - sf.surv_prob
    y = (ci.cinc[0] + ci.cinc[1])[np.flatnonzero(statusa)]
    assert_allclose(x, y) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:19,代碼來源:test_survfunc.py

示例5: vb_elbo_grad

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def vb_elbo_grad(self, vb_mean, vb_sd):
        """
        Returns the gradient of the model's evidence lower bound (ELBO).
        """

        fep_mean, vcp_mean, vc_mean = self._unpack(vb_mean)
        fep_sd, vcp_sd, vc_sd = self._unpack(vb_sd)
        tm, tv = self._lp_stats(fep_mean, fep_sd, vc_mean, vc_sd)

        def h(z):
            u = tm + np.sqrt(tv)*z
            x = np.zeros_like(u)
            ii = np.flatnonzero(u > 0)
            uu = u[ii]
            x[ii] = 1 / (1 + np.exp(-uu))
            ii = np.flatnonzero(u <= 0)
            uu = u[ii]
            x[ii] = np.exp(uu) / (1 + np.exp(uu))
            return -x

        return self.vb_elbo_grad_base(
            h, tm, tv, fep_mean, vcp_mean, vc_mean, fep_sd, vcp_sd, vc_sd) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:24,代碼來源:bayes_mixed_glm.py

示例6: covariance_matrix

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def covariance_matrix(self, endog_expval, index):

        if self.grid:
            return self.covariance_matrix_grid(endog_expval, index)

        j1, j2 = np.tril_indices(len(endog_expval))
        dx = np.abs(self.time[index][j1] - self.time[index][j2])
        ii = np.flatnonzero((0 < dx) & (dx <= self.max_lag))
        j1 = j1[ii]
        j2 = j2[ii]
        dx = dx[ii]

        cmat = np.eye(len(endog_expval))
        cmat[j1, j2] = self.dep_params[dx - 1]
        cmat[j2, j1] = self.dep_params[dx - 1]
        return cmat, True 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:18,代碼來源:cov_struct.py

示例7: test_default_time

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def test_default_time(self):
        # Check that the time defaults work correctly.

        endog, exog, group = load_data("gee_logistic_1.csv")

        # Time values for the autoregressive model
        T = np.zeros(len(endog))
        idx = set(group)
        for ii in idx:
            jj = np.flatnonzero(group == ii)
            T[jj] = lrange(len(jj))

        family = Binomial()
        va = Autoregressive()

        md1 = GEE(endog, exog, group, family=family, cov_struct=va)
        mdf1 = md1.fit()

        md2 = GEE(endog, exog, group, time=T, family=family,
                  cov_struct=va)
        mdf2 = md2.fit()

        assert_almost_equal(mdf1.params, mdf2.params, decimal=6)
        assert_almost_equal(mdf1.standard_errors(),
                            mdf2.standard_errors(), decimal=6) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:27,代碼來源:test_gee.py

示例8: update_data

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def update_data(self):
        """
        Gibbs update of the missing data values.
        """

        for ix in self.patterns:

            i = ix[0]
            ix_miss = np.flatnonzero(self.mask[i, :])
            ix_obs = np.flatnonzero(~self.mask[i, :])

            mm = self.mean[ix_miss]
            mo = self.mean[ix_obs]

            voo = self.cov[ix_obs, :][:, ix_obs]
            vmm = self.cov[ix_miss, :][:, ix_miss]
            vmo = self.cov[ix_miss, :][:, ix_obs]

            r = self.data[ix, :][:, ix_obs] - mo
            cm = mm + np.dot(vmo, np.linalg.solve(voo, r.T)).T
            cv = vmm - np.dot(vmo, np.linalg.solve(voo, vmo.T))

            cs = np.linalg.cholesky(cv)
            u = np.random.normal(size=(len(ix), len(ix_miss)))
            self.data[np.ix_(ix, ix_miss)] = cm + np.dot(u, cs.T) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:27,代碼來源:bayes_mi.py

示例9: transform

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def transform(self, X):
        """Transform X.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)

        Returns
        -------
        X_new : array-like, shape (n_samples, n_components)
        """
        check_is_fitted(self, 'X_fit_')

        # Compute centered gram matrix between X and training data X_fit_
        K = self._centerer.transform(self._get_kernel(X, self.X_fit_))

        # scale eigenvectors (properly account for null-space for dot product)
        non_zeros = np.flatnonzero(self.lambdas_)
        scaled_alphas = np.zeros_like(self.alphas_)
        scaled_alphas[:, non_zeros] = (self.alphas_[:, non_zeros]
                                       / np.sqrt(self.lambdas_[non_zeros]))

        # Project with a scalar product between K and the scaled eigenvectors
        return np.dot(K, scaled_alphas) 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:26,代碼來源:kernel_pca.py

示例10: get_data_by_id

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def get_data_by_id(self, ids):
        """  Helper for getting current data values from stored identifiers
        :param float|list ids: ids for which data are requested
        :return: the stored ids
        :rtype: np.ndarray
        """
        if self.ids is None:
            raise ValueError("IDs not stored in node {}".format(self.name))
        if self.data is None:
            raise ValueError("No data in node {}".format(self.name))
        ids = np.array(ids, ndmin=1, copy=False)
        found_items = np.in1d(ids, self.ids)
        if not np.all(found_items):
            raise ValueError("Cannot find {} among {}".format(ids[np.logical_not(found_items)],
                                                              self.name))
        idx = np.empty(len(ids), dtype='int')
        for k, this_id in enumerate(ids):
            if self.ids.ndim > 1:
                idx[k] = np.flatnonzero(np.all(self.ids == this_id, axis=1))[0]
            else:
                idx[k] = np.flatnonzero(self.ids == this_id)[0]
        return np.array(self.data, ndmin=1)[idx] 
開發者ID:Knewton,項目名稱:edm2016,代碼行數:24,代碼來源:node.py

示例11: subset_test

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def subset_test(lin_op):
        """ Test that subsetting a linear operator produces the correct outputs.
        :param LinearOperator lin_op: the linear operator
        """
        sub_idx = np.random.rand(lin_op.shape[0], 1) > 0.5
        # make sure at least one element included
        sub_idx[np.random.randint(0, len(sub_idx))] = True
        sub_idx = np.flatnonzero(sub_idx)
        sub_lin_op = undertest.get_subset_lin_op(lin_op, sub_idx)

        # test projection to subset of indices
        x = np.random.randn(lin_op.shape[1], np.random.randint(1, 3))
        np.testing.assert_array_almost_equal(sub_lin_op * x, (lin_op * x)[sub_idx, :])

        # test back projection from subset of indices
        y = np.random.randn(len(sub_idx), np.random.randint(1, 3))
        z = np.zeros((lin_op.shape[0], y.shape[1]))
        z[sub_idx] = y
        np.testing.assert_array_almost_equal(sub_lin_op.rmatvec(y), lin_op.rmatvec(z)) 
開發者ID:Knewton,項目名稱:edm2016,代碼行數:21,代碼來源:test_linear_operators.py

示例12: test_get_data_by_id

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def test_get_data_by_id(self):
        dim, data, cpd, ids = self.gen_data()
        node = undertest.Node(name='test node', data=data, cpd=cpd, ids=ids)
        # test setting of ids
        np.testing.assert_array_equal(node.ids, ids)
        # test for one id
        idx = np.random.randint(0, dim)
        np.testing.assert_array_equal(node.get_data_by_id(ids[idx]).ravel(), node.data[idx])
        # test for a random set of ids
        ids_subset = np.random.choice(ids, dim, replace=True)
        np.testing.assert_array_equal(node.get_data_by_id(ids_subset),
                                      [node.data[np.flatnonzero(ids == x)[0]] for x in ids_subset])
        # test for all ids
        self.assertEqual(node.get_all_data_and_ids(), {x: node.get_data_by_id(x) for x in ids})
        # test when data are singleton
        dim, _, cpd, ids = self.gen_data(dim=1)
        node = undertest.Node(name='test node', data=1, cpd=cpd, ids=ids)
        self.assertEqual(node.get_all_data_and_ids(), {x: node.get_data_by_id(x) for x in ids}) 
開發者ID:Knewton,項目名稱:edm2016,代碼行數:20,代碼來源:test_node.py

示例13: fill_nan

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def fill_nan(data):
    """
    Returns the timeseries where any gaps (represented by NaN) are
    filled, using a linear approximation between the neighbors.
    Gaps at the beginning or end are filled with the first resp. last
    valid entry

    :param data: The timeseries data as a numeric sequence
    :return: The filled timeseries as array
    """
    # All data indices
    x = np.arange(len(data))
    # Valid data indices
    xp = np.flatnonzero(np.isfinite(data))
    # Valid data
    fp = remove_nan(data)
    # Interpolate missing values
    return np.interp(x, xp, fp) 
開發者ID:thouska,項目名稱:spotpy,代碼行數:20,代碼來源:signatures.py

示例14: computeNonzeroRows

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def computeNonzeroRows(S, Nl = 'all'):
    """
    computeNonzeroRows: Find the position of the nonzero elements of each
        row of a matrix

    Input:

        S (np.array): matrix
        Nl (int or 'all'): number of rows to compute the nonzero elements; if
            'all', then Nl = S.shape[0]. Rows are counted from the top.

    Output:

        nonzeroElements (list): list of size Nl where each element is an array
            of the indices of the nonzero elements of the corresponding row.
    """
    # Find the position of the nonzero elements of each row of the matrix S.
    # Nl = 'all' means for all rows, otherwise, it will be an int.
    if Nl == 'all':
        Nl = S.shape[0]
    assert Nl <= S.shape[0]
    # Save neighborhood variable
    neighborhood = []
    # For each of the selected nodes
    for n in range(Nl):
        neighborhood += [np.flatnonzero(S[n,:])]

    return neighborhood 
開發者ID:alelab-upenn,項目名稱:graph-neural-networks,代碼行數:30,代碼來源:graphTools.py

示例15: _one_sample_positive_class_precisions

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import flatnonzero [as 別名]
def _one_sample_positive_class_precisions(self, scores, truth):
        """Calculate precisions for each true class for a single sample.
        Args:
          scores: np.array of (num_classes,) giving the individual classifier scores.
          truth: np.array of (num_classes,) bools indicating which classes are true.
        Returns:
          pos_class_indices: np.array of indices of the true classes for this sample.
          pos_class_precisions: np.array of precisions corresponding to each of those
            classes.
        """
        num_classes = scores.shape[0]
        pos_class_indices = np.flatnonzero(truth > 0)
        # Only calculate precisions if there are some true classes.
        if not len(pos_class_indices):
            return pos_class_indices, np.zeros(0)
        # Retrieval list of classes for this sample.
        retrieved_classes = np.argsort(scores)[::-1]
        # class_rankings[top_scoring_class_index] == 0 etc.
        class_rankings = np.zeros(num_classes, dtype=np.int)
        class_rankings[retrieved_classes] = range(num_classes)
        # Which of these is a true label?
        retrieved_class_true = np.zeros(num_classes, dtype=np.bool)
        retrieved_class_true[class_rankings[pos_class_indices]] = True
        # Num hits for every truncated retrieval list.
        retrieved_cumulative_hits = np.cumsum(retrieved_class_true)
        # Precision of retrieval list truncated at each hit, in order of pos_labels.
        precision_at_hits = (
                retrieved_cumulative_hits[class_rankings[pos_class_indices]] /
                (1 + class_rankings[pos_class_indices].astype(np.float)))
        return pos_class_indices, precision_at_hits 
開發者ID:lRomul,項目名稱:argus-freesound,代碼行數:32,代碼來源:metrics.py


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