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


Python networkx.is_directed方法代码示例

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


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

示例1: _sanity_check

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def _sanity_check(G):
    r"""
    Helper function that checks if the input graphs contains a single connected component. Raises an error if not.

    Parameters
    ----------
    G : graph
       A NetworkX graph

    Raises
    ------
    ValueError
        If the graph has more than one (weakly) connected component.
    """
    # Compute the number of connected components
    if G.is_directed():
        num_ccs = nx.number_weakly_connected_components(G)
    else:
        num_ccs = nx.number_connected_components(G)

    # Rise an error if more than one CC exists
    if num_ccs != 1:
        raise ValueError("Input graph should contain one (weakly) connected component. "
                         "This graph contains: " + str(num_ccs)) 
开发者ID:Dru-Mara,项目名称:EvalNE,代码行数:26,代码来源:split_train_test.py

示例2: train

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def train(self, G):
        self.G = G
        is_directed = nx.is_directed(self.G)
        for i, j in G.edges():
            G[i][j]["weight"] = G[i][j].get("weight", 1.0)
            if not is_directed:
                G[j][i]["weight"] = G[j][i].get("weight", 1.0)
        self._preprocess_transition_probs()
        walks = self._simulate_walks(self.walk_num, self.walk_length)
        walks = [[str(node) for node in walk] for walk in walks]
        model = Word2Vec(
            walks,
            size=self.dimension,
            window=self.window_size,
            min_count=0,
            sg=1,
            workers=self.worker,
            iter=self.iteration,
        )
        id2node = dict([(vid, node) for vid, node in enumerate(G.nodes())])
        self.embeddings = np.asarray(
            [model[str(id2node[i])] for i in range(len(id2node))]
        )
        return self.embeddings 
开发者ID:imsheridan,项目名称:CogDL-TensorFlow,代码行数:26,代码来源:node2vec.py

示例3: rm_useless

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def rm_useless(G, feats, class_map, unlabeled_nodes, num_layers):
    # find useless nodes
    print('start to check and remove {} unlabeled nodes'.format(len(unlabeled_nodes)))
    unlabeled_nodes = set(unlabeled_nodes)
    rm_nodes = []
    for n_id in tqdm(unlabeled_nodes):
        neighbors_set = set()
        neighbors_set.add(n_id)
        for _ in range(num_layers):
            for node in neighbors_set:
                if nx.is_directed(G):
                    neighbors_set = neighbors_set | set(G.neighbors(node)) | set(G.predecessors(node))
                else:
                    neighbors_set = neighbors_set | set(G.neighbors(node))
        if check_rm(neighbors_set, unlabeled_nodes):
            rm_nodes.append(n_id)
    # rm nodes
    if len(rm_nodes):
        for node in rm_nodes:
            G.remove_node(node)
        G_new = nx.relabel.convert_node_labels_to_integers(G, ordering='sorted')
        feats = np.delete(feats, rm_nodes, 0)
        class_map = np.delete(class_map, rm_nodes, 0)
        print('remove {} '.format(len(rm_nodes)), 'useless unlabeled nodes')
    return G_new, feats, class_map 
开发者ID:yifan-h,项目名称:CS-GNN,代码行数:27,代码来源:utils.py

示例4: compute_feature_smoothness

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def compute_feature_smoothness(path, times=0):
    G_org = json_graph.node_link_graph(json.load(open(path+'-G.json')))
    # G_org = remove_unlabeled(G_org)
    if nx.is_directed(G_org):
        G_org = G_org.to_undirected()
    edge_num = G_org.number_of_edges()
    G = pygsp.graphs.Graph(nx.adjacency_matrix(G_org))
    feats = np.load(path+'-feats.npy')
    # smooth
    for i in range(times):
        feats = feature_broadcast(feats, G_org)
    np.save(path+'-feats_'+str(times)+'.npy', feats)

    min_max_scaler = preprocessing.MinMaxScaler()
    feats = min_max_scaler.fit_transform(feats)
    smoothness = np.zeros(feats.shape[1])
    for src, dst in G_org.edges():
        smoothness += (feats[src]-feats[dst])*(feats[src]-feats[dst])
    smoothness = np.linalg.norm(smoothness,ord=1)
    print('The smoothness is: ', 2*smoothness/edge_num/feats.shape[1]) 
开发者ID:yifan-h,项目名称:CS-GNN,代码行数:22,代码来源:smoothness.py

示例5: compute_label_smoothness

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def compute_label_smoothness(path, rate=0.):
    G_org = json_graph.node_link_graph(json.load(open(path+'-G.json')))
    # G_org = remove_unlabeled(G_org)
    if nx.is_directed(G_org):
        G_org = G_org.to_undirected()
    class_map = json.load(open(path+'-class_map.json'))
    for k, v in class_map.items():
        if type(v) != list:
            class_map = convert_list(class_map)
        break
    labels = convert_ndarray(class_map)
    labels = np.squeeze(label_to_vector(labels))

    # smooth
    G_org = label_broadcast(G_org, labels, rate)
    with open(path+'-G_'+str(rate)+'.json', 'w') as f:
        f.write(json.dumps(json_graph.node_link_data(G_org)))

    edge_num = G_org.number_of_edges()
    G = pygsp.graphs.Graph(nx.adjacency_matrix(G_org))
    smoothness = 0
    for src, dst in G_org.edges():
        if labels[src] != labels[dst]:
            smoothness += 1
    print('The smoothness is: ', 2*smoothness/edge_num) 
开发者ID:yifan-h,项目名称:CS-GNN,代码行数:27,代码来源:smoothness.py

示例6: ensure_undirected

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def ensure_undirected(G):
    """Ensure the graph G is undirected.

    If it is not, coerce it to undirected and warn the user.

    Parameters
    ----------
    G (networkx graph)
        The graph to be checked

    Returns
    -------

    G (nx.Graph)
        Undirected version of the input graph

    """
    if nx.is_directed(G):
        G = G.to_undirected(as_view=False)
        warnings.warn("Coercing directed graph to undirected.", RuntimeWarning)
    return G 
开发者ID:netsiphd,项目名称:netrd,代码行数:23,代码来源:graph.py

示例7: _random_walk_matrix

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def _random_walk_matrix(self, pid):
        # construct matrix based on random walk
        np.random.seed(pid)
        matrix = sp.lil_matrix((self.num_node, self.num_node))
        t0 = time.time()
        for round in range(int(self.num_round / self.worker)):
            if round % 10 == 0 and pid == 0:
                print(
                    "round %d / %d, time: %lf"
                    % (round * self.worker, self.num_round, time.time() - t0)
                )
            for i in range(self.num_edge):
                u, v = self.edges[i]
                if not self.is_directed and np.random.rand() > 0.5:
                    v, u = self.edges[i]
                for r in range(1, self.window_size + 1):
                    u_, v_, zp = self._path_sampling(u, v, r)
                    matrix[u_, v_] += 2 * r / self.window_size / self.num_round / zp
        return matrix 
开发者ID:THUDM,项目名称:cogdl,代码行数:21,代码来源:netsmf.py

示例8: train

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def train(self, G):
        self.G = G
        is_directed = nx.is_directed(self.G)
        for i, j in G.edges():
            G[i][j]["weight"] = G[i][j].get("weight", 1.0)
            if not is_directed:
                G[j][i]["weight"] = G[j][i].get("weight", 1.0)
        self._preprocess_transition_probs()
        walks = self._simulate_walks(self.walk_num, self.walk_length)
        walks = [[str(node) for node in walk] for walk in walks]
        model = Word2Vec(
            walks,
            size=self.dimension,
            window=self.window_size,
            min_count=0,
            sg=1,
            workers=self.worker,
            iter=self.iteration,
        )
        id2node = dict([(vid, node) for vid, node in enumerate(G.nodes())])
        self.embeddings = np.asarray(
            [model.wv[str(id2node[i])] for i in range(len(id2node))]
        )
        return self.embeddings 
开发者ID:THUDM,项目名称:cogdl,代码行数:26,代码来源:node2vec.py

示例9: from_networkx

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def from_networkx(G):
    r"""Converts a :obj:`networkx.Graph` or :obj:`networkx.DiGraph` to a
    :class:`torch_geometric.data.Data` instance.

    Args:
        G (networkx.Graph or networkx.DiGraph): A networkx graph.
    """

    G = nx.convert_node_labels_to_integers(G)
    G = G.to_directed() if not nx.is_directed(G) else G
    edge_index = torch.tensor(list(G.edges)).t().contiguous()

    data = {}

    for i, (_, feat_dict) in enumerate(G.nodes(data=True)):
        for key, value in feat_dict.items():
            data[key] = [value] if i == 0 else data[key] + [value]

    for i, (_, _, feat_dict) in enumerate(G.edges(data=True)):
        for key, value in feat_dict.items():
            data[key] = [value] if i == 0 else data[key] + [value]

    for key, item in data.items():
        try:
            data[key] = torch.tensor(item)
        except ValueError:
            pass

    data['edge_index'] = edge_index.view(2, -1)
    data = torch_geometric.data.Data.from_dict(data)
    data.num_nodes = G.number_of_nodes()

    return data 
开发者ID:rusty1s,项目名称:pytorch_geometric,代码行数:35,代码来源:convert.py

示例10: _check_directedness

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def _check_directedness(self, graph):
        """Checking the undirected nature of a single graph."""
        directed = nx.is_directed(graph)
        assert directed == False, "Graph is directed." 
开发者ID:benedekrozemberczki,项目名称:karateclub,代码行数:6,代码来源:estimator.py

示例11: from_networkx

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def from_networkx(G_nx):
    """Convert a networkx graph to my graph representation"""
    V = list(G_nx.nodes)
    edges = list(G_nx.edges)
    is_weighted = "weight" in G_nx[edges[0][0]][edges[0][1]]

    E = []
    for e in edges:
        if is_weighted:
            E.append(Edge(e[0], e[1], G_nx[e[0]][e[1]]["weight"]))
        else:
            E.append(Edge(e[0], e[1]))

    return DiGraph(V, E) if nx.is_directed(G_nx) else UndirectedGraph(V, E) 
开发者ID:ddbourgin,项目名称:numpy-ml,代码行数:16,代码来源:test_utils.py

示例12: to_networkx

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def to_networkx(G):
    """Convert my graph representation to a networkx graph"""
    G_nx = nx.DiGraph() if G.is_directed else nx.Graph()
    V = list(G._V2I.keys())
    G_nx.add_nodes_from(V)

    for v in V:
        fr_i = G._V2I[v]
        edges = G._G[fr_i]

        for edge in edges:
            G_nx.add_edge(edge.fr, edge.to, weight=edge._w)
    return G_nx 
开发者ID:ddbourgin,项目名称:numpy-ml,代码行数:15,代码来源:test_utils.py

示例13: _preprocess_transition_probs

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def _preprocess_transition_probs(self):
        # Preprocessing of transition probabilities for guiding the random walks.
        G = self.G
        is_directed = nx.is_directed(self.G)

        print(len(list(G.nodes())))
        print(len(list(G.edges())))

        s = time.time()
        alias_nodes = {}
        for node in G.nodes():
            unnormalized_probs = [G[node][nbr]["weight"] for nbr in G.neighbors(node)]
            norm_const = sum(unnormalized_probs)
            normalized_probs = [
                float(u_prob) / norm_const for u_prob in unnormalized_probs
            ]
            alias_nodes[node] = alias_setup(normalized_probs)

        t = time.time()
        print("alias_nodes", t - s)

        alias_edges = {}
        s = time.time()

        if is_directed:
            for edge in G.edges():
                alias_edges[edge] = self._get_alias_edge(edge[0], edge[1])
        else:
            for edge in G.edges():
                alias_edges[edge] = self._get_alias_edge(edge[0], edge[1])
                alias_edges[(edge[1], edge[0])] = self._get_alias_edge(edge[1], edge[0])

        t = time.time()
        print("alias_edges", t - s)

        self.alias_nodes = alias_nodes
        self.alias_edges = alias_edges

        return 
开发者ID:imsheridan,项目名称:CogDL-TensorFlow,代码行数:41,代码来源:node2vec.py

示例14: _train_line

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def _train_line(self, order):
        # train Line model with order
        self.alpha = self.init_alpha
        batch_size = self.batch_size
        t0 = time.time()
        num_batch = int(self.num_sampling_edge / batch_size)
        epoch_iter = tqdm(range(num_batch))
        for b in epoch_iter:
            if b % 100 == 0:
                epoch_iter.set_description(
                    f"Progress: {b *1.0/num_batch * 100:.4f}%, alpha: {self.alpha:.6f}, time: {time.time() - t0:.4f}"
                )
                self.alpha = self.init_alpha * max((1 - b * 1.0 / num_batch), 0.0001)
            u, v = [0] * batch_size, [0] * batch_size
            for i in range(batch_size):
                edge_id = alias_draw(self.edges_table, self.edges_prob)
                u[i], v[i] = self.edges[edge_id]
                if not self.is_directed and np.random.rand() > 0.5:
                    v[i], u[i] = self.edges[edge_id]

            vec_error = np.zeros((batch_size, self.dimension))
            label, target = np.asarray([1 for i in range(batch_size)]), np.asarray(v)
            for j in range(self.negative):
                if j != 0:
                    label = np.asarray([0 for i in range(batch_size)])
                    for i in range(batch_size):
                        target[i] = alias_draw(self.node_table, self.node_prob)
                if order == 1:
                    self._update(
                        self.emb_vertex[u], self.emb_vertex[target], vec_error, label
                    )
                else:
                    self._update(
                        self.emb_vertex[u], self.emb_context[target], vec_error, label
                    )
            self.emb_vertex[u] += vec_error 
开发者ID:imsheridan,项目名称:CogDL-TensorFlow,代码行数:38,代码来源:line.py

示例15: _train_line

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import is_directed [as 别名]
def _train_line(self, order):
        # train Line model with order
        self.alpha = self.init_alpha
        batch_size = self.batch_size
        t0 = time.time()
        num_batch = int(self.num_sampling_edge / batch_size)
        epoch_iter = tqdm(range(num_batch))
        for b in epoch_iter:
            if b % 100 == 0:
                epoch_iter.set_description(
                    f"Progress: {b *1.0/num_batch * 100:.4f}%, alpha: {self.alpha:.6f}, time: {time.time() - t0:.4f}"
                )
                self.alpha = self.init_alpha * max((1 - b * 1.0 / num_batch), 0.0001)
            u, v = [0] * batch_size, [0] * batch_size
            for i in range(batch_size):
                edge_id = alias_draw(self.edges_table, self.edges_prob)
                u[i], v[i] = self.edges[edge_id]
                if not self.is_directed and np.random.rand() > 0.5:
                    v[i], u[i] = self.edges[edge_id]

            vec_error = np.zeros((batch_size, self.dimension))
            label, target = np.asarray([1 for i in range(batch_size)]), np.asarray(v)
            for j in range(1 + self.negative):
                if j != 0:
                    label = np.asarray([0 for i in range(batch_size)])
                    for i in range(batch_size):
                        target[i] = alias_draw(self.node_table, self.node_prob)
                if order == 1:
                    self._update(
                        self.emb_vertex[u], self.emb_vertex[target], vec_error, label
                    )
                else:
                    self._update(
                        self.emb_vertex[u], self.emb_context[target], vec_error, label
                    )
            self.emb_vertex[u] += vec_error 
开发者ID:THUDM,项目名称:cogdl,代码行数:38,代码来源:line.py


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