当前位置: 首页>>代码示例>>Python>>正文


Python spatial.distance方法代码示例

本文整理汇总了Python中scipy.spatial.distance方法的典型用法代码示例。如果您正苦于以下问题:Python spatial.distance方法的具体用法?Python spatial.distance怎么用?Python spatial.distance使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在scipy.spatial的用法示例。


在下文中一共展示了spatial.distance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_similarity_matrix

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def get_similarity_matrix(self, observation_matrix: numpy.array):
        """
        Calculate the pairwise similarity of a set of records in an MxN `observation_matrix` with M records and N features.
        :param observation_matrix: numpy.array - feature matrix
        :return: numpy.array - distance_matrix
        # TODO: Implement boolean conversion for relevant distance metrics, e.g., Jaccard.
        """
        # Toggle TF-IDF
        if self.use_tfidf:
            observation_matrix = sklearn.feature_extraction.text.TfidfTransformer().fit_transform(
                observation_matrix).toarray()
            distance_matrix = scipy.spatial.distance.squareform(
                scipy.spatial.distance.pdist(observation_matrix, metric=self.distance_type))
        else:
            distance_matrix = scipy.spatial.distance.squareform(
                scipy.spatial.distance.pdist(observation_matrix, self.distance_type))

        return distance_matrix 
开发者ID:LexPredict,项目名称:lexpredict-contraxsuite,代码行数:20,代码来源:similarity.py

示例2: __init__

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def __init__(self, table, lens='mds', metric='correlation', precomputed=False, **kwargs):
        """
        Initializes the class by providing the mapper input table generated by Preprocess.save(). The parameter 'metric'
        specifies the metric distance to be used ('correlation', 'euclidean' or 'neighbor'). The parameter 'lens'
        specifies the dimensional reduction algorithm to be used ('mds' or 'pca'). The rest of the arguments are
        passed directly to sklearn.manifold.MDS or sklearn.decomposition.PCA. It plots the low-dimensional projection
        of the data.
        """
        self.df = pandas.read_table(table + '.mapper.tsv')
        if lens == 'neighbor':
            self.lens_data_mds = sakmapper.apply_lens(self.df, lens=lens, **kwargs)
        elif lens == 'mds':
            if precomputed:
                self.lens_data_mds = sakmapper.apply_lens(self.df, lens=lens, metric=metric,
                                                          dissimilarity='precomputed', **kwargs)
            else:
                self.lens_data_mds = sakmapper.apply_lens(self.df, lens=lens, metric=metric, **kwargs)
        else:
            self.lens_data_mds = sakmapper.apply_lens(self.df, lens=lens, **kwargs)
        pylab.figure()
        pylab.scatter(numpy.array(self.lens_data_mds)[:, 0], numpy.array(self.lens_data_mds)[:, 1], s=10, alpha=0.7)
        pylab.show() 
开发者ID:CamaraLab,项目名称:scTDA,代码行数:24,代码来源:main.py

示例3: cellular_subpopulations

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def cellular_subpopulations(self, threshold=0.05, min_cells=5, clus_thres=0.65):
        """
        Identifies potential transient cellular subpopulations. The parameter
        'threshold' sets an upper bound of the q-value of the genes that are considered in the analysis.
        The parameter 'min_cells' sets the minimum number of cells on which each of the genes considered in the
        analysis is expressed. Cellular subpopulations are determined by clustering the Jensen-Shannon distance
        matrix of the genes that pass all the constraints. The number of clusters is controlled in this case by
        the parameter 'clus_thres'. In both cases a list with the genes associated to each cluster is returned.
        It requires the presence of the file 'name.genes.tsv', produced by the method RotedGraph.save().
        """
        con = []
        dis = []
        nam = []
        f = open(self.name + '.genes.tsv', 'r')
        for n, line in enumerate(f):
            if n > 0:
                sp = line[:-1].split('\t')
                if float(sp[7]) < threshold and float(sp[1]) > min_cells:
                    nam.append(sp[0])
        f.close()
        mat2 = self.JSD_matrix(nam)
        return [map(lambda xx: nam[xx], m)
                for m in find_clusters(hierarchical_clustering(mat2, labels=nam,
                                                               cluster_distance=True, thres=clus_thres)).values()] 
开发者ID:CamaraLab,项目名称:scTDA,代码行数:26,代码来源:main.py

示例4: get_gene

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def get_gene(self, genin, ignore_log=False, con=True):
        """
        Returns a dictionary that asigns to each node id the average value of the column 'genin' in the raw table.
        'genin' can be also a list of columns, on which case the average of all columns. The output is normalized
        such that the sum over all nodes is equal to 1. It also provides as an output the normalization factor, to
        convert the dictionary to log_2(1+TPM) units (or TPM units). When 'ignore_log' is True it treat entries as
        being in natural scale, even if self.log2 is True (used internally). When 'con' is False, it uses all
        nodes, not only the ones in the first connected component of the topological representation (used internally).
        Argument 'genin' may also be equal to the special keyword '_dist_root', on which case it returns the graph
        distance funtion to the root node. It can be also equal to 'timepoint_xxx', on which case it returns a
        dictionary with the fraction of cells belonging to timepoint xxx in each node.
        """
        if genin == '_dist_root':
            return self.get_distroot(self.root), 1.0
        elif genin is not None and 'timepoint_' in genin:
            return self.count_gene(self.rootlane, float(genin[genin.index('_')+1:]))
        else:
            return UnrootedGraph.get_gene(self, genin, ignore_log, con) 
开发者ID:CamaraLab,项目名称:scTDA,代码行数:20,代码来源:main.py

示例5: knnsearch

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def knnsearch(N, X, k = 1, method = 'brute', p = 2.):
  #if p != 2: assert method == 'kd'

  if method == 'kd':
    kd_ = kd(N)
    return kd_query(kd_, X, k = k, p = p)
  elif method == 'brute':
    import scipy.spatial.distance
    if p == 2:
      D = scipy.spatial.distance.cdist(X, N)
    else:
      D = scipy.spatial.distance.cdist(X, N, p)

    if k == 1:
      I = np.argmin(D, 1)[:, np.newaxis]
    else:
      I = np.argsort(D)[:, :k]
    return D[np.arange(D.shape[0])[:, np.newaxis], I], I 
  else:
    fail('Unknown search method: %s' % method) 
开发者ID:andrewowens,项目名称:multisensory,代码行数:22,代码来源:util.py

示例6: _on_map_mouse_click_event

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def _on_map_mouse_click_event(self, event):
        if None in (event.xdata, event.ydata):
            return
        # Get map coordinates by the inverse transform.
        lng, lat = self.map(event.xdata, event.ydata, inverse=True)
        # Left click: set mid point
        if event.button == 1:
            self.ui.midpt_longitude.setValue(lng)
            self.ui.midpt_latitude.setValue(lat)
            rng = float(self.ui.width_cross.value())/2. # distance in degrees
            r = self.center_pt
            lon, lat = r.longitude, r.latitude
            az = float(self.ui.azimuth.value())
            end_lat,end_lon,end_lat2,end_lon2 = SeisTomoPy.path_tracer(lon,lat,rng,az)
            self.ui.label_4.setText(str(int(end_lat2)))
            self.ui.label_9.setText(str(int(end_lon2)))
            self._plot_path() 
开发者ID:stephaniedurand,项目名称:SeisTomoPy_V3,代码行数:19,代码来源:seistomopy_gui.py

示例7: dist

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def dist(x, y, metric='chebyshev'):
    """Compute the distance between all sequential pairs of points.

    Computes the distance between all sequential pairs of points from
    two arrays using scipy.spatial.distance.

    Paramters
    ---------
    x : ndarray
        Input array.
    y : ndarray
        Input array.
    metric : string, optional (default = 'chebyshev')
        Metric to use while computing distances.

    Returns
    -------
    d : ndarray
        Array containing distances.
    """
    func = getattr(distance, metric)
    return np.asarray([func(i, j) for i, j in zip(x, y)]) 
开发者ID:manu-mannattil,项目名称:nolitsa,代码行数:24,代码来源:utils.py

示例8: rbf_gauss

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def rbf_gauss(rsq, p):
    r"""Gaussian RBF :math:`\exp\left(-\frac{r^2}{2\,p^2}\right)`

    Parameters
    ----------
    rsq : float
        squared distance :math:`r^2`
    p : float
        width
    """
    return np.exp(-0.5*rsq / p**2.0) 
开发者ID:elcorto,项目名称:pwtools,代码行数:13,代码来源:rbf.py

示例9: rbf_multi

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def rbf_multi(rsq, p):
    r"""Multiquadric RBF :math:`\sqrt{r^2 + p^2}`

    Parameters
    ----------
    rsq : float
        squared distance :math:`r^2`
    p : float
        width
    """
    return np.sqrt(rsq + p**2.0) 
开发者ID:elcorto,项目名称:pwtools,代码行数:13,代码来源:rbf.py

示例10: rbf_inv_multi

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def rbf_inv_multi(rsq, p):
    r"""Inverse Multiquadric RBF :math:`\frac{1}{\sqrt{r^2 + p^2}}`

    Parameters
    ----------
    rsq : float
        squared distance :math:`r^2`
    p : float
        width
    """
    return 1/rbf_multi(rsq, p) 
开发者ID:elcorto,项目名称:pwtools,代码行数:13,代码来源:rbf.py

示例11: get_distsq

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def get_distsq(self, points=None):
        """Matrix of distance values :math:`R_{ij} = |\mathbf x_i - \mathbf
        c_j|`.

            | :math:`\mathbf x_i` : points[i,:]
            | :math:`\mathbf c_i` : centers[i,:]

        Parameters
        ----------
        points : array (M,N) with N-dim points, optional
            If None then ``self.points`` is used (training points).

        Returns
        -------
        distsq : (M,K), where K = M usually for training
        """
        # pure numpy:
        #     dist = points[:,None,...] - centers[None,...]
        #     distsq = (dist**2.0).sum(axis=-1)
        # where
        #     points:  (M,N)
        #     centers: (K,N)
        #     dist:    (M,K,N) "matrix" of distance vectors (only for numpy case)
        #     distsq:  (M,K)    matrix of squared distance values
        # Creates *big* temporary arrays if points is big (~1e4 points).
        #
        # training:
        #     If points == centers, we could also use pdist(points), which
        #     would give us a 1d array of all distances. But we need the
        #     redundant square matrix form for G=rbf(distsq) anyway, so there
        #     is no real point in special-casing that. These two are the same:
        #      >>> R = spatial.squareform(spatial.distances.pdist(points))
        #      >>> R = spatial.distances.cdist(points,points)
        #      >>> distsq = R**2
        if points is None:
            if self.distsq is None:
                return num.distsq(self.points, self.centers)
            else:
                return self.distsq
        else:
            return num.distsq(points, self.centers) 
开发者ID:elcorto,项目名称:pwtools,代码行数:43,代码来源:rbf.py

示例12: interpolate

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def interpolate(self, points):
        """Actually do interpolation. Return interpolated values at each
        point in points.

        Parameters
        ----------
        points : see :meth:`__call__`

        Returns
        -------
        vals : 1d array (points.shape[0],)

        Notes
        -----
        Calculates
            distsq = (points - centers)**2  # squared distance matrix
            G = rbf(distsq)                 # RBF values
            zi = dot(G, w)                  # interpolation z_i = Sum_j g_ij w_j
        """
        self._assert_ndim_points(points)
        distsq = self.get_distsq(points=points)
        G = self.rbf(distsq, self.p)
        assert G.shape[1] == len(self.w), \
               "shape mismatch between g_ij: %s and w_j: %s, 2nd dim of "\
               "g_ij must match length of w_j" %(str(G.shape),
                                                 str(self.w.shape))
        # normalize w
        ww = self.w
        maxw = np.abs(ww).max()*1.0
        return np.dot(G, ww / maxw) * maxw 
开发者ID:elcorto,项目名称:pwtools,代码行数:32,代码来源:rbf.py

示例13: mds

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def mds(class_dist, num_dim = None):
    """
    Finds an embedding of `n` classes in a `d`-dimensional space, so that their Euclidean distances corresponds
    to pre-defined ones, using classical multidimensional scaling (MDS).
    
    class_dist - `n-by-n` matrix specifying the desired distance between each pair of classes.
                 The distances in this matrix *must* define a proper metric that fulfills the triangle inequality.
                 Otherwise, a `RuntimeError` will be raised.
    num_dim - Optionally, the maximum target dimensionality `d` for the embeddings. If not given, it will be determined
              automatically based on the eigenvalues, but this might not be accurate due to limited machine precision.
    
    Returns: `n-by-d` matrix with rows being the locations of the corresponding classes in the embedding space.
    """

    H = np.eye(class_dist.shape[0], dtype=class_dist.dtype) - np.ones(class_dist.shape, dtype=class_dist.dtype) / class_dist.shape[0]
    B = np.dot(H, np.dot(class_dist ** 2, H)) / -2

    eigval, eigvec = np.linalg.eigh(B)
    nonzero_eigvals = (eigval > np.finfo(class_dist.dtype).eps)
    eigval = eigval[nonzero_eigvals]
    eigvec = eigvec[:,nonzero_eigvals]
    
    if num_dim is not None:
        sort_ind = np.argsort(eigval)[::-1]
        eigval = eigval[sort_ind[:num_dim]]
        eigvec = eigvec[:,sort_ind[:num_dim]]

    embedding = eigvec * np.sqrt(eigval[None,:])
    return embedding 
开发者ID:cvjena,项目名称:semantic-embeddings,代码行数:31,代码来源:compute_class_embedding.py

示例14: find_closest_point_index

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def find_closest_point_index(self, x, y, return_distance=False):
        """Find the index of the exterior point closest to given coordinates.

        "Closeness" is here defined based on euclidean distance.
        This method will raise an ``AssertionError`` if the exterior contains
        no points.

        Parameters
        ----------
        x : number
            X-coordinate around which to search for close points.

        y : number
            Y-coordinate around which to search for close points.

        return_distance : bool, optional
            Whether to also return the distance of the closest point.

        Returns
        -------
        int
            Index of the closest point.

        number
            Euclidean distance to the closest point.
            This value is only returned if `return_distance` was set
            to ``True``.

        """
        assert len(self.exterior) > 0, (
            "Cannot find the closest point on a polygon which's exterior "
            "contains no points.")
        distances = []
        for x2, y2 in self.exterior:
            dist = (x2 - x) ** 2 + (y2 - y) ** 2
            distances.append(dist)
        distances = np.sqrt(distances)
        closest_idx = np.argmin(distances)
        if return_distance:
            return closest_idx, distances[closest_idx]
        return closest_idx 
开发者ID:aleju,项目名称:imgaug,代码行数:43,代码来源:polys.py

示例15: coords_almost_equals

# 需要导入模块: from scipy import spatial [as 别名]
# 或者: from scipy.spatial import distance [as 别名]
def coords_almost_equals(self, other, max_distance=1e-4):
        """Estimate if this and another KP have almost identical coordinates.

        Added in 0.4.0.

        Parameters
        ----------
        other : imgaug.augmentables.kps.Keypoint or iterable
            The other keypoint with which to compare this one.
            If this is an ``iterable``, it is assumed to contain the
            xy-coordinates of a keypoint.

        max_distance : number, optional
            The maximum euclidean distance between a this keypoint and the
            other one. If the distance is exceeded, the two keypoints are not
            viewed as equal.

        Returns
        -------
        bool
            Whether the two keypoints have almost identical coordinates.

        """
        if ia.is_np_array(other):
            # we use flat here in case other is (N,2) instead of (4,)
            coords_b = other.flat
        elif ia.is_iterable(other):
            coords_b = list(ia.flatten(other))
        else:
            assert isinstance(other, Keypoint), (
                "Expected 'other' to be an iterable containing one "
                "(x,y)-coordinate pair or a Keypoint. "
                "Got type %s." % (type(other),))
            coords_b = other.coords.flat

        coords_a = self.coords

        return np.allclose(coords_a.flat, coords_b, atol=max_distance, rtol=0) 
开发者ID:aleju,项目名称:imgaug,代码行数:40,代码来源:kps.py


注:本文中的scipy.spatial.distance方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。