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


Python csgraph.connected_components方法代码示例

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


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

示例1: computeObj

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def computeObj(U, pairs, _delta, gtlabels, numeval):
    """ This is similar to computeObj function in Matlab """
    numsamples = len(U)
    diff = np.linalg.norm(U[pairs[:, 0].astype(int)] - U[pairs[:, 1].astype(int)], axis=1)**2

    # computing clustering measures
    index1 = np.sqrt(diff) < _delta
    index = np.where(index1)
    adjacency = csr_matrix((np.ones(len(index[0])), (pairs[index[0], 0].astype(int), pairs[index[0], 1].astype(int))),
                           shape=(numsamples, numsamples))
    adjacency = adjacency + adjacency.transpose()
    n_components, labels = connected_components(adjacency, directed=False)

    index2 = labels[pairs[:, 0].astype(int)] == labels[pairs[:, 1].astype(int)]

    ari, ami, nmi, acc = benchmarking(gtlabels[:numeval], labels[:numeval])

    return index2, ari, ami, nmi, acc, n_components, labels 
开发者ID:shahsohil,项目名称:DCC,代码行数:20,代码来源:DCCComputation.py

示例2: compute_assignment

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def compute_assignment(self, epsilon):
        """
        Assigns points to clusters based on their representative. Two points are part of the same cluster if their
        representative are close enough (their squared euclidean distance is < delta)
        """
        diff = np.sum((self.U[self.i, :] - self.U[self.j, :])**2, axis=1)

        # computing connected components.
        is_conn = np.sqrt(diff) <= self.clustering_threshold*epsilon

        G = scipy.sparse.coo_matrix((np.ones((2*np.sum(is_conn),)),
                                     (np.concatenate([self.i[is_conn], self.j[is_conn]], axis=0),
                                      np.concatenate([self.j[is_conn], self.i[is_conn]], axis=0))),
                                    shape=[self.n_samples, self.n_samples])

        num_components, labels = connected_components(G, directed=False)

        return labels, num_components 
开发者ID:yhenon,项目名称:pyrcc,代码行数:20,代码来源:rcc.py

示例3: _graph_is_connected

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def _graph_is_connected(graph):
    """ Return whether the graph is connected (True) or Not (False)

    Parameters
    ----------
    graph : array-like or sparse matrix, shape: (n_samples, n_samples)
        adjacency matrix of the graph, non-zero weight means an edge
        between the nodes

    Returns
    -------
    is_connected : bool
        True means the graph is fully connected and False means not
    """
    if sparse.isspmatrix(graph):
        # sparse graph, find all the connected components
        n_connected_components, _ = connected_components(graph)
        return n_connected_components == 1
    else:
        # dense graph, find all connected components start from node 0
        return _graph_connected_component(graph, 0).sum() == graph.shape[0] 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:23,代码来源:spectral_embedding_.py

示例4: rt_grouping

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def rt_grouping(mzregions):
    """
    A function that groups roi inside mzregions.
    :param mzregions: a list of mzRegion objects
    :return: a list of defaultdicts, where the key is the name of file and value is a list of ROIs
    """
    components = []
    for region in mzregions:
        region = np.array([(name, roi) for name, s in region.rois.items() for roi in s])
        n = len(region)
        graph = np.zeros((n, n), dtype=np.uint8)
        for i in range(n - 1):
            for j in range(i + 1, n):
                graph[i, j] = roi_intersected(region[i][1], region[j][1])
        n_components, labels = connected_components(graph, directed=False)

        for k in range(n_components):
            rois = region[labels == k]
            component = defaultdict(list)
            for roi in rois:
                component[roi[0]].append(roi[1])
            components.append(component)
    return components 
开发者ID:Arseha,项目名称:peakonly,代码行数:25,代码来源:matching.py

示例5: check_mesh

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def check_mesh(verts, tris, filename=None):
    ij = np.r_[np.c_[tris[:,0], tris[:,1]], 
               np.c_[tris[:,0], tris[:,2]], 
               np.c_[tris[:,1], tris[:,2]]]
    G = sparse.csr_matrix((np.ones(len(ij)), ij.T), shape=(verts.shape[0], verts.shape[0]))
    n_components, labels = csgraph.connected_components(G, directed=False)
    if n_components > 1:
        size_components = np.bincount(labels)
        if len(size_components) > 1:
            raise ValueError, "found %d connected components in the mesh (%s)" % (n_components, filename)
        keep_vert = labels == size_components.argmax()
    else:
        keep_vert = np.ones(verts.shape[0], np.bool)
    verts = verts[keep_vert, :]
    tris = filter_reindex(keep_vert, tris[keep_vert[tris].all(axis=1)])
    return verts, tris 
开发者ID:tneumann,项目名称:cmm,代码行数:18,代码来源:__init__.py

示例6: _compute_cp_labels

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def _compute_cp_labels(core_points, *in_cp_neighs):
    core_ids = np.cumsum(core_points) - 1
    n_core_pts = np.count_nonzero(core_points)
    adj_matrix = lil_matrix((n_core_pts, n_core_pts))

    # Build adjacency matrix of core points
    in_cp_neighs_iter = chain(*in_cp_neighs)
    core_idx = 0
    for idx, neighbours in zip(core_points.nonzero()[0], in_cp_neighs_iter):
        neighbours = core_ids[neighbours[core_points[neighbours]]]
        adj_matrix.rows[core_idx] = neighbours
        adj_matrix.data[core_idx] = [1] * len(neighbours)
        core_idx += 1

    n_clusters, core_labels = connected_components(adj_matrix, directed=False)
    labels = np.full(core_points.shape, -1)
    labels[core_points] = core_labels
    return labels 
开发者ID:bsc-wdc,项目名称:dislib,代码行数:20,代码来源:classes.py

示例7: largest_connected_components

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def largest_connected_components(adj, n_components=1):
    """Select the largest connected components in the graph.
    Parameters
    ----------
    adj : gust.SparseGraph
        Input graph.
    n_components : int, default 1
        Number of largest connected components to keep.
    Returns
    -------
    sparse_graph : gust.SparseGraph
        Subgraph of the input graph where only the nodes in largest n_components are kept.
    """
    _, component_indices = connected_components(adj)
    component_sizes = np.bincount(component_indices)
    components_to_keep = np.argsort(component_sizes)[::-1][:n_components]  # reverse order to sort descending
    nodes_to_keep = [
        idx for (idx, component) in enumerate(component_indices) if component in components_to_keep


    ]
    print("Selecting {0} largest connected components".format(n_components))
    return nodes_to_keep 
开发者ID:danielzuegner,项目名称:gnn-meta-attack,代码行数:25,代码来源:utils.py

示例8: make_cut

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def make_cut(self, in_node, out_node, score, MSF=None):
        """
        make a cut on the MSF inplace, provided the in_node, out_node, MSF, and score. 
        in_node: int, ID of the source node for the edge to be cut
        out_node: int, ID of the destination node for the edge to be cut
        score: float, the value of the score being cut. if the score is infinite, the cut is not made. 
        MSF: the spanning forest to use when making the cut. If not provided,
             uses the defualt tree in self.minimum_spanning_forest_
        """
        if MSF is None:
            MSF = self.minimum_spanning_forest_
        if np.isfinite(score):
            MSF[in_node, out_node] = 0
            MSF.eliminate_zeros()
            return (MSF, *cg.connected_components(MSF, directed=False))
        raise OptimizeWarning('Score of the ({},{}) cut is inf, the quorum is likely not met!') 
开发者ID:pysal,项目名称:region,代码行数:18,代码来源:skater.py

示例9: __init__

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def __init__(self, arg_dict):
		BaseAlg.__init__(self, arg_dict)
		self.time = 0
		#N_LinUCBAlgorithm.__init__(dimension = dimension, alpha=alpha,lambda_ = lambda_,n=n)
		self.users = []
		#algorithm have n users, each user has a user structure
		for i in range(self.n):
			self.users.append(CLUBUserStruct(self.dimension,self.lambda_, i)) 
		if (self.cluster_init=="Erdos-Renyi"):
			p = 3*math.log(self.n)/self.n
			self.Graph = np.random.choice([0, 1], size=(self.n,self.n), p=[1-p, p])
			self.clusters = []
			g = csr_matrix(self.Graph)
			N_components, components = connected_components(g)
		else:
			self.Graph = np.ones([self.n,self.n]) 
			self.clusters = []
			g = csr_matrix(self.Graph)
			N_components, components = connected_components(g) 
开发者ID:huazhengwang,项目名称:BanditLib,代码行数:21,代码来源:CLUB.py

示例10: updateGraphClusters

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def updateGraphClusters(self,userID, binaryRatio):
		n = len(self.users)
		for j in range(n):
			ratio = float(np.linalg.norm(self.users[userID].UserTheta - self.users[j].UserTheta,2))/float(self.users[userID].CBPrime + self.users[j].CBPrime)
			#print float(np.linalg.norm(self.users[userID].UserTheta - self.users[j].UserTheta,2)),'R', ratio
			if ratio > 1:
				ratio = 0
			elif binaryRatio == 'True':
				ratio = 1
			elif binaryRatio == 'False':
				ratio = 1.0/math.exp(ratio)
			#print 'ratio',ratio
			self.Graph[userID][j] = ratio
			self.Graph[j][userID] = self.Graph[userID][j]
		N_components, component_list = connected_components(csr_matrix(self.Graph))
		#print 'N_components:',N_components
		self.clusters = component_list
		return N_components 
开发者ID:huazhengwang,项目名称:BanditLib,代码行数:20,代码来源:CLUB.py

示例11: largest_connected_components

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def largest_connected_components(adj, n_components=1):
    """Select the largest connected components in the graph.

    Parameters
    ----------
    sparse_graph : gust.SparseGraph
        Input graph.
    n_components : int, default 1
        Number of largest connected components to keep.

    Returns
    -------
    sparse_graph : gust.SparseGraph
        Subgraph of the input graph where only the nodes in largest n_components are kept.

    """
    _, component_indices = connected_components(adj)
    component_sizes = np.bincount(component_indices)
    components_to_keep = np.argsort(component_sizes)[::-1][:n_components]  # reverse order to sort descending
    nodes_to_keep = [
        idx for (idx, component) in enumerate(component_indices) if component in components_to_keep


    ]
    print("Selecting {0} largest connected components".format(n_components))
    return nodes_to_keep 
开发者ID:danielzuegner,项目名称:nettack,代码行数:28,代码来源:utils.py

示例12: retrieve_weakly_connected_components

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def retrieve_weakly_connected_components(cgpms):
    v_to_c = retrieve_variable_to_cgpm(cgpms)
    adjacency = retrieve_adjacency_matrix(cgpms, v_to_c)
    n_components, labels = connected_components(
        adjacency, directed=True, connection='weak', return_labels=True)
    return labels 
开发者ID:probcomp,项目名称:cgpm,代码行数:8,代码来源:helpers.py

示例13: test_weak_connections

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def test_weak_connections():
    Xde = np.array([[0, 1, 0],
                    [0, 0, 0],
                    [0, 0, 0]])

    Xsp = csgraph.csgraph_from_dense(Xde, null_value=0)

    for X in Xsp, Xde:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='weak')

        assert_equal(n_components, 2)
        assert_array_almost_equal(labels, [0, 0, 1]) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:16,代码来源:test_connected_components.py

示例14: test_strong_connections

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def test_strong_connections():
    X1de = np.array([[0, 1, 0],
                     [0, 0, 0],
                     [0, 0, 0]])
    X2de = X1de + X1de.T

    X1sp = csgraph.csgraph_from_dense(X1de, null_value=0)
    X2sp = csgraph.csgraph_from_dense(X2de, null_value=0)

    for X in X1sp, X1de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 3)
        labels.sort()
        assert_array_almost_equal(labels, [0, 1, 2])

    for X in X2sp, X2de:
        n_components, labels =\
            csgraph.connected_components(X, directed=True,
                                         connection='strong')

        assert_equal(n_components, 2)
        labels.sort()
        assert_array_almost_equal(labels, [0, 0, 1]) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:28,代码来源:test_connected_components.py

示例15: test_strong_connections2

# 需要导入模块: from scipy.sparse import csgraph [as 别名]
# 或者: from scipy.sparse.csgraph import connected_components [as 别名]
def test_strong_connections2():
    X = np.array([[0, 0, 0, 0, 0, 0],
                  [1, 0, 1, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0],
                  [0, 0, 1, 0, 1, 0],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 1, 0]])
    n_components, labels =\
        csgraph.connected_components(X, directed=True,
                                     connection='strong')
    assert_equal(n_components, 5)
    labels.sort()
    assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4]) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:15,代码来源:test_connected_components.py


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