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


Python distance.pdist方法代碼示例

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


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

示例1: kernel_matrix

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def kernel_matrix(svm_model, original_X):

        if (svm_model.svm_kernel == 'polynomial_kernel' or svm_model.svm_kernel == 'soft_polynomial_kernel'):
            K = (svm_model.zeta + svm_model.gamma * np.dot(original_X, original_X.T)) ** svm_model.Q
        elif (svm_model.svm_kernel == 'gaussian_kernel' or svm_model.svm_kernel == 'soft_gaussian_kernel'):
            pairwise_dists = squareform(pdist(original_X, 'euclidean'))
            K = np.exp(-svm_model.gamma * (pairwise_dists ** 2))

        '''
        K = np.zeros((svm_model.data_num, svm_model.data_num))

        for i in range(svm_model.data_num):
            for j in range(svm_model.data_num):
                if (svm_model.svm_kernel == 'polynomial_kernel' or svm_model.svm_kernel == 'soft_polynomial_kernel'):
                    K[i, j] = Kernel.polynomial_kernel(svm_model, original_X[i], original_X[j])
                elif (svm_model.svm_kernel == 'gaussian_kernel' or svm_model.svm_kernel == 'soft_gaussian_kernel'):
                    K[i, j] = Kernel.gaussian_kernel(svm_model, original_X[i], original_X[j])
        '''

        return K 
開發者ID:fukuball,項目名稱:fuku-ml,代碼行數:22,代碼來源:Utility.py

示例2: k_nearest_neighbor

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def k_nearest_neighbor(self, sequence):
        # Calculate dist_matrix
        dist_array = pdist(sequence)
        dist_matrix = squareform(dist_array)
        # Construct tour
        new_sequence = [sequence[0]]
        current_city = 0
        visited_cities = [0]
        for i in range(1,len(sequence)):
            j = np.random.randint(0,min(len(sequence)-i,self.kNN))
            next_city = [index for index in dist_matrix[current_city].argsort() if index not in visited_cities][j]
            visited_cities.append(next_city)
            new_sequence.append(sequence[next_city])
            current_city = next_city
        return np.asarray(new_sequence)


    # Generate random TSP-TW instance 
開發者ID:MichelDeudon,項目名稱:neural-combinatorial-optimization-rl-tensorflow,代碼行數:20,代碼來源:dataset.py

示例3: coords2sort_order

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def coords2sort_order(a2c):
  """ Delivers a list of atom indices which generates a near-diagonal overlap for a given set of atom coordinates """
  na  = a2c.shape[0]
  aa2d = squareform(pdist(a2c))
  mxd = np.amax(aa2d)+1.0
  a = 0
  lsa = []
  for ia in range(na):
    lsa.append(a)
    asrt = np.argsort(aa2d[a])
    for ja in range(1,na):
      b = asrt[ja]
      if b not in lsa: break
    aa2d[a,b] = aa2d[b,a] = mxd
    a = b
  return np.array(lsa) 
開發者ID:pyscf,項目名稱:pyscf,代碼行數:18,代碼來源:coords2sort_order.py

示例4: vote

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def vote(vec, tol):
    vec = np.sort(vec)
    n = np.arange(len(vec))[::-1]
    n = n[:, None] - n[None, :] + 1.0
    l = squareform(pdist(vec[:, None], 'minkowski', p=1) + 1e-9)

    invalid = (n < len(vec) * 0.4) | (l > tol)
    if (~invalid).sum() == 0 or len(vec) < tol:
        best_fit = np.median(vec)
        p_score = 0
    else:
        l[invalid] = 1e5
        n[invalid] = -1
        score = n
        max_idx = score.argmax()
        max_row = max_idx // len(vec)
        max_col = max_idx % len(vec)
        assert max_col > max_row
        best_fit = vec[max_row:max_col+1].mean()
        p_score = (max_col - max_row + 1) / len(vec)

    l1_score = np.abs(vec - best_fit).mean()

    return best_fit, p_score, l1_score 
開發者ID:sunset1995,項目名稱:HorizonNet,代碼行數:26,代碼來源:post_proc.py

示例5: _get_sorted_db_keypoint_distances

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def _get_sorted_db_keypoint_distances(self, N=None):
        """Use a minimum spanning tree heuristic to find the N largest gaps in the
        line constituted by the current decision boundary keypoints.
        """
        if N == None:
            N = self.n_interpolated_keypoints
        edges = minimum_spanning_tree(
            squareform(pdist(self.decision_boundary_points_2d))
        )
        edged = np.array(
            [
                euclidean(
                    self.decision_boundary_points_2d[u],
                    self.decision_boundary_points_2d[v],
                )
                for u, v in edges
            ]
        )
        gap_edge_idx = np.argsort(edged)[::-1][: int(N)]
        edges = edges[gap_edge_idx]
        gap_distances = np.square(edged[gap_edge_idx])
        gap_probability_scores = gap_distances / np.sum(gap_distances)
        return edges, gap_distances, gap_probability_scores 
開發者ID:tmadl,項目名稱:highdimensional-decision-boundary-plot,代碼行數:25,代碼來源:decisionboundaryplot.py

示例6: _execute_single

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def _execute_single(cls, ctx, op):
        from scipy.spatial.distance import pdist

        inputs, device_id, xp = as_same_device(
            [ctx[inp.key] for inp in op.inputs], device=op.device, ret_extra=True)

        if xp is cp:  # pragma: no cover
            raise NotImplementedError('`pdist` does not support running on GPU yet')

        with device(device_id):
            inputs_iter = iter(inputs)
            x = next(inputs_iter)
            kw = dict()
            if op.p is not None:
                kw['p'] = op.p
            if op.w is not None:
                kw['w'] = next(inputs_iter)
            if op.v is not None:
                kw['V'] = next(inputs_iter)
            if op.vi is not None:
                kw['VI'] = next(inputs_iter)

        ctx[op.outputs[0].key] = pdist(x, metric=op.metric, **kw) 
開發者ID:mars-project,項目名稱:mars,代碼行數:25,代碼來源:pdist.py

示例7: single

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def single(y):
    """
    Perform single/min/nearest linkage on the condensed distance matrix ``y``.

    Parameters
    ----------
    y : ndarray
        The upper triangular of the distance matrix. The result of
        ``pdist`` is returned in this form.

    Returns
    -------
    Z : ndarray
        The linkage matrix.

    See Also
    --------
    linkage: for advanced creation of hierarchical clusterings.
    scipy.spatial.distance.pdist : pairwise distance metrics

    """
    return linkage(y, method='single', metric='euclidean') 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:24,代碼來源:hierarchy.py

示例8: complete

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def complete(y):
    """
    Perform complete/max/farthest point linkage on a condensed distance matrix.

    Parameters
    ----------
    y : ndarray
        The upper triangular of the distance matrix. The result of
        ``pdist`` is returned in this form.

    Returns
    -------
    Z : ndarray
        A linkage matrix containing the hierarchical clustering. See
        the `linkage` function documentation for more information
        on its structure.

    See Also
    --------
    linkage: for advanced creation of hierarchical clusterings.
    scipy.spatial.distance.pdist : pairwise distance metrics

    """
    return linkage(y, method='complete', metric='euclidean') 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:26,代碼來源:hierarchy.py

示例9: average

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def average(y):
    """
    Perform average/UPGMA linkage on a condensed distance matrix.

    Parameters
    ----------
    y : ndarray
        The upper triangular of the distance matrix. The result of
        ``pdist`` is returned in this form.

    Returns
    -------
    Z : ndarray
        A linkage matrix containing the hierarchical clustering. See
        `linkage` for more information on its structure.

    See Also
    --------
    linkage: for advanced creation of hierarchical clusterings.
    scipy.spatial.distance.pdist : pairwise distance metrics

    """
    return linkage(y, method='average', metric='euclidean') 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:25,代碼來源:hierarchy.py

示例10: single

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def single(y):
    """
    Performs single/min/nearest linkage on the condensed distance matrix ``y``

    Parameters
    ----------
    y : ndarray
        The upper triangular of the distance matrix. The result of
        ``pdist`` is returned in this form.

    Returns
    -------
    Z : ndarray
        The linkage matrix.

    See Also
    --------
    linkage: for advanced creation of hierarchical clusterings.

    """
    return linkage(y, method='single', metric='euclidean') 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:23,代碼來源:hierarchy.py

示例11: complete

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def complete(y):
    """
    Performs complete/max/farthest point linkage on a condensed distance matrix

    Parameters
    ----------
    y : ndarray
        The upper triangular of the distance matrix. The result of
        ``pdist`` is returned in this form.

    Returns
    -------
    Z : ndarray
        A linkage matrix containing the hierarchical clustering. See
        the ``linkage`` function documentation for more information
        on its structure.

    See Also
    --------
    linkage

    """
    return linkage(y, method='complete', metric='euclidean') 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:25,代碼來源:hierarchy.py

示例12: average

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def average(y):
    """
    Performs average/UPGMA linkage on a condensed distance matrix

    Parameters
    ----------
    y : ndarray
        The upper triangular of the distance matrix. The result of
        ``pdist`` is returned in this form.

    Returns
    -------
    Z : ndarray
        A linkage matrix containing the hierarchical clustering. See
        the ``linkage`` function documentation for more information
        on its structure.

    See Also
    --------
    linkage: for advanced creation of hierarchical clusterings.

    """
    return linkage(y, method='average', metric='euclidean') 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:25,代碼來源:hierarchy.py

示例13: _build_kernel

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def _build_kernel(x, kernel, gamma=None):

    if kernel in {'pearson', 'spearman'}:
        if kernel == 'spearman':
            x = np.apply_along_axis(rankdata, 1, x)
        return np.corrcoef(x)

    if kernel in {'cosine', 'normalized_angle'}:
        x = 1 - squareform(pdist(x, metric='cosine'))
        if kernel == 'normalized_angle':
            x = 1 - np.arccos(x, x)/np.pi
        return x

    if kernel == 'gaussian':
        if gamma is None:
            gamma = 1 / x.shape[1]
        return rbf_kernel(x, gamma=gamma)

    if callable(kernel):
        return kernel(x)

    raise ValueError("Unknown kernel '{0}'.".format(kernel)) 
開發者ID:MICA-MNI,項目名稱:BrainSpace,代碼行數:24,代碼來源:kernels.py

示例14: test_euclidean_distances_sym

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def test_euclidean_distances_sym(dtype, x_array_constr):
    # check that euclidean distances gives same result as scipy pdist
    # when only X is provided
    rng = np.random.RandomState(0)
    X = rng.random_sample((100, 10)).astype(dtype, copy=False)
    X[X < 0.8] = 0

    expected = squareform(pdist(X))

    X = x_array_constr(X)
    distances = euclidean_distances(X)

    # the default rtol=1e-7 is too close to the float32 precision
    # and fails due too rounding errors.
    assert_allclose(distances, expected, rtol=1e-6)
    assert distances.dtype == dtype 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:18,代碼來源:test_pairwise.py

示例15: find_medioid

# 需要導入模塊: from scipy.spatial import distance [as 別名]
# 或者: from scipy.spatial.distance import pdist [as 別名]
def find_medioid(self, X, Y):
        """
        Find point with minimal distance to all other points.

        Parameters
        ----------
        X : array
            data set, with N samples x D features.
        Y : array
            labels to select for which samples to compute distances.

        Returns
        -------
        x : array
            medioid
        ix : int
            index of medioid

        """
        # Initiate an array with infinities
        A = np.full((X.shape[0],), np.inf)

        # Insert sum of distances to other points
        A[Y] = np.sum(squareform(pdist(X[Y, :])), axis=1)

        # Find the index of the point with the smallest distance
        ix = np.argmin(A)

        return X[ix, :], ix 
開發者ID:wmkouw,項目名稱:libTLDA,代碼行數:31,代碼來源:suba.py


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