### PageRank Initialization and Usage Example Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/ranking/pagerank.html Demonstrates how to initialize the PageRank class and compute scores for a given graph. The example uses the 'house' dataset and specifies a personalized restart distribution. ```python from sknetwork.ranking import PageRank from sknetwork.data import house pagerank = PageRank() adjacency = house() weights = {0: 1} scores = pagerank.fit_predict(adjacency, weights) np.round(scores, 2) ``` -------------------------------- ### Load Dataset Example Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/data/load.html Demonstrates how to save a dataset and then load it back using sknetwork.data.save and sknetwork.data.load. ```python from sknetwork.data import save from sknetwork.data import load from scipy import sparse import numpy as np from pathlib import Path # Assuming Dataset class is defined elsewhere and has adjacency and names attributes # For demonstration, we'll mock a simple structure class MockDataset: def __init__(self): self.adjacency = None self.names = None dataset = MockDataset() dataset.adjacency = sparse.csr_matrix(np.random.random((3, 3)) < 0.5) dataset.names = np.array(['a', 'b', 'c']) save('dataset', dataset) dataset = load('dataset') print(dataset.names) ``` -------------------------------- ### PropagationClustering Example Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/clustering/propagation_clustering.html Demonstrates how to use PropagationClustering to find clusters in a graph. The example uses the karate club dataset and fits the model to the adjacency matrix. ```python from sknetwork.clustering import PropagationClustering from sknetwork.data import karate_club propagation = PropagationClustering() graph = karate_club(metadata=True) adjacency = graph.adjacency labels = propagation.fit_predict(adjacency) len(set(labels)) ``` -------------------------------- ### PageRank Calculation Example Source: https://scikit-network.readthedocs.io/en/latest/reference/ranking.html Demonstrates how to compute PageRank scores for nodes in a graph using the PageRank class. The example initializes PageRank, creates a graph, and then fits and predicts the scores. ```python from sknetwork.ranking import PageRank from sknetwork.data import house pagerank = PageRank() adjacency = house() weights = {0: 1} scores = pagerank.fit_predict(adjacency, weights) np.round(scores, 2) ``` -------------------------------- ### LouvainEmbedding Example Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/embedding/louvain_embedding.html Demonstrates how to use LouvainEmbedding to get an embedding of a graph. The embedding's shape indicates the number of nodes and the number of detected communities. ```python from sknetwork.embedding import LouvainEmbedding from sknetwork.data import house louvain = LouvainEmbedding() adjacency = house() embedding = louvain.fit_transform(adjacency) print(embedding.shape) ``` -------------------------------- ### Leiden Algorithm Example Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/clustering/leiden.html Demonstrates how to use the Leiden algorithm to find clusters in a graph. Requires importing the Leiden class and a graph dataset. ```python from sknetwork.clustering import Leiden from sknetwork.data import karate_club leiden = Leiden() adjacency = karate_club() labels = leiden.fit_predict(adjacency) print(len(set(labels))) ``` -------------------------------- ### LouvainHierarchy Example Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/hierarchy/louvain_hierarchy.html Demonstrates how to use LouvainHierarchy for hierarchical clustering. It fits the model to the graph and predicts the clustering at each level. ```python from sknetwork.hierarchy import LouvainHierarchy from sknetwork.data import house louvain = LouvainHierarchy() adjacency = house() louvain.fit_predict(adjacency) ``` -------------------------------- ### Louvain Algorithm Example Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/clustering/louvain.html Demonstrates how to use the Louvain algorithm to cluster nodes in a graph. The algorithm fits the graph and predicts the community labels for each node. ```python from sknetwork.clustering import Louvain from sknetwork.data import karate_club louvain = Louvain() adjacency = karate_club() labels = louvain.fit_predict(adjacency) len(set(labels)) ``` -------------------------------- ### Create a Mask for Positive Examples Source: https://scikit-network.readthedocs.io/en/latest/_sources/use_cases/recommendation.ipynb.txt Generates a boolean mask to identify positive examples (movies watched by the user) for use in recommendation algorithms. ```python mask = np.zeros(len(names), dtype=bool) mask[targets] = 1 ``` -------------------------------- ### Import toy graph datasets and visualization functions Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/data/toy_graphs.ipynb.txt Imports various toy graph datasets and the visualization functions from scikit-network. Ensure these are installed before running. ```python from sknetwork.data import house, bow_tie, karate_club, miserables, painters, hourglass, star_wars, movie_actor from sknetwork.visualization import visualize_graph, visualize_bigraph ``` -------------------------------- ### HITS Algorithm Example Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/ranking/hits.html Demonstrates how to use the HITS class to compute hub and authority scores on a biadjacency matrix. The example uses the star_wars dataset and prints the rounded scores. ```python from sknetwork.ranking import HITS from sknetwork.data import star_wars hits = HITS() biadjacency = star_wars() scores = hits.fit_predict(biadjacency) np.round(scores, 2) ``` -------------------------------- ### Initialize DiffusionClassifier Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/classification/metrics.ipynb.txt Initializes the DiffusionClassifier model. No specific setup is required before this step. ```python diffusion = DiffusionClassifier() ``` -------------------------------- ### HITS Algorithm Example Source: https://scikit-network.readthedocs.io/en/latest/reference/ranking.html Demonstrates how to use the HITS algorithm to compute hub and authority scores on a bipartite graph. Requires importing HITS and a graph dataset. ```python from sknetwork.ranking import HITS from sknetwork.data import star_wars hits = HITS() biadjacency = star_wars() scores = hits.fit_predict(biadjacency) import numpy as np np.round(scores, 2) ``` -------------------------------- ### NNLinker Initialization and Usage Example Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/linkpred/nn.html Demonstrates how to initialize NNLinker and use it for link prediction on the karate club graph. The number of neighbors and the similarity threshold can be configured. ```python from sknetwork.linkpred import NNLinker from sknetwork.data import karate_club linker = NNLinker(n_neighbors=5, threshold=0.5) graph = karate_club(metadata=True) adjacency = graph.adjacency links = linker.fit_predict(adjacency) print(links.shape) ``` -------------------------------- ### Install scikit-network from source Source: https://scikit-network.readthedocs.io/en/latest/first_steps.html Install scikit-network by downloading the source code and running the setup script. This is useful for development or custom builds. ```bash cd python setup.py develop ``` -------------------------------- ### ForceAtlas Initialization and Fit Example Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/embedding/force_atlas.html Demonstrates how to initialize and use the ForceAtlas layout algorithm to compute node positions for a graph. Requires the karate_club dataset and the ForceAtlas class. ```python from sknetwork.embedding.force_atlas import ForceAtlas from sknetwork.data import karate_club force_atlas = ForceAtlas() adjacency = karate_club() embedding = force_atlas.fit_transform(adjacency) print(embedding.shape) ``` -------------------------------- ### Install scikit-network Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/overview/get_started.ipynb.txt Use pip to install the scikit-network package. Uncomment the line to execute the installation. ```python # uncomment to install # !pip install scikit-network ``` -------------------------------- ### SparseLR Class Initialization and Basic Usage Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/linalg/sparse_lowrank.html Demonstrates how to initialize the SparseLR class with a sparse matrix and a low-rank component, and perform basic operations like dot product and sum. ```python from scipy import sparse from sknetwork.linalg import SparseLR adjacency = sparse.eye(2, format='csr') slr = SparseLR(adjacency, (np.ones(2), np.ones(2))) x = np.ones(2) slr.dot(x) slr.sum(axis=0) slr.sum(axis=1) float(slr.sum()) ``` -------------------------------- ### Install scikit-network Source: https://scikit-network.readthedocs.io/en/latest/index.html Use pip to install the scikit-network library. ```bash $ pip install scikit-network ``` -------------------------------- ### Dirichlet Regression Example Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/regression/diffusion.html Demonstrates how to use the Dirichlet class to predict node values based on initial conditions. Requires importing Dirichlet and a graph dataset. ```python from sknetwork.regression import Dirichlet from sknetwork.data import house dirichlet = Dirichlet() adjacency = house() values = {0: 1, 2: 0} values_pred = dirichlet.fit_predict(adjacency, values) np.round(values_pred, 2) ``` -------------------------------- ### Spring Layout Fit Method with Custom Initialization Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/embedding/spring.html Shows how to use the `fit` method of the Spring layout with custom initial positions. It also demonstrates overriding the default number of iterations. ```python from sknetwork.embedding import Spring from sknetwork.data import karate_club spring = Spring(n_iter=100) adjacency = karate_club() position_init = np.random.randn(adjacency.shape[0], 2) spring.fit(adjacency, position_init=position_init, n_iter=50) print(spring.embedding_.shape) ``` -------------------------------- ### Install Scikit-network Source: https://scikit-network.readthedocs.io/en/latest/_sources/first_steps.rst.txt Install scikit-network using pip. This is the recommended method for most users. ```console pip install scikit-network ``` -------------------------------- ### Install scikit-network via pip Source: https://scikit-network.readthedocs.io/en/latest/first_steps.html Use this command to install the package directly from the Python Package Index. ```bash pip install scikit-network ``` -------------------------------- ### Install Scikit-network from Source Source: https://scikit-network.readthedocs.io/en/latest/_sources/first_steps.rst.txt Install scikit-network from source code. This method is useful for developers or when specific versions are needed. ```console cd python setup.py develop ``` -------------------------------- ### Initialize and Use LouvainEmbedding Source: https://scikit-network.readthedocs.io/en/latest/reference/embedding.html Demonstrates how to initialize the LouvainEmbedding class and use it to compute the embedding of a graph. The adjacency matrix is obtained from the 'house' dataset. ```python >>> from sknetwork.embedding import LouvainEmbedding >>> from sknetwork.data import house >>> louvain = LouvainEmbedding() >>> adjacency = house() >>> embedding = louvain.fit_transform(adjacency) >>> embedding.shape (5, 2) ``` -------------------------------- ### Get Node Index for Dendrogram Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/visualization/dendrograms.html Helper function to get the order of nodes in a dendrogram, with an option to reorder based on subtree size. ```python def get_index(dendrogram, reorder=True): """Index nodes for pretty dendrogram.""" n = dendrogram.shape[0] + 1 tree = {i: [i] for i in range(n)} for t in range(n - 1): i = int(dendrogram[t, 0]) j = int(dendrogram[t, 1]) left: list = tree.pop(i) right: list = tree.pop(j) if reorder and len(left) < len(right): tree[n + t] = right + left else: tree[n + t] = left + right return list(tree.values())[0] ``` -------------------------------- ### Initialize Louvain Clustering Source: https://scikit-network.readthedocs.io/en/latest/use_cases/votes.html Instantiate the Louvain clustering algorithm object. ```python louvain = Louvain() ``` -------------------------------- ### K-Centers Initialization and Iteration Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/clustering/kcenters.html This snippet illustrates the core logic of the K-Centers algorithm, including node assignment to centers using PageRank and the iterative refinement of center selection. It handles both bipartite and non-bipartite graphs and selects the best clustering based on modularity across multiple initializations. ```python if min(ppr_scores) == 0: center = np.random.choice(nodes[mask][ppr_scores == 0]) else: probs = 1 / ppr_scores probs = probs / np.sum(probs) center = np.random.choice(nodes[mask], p=probs) mask[center] = 0 centers.append(center) weights.update({center: 1}) centers = np.array(centers) return centers ``` ```python if self.n_clusters < 2: raise ValueError("The number of clusters must be at least 2.") if self.n_init < 1: raise ValueError("The n_init parameter must be at least 1.") if self.directed: input_matrix = directed2undirected(input_matrix) adjacency, self.bipartite = get_adjacency(input_matrix, force_bipartite=force_bipartite) n_row = input_matrix.shape[0] n_nodes = adjacency.shape[0] nodes = np.arange(n_nodes) mask = self._compute_mask_centers(input_matrix) if self.n_clusters > np.sum(mask): raise ValueError("The number of clusters is to high. This might be due to the center_position parameter.") pagerank_clf = PageRankClassifier() pagerank = PageRank() labels_ = [] centers_ = [] modularity_ = [] # Restarts for i in range(self.n_init): # Initialization centers = self._init_centers(adjacency, mask, self.n_clusters) prev_centers = None labels = None n_iter = 0 while not np.equal(prev_centers, centers).all() and (n_iter < self.max_iter): # Assign nodes to centers labels_center = {center: label for label, center in enumerate(centers)} labels = pagerank_clf.fit_predict(adjacency, labels_center) # Find new centers prev_centers = centers.copy() new_centers = [] for label in np.unique(labels): mask_cluster = labels == label mask_cluster &= mask scores = pagerank.fit_predict(adjacency, weights=mask_cluster) scores[~mask_cluster] = 0 new_centers.append(nodes[np.argmax(scores)]) n_iter += 1 # Store results if self.bipartite: labels_row = labels[:n_row] labels_col = labels[n_row:] modularity = get_modularity(input_matrix, labels_row, labels_col) else: modularity = get_modularity(adjacency, labels) labels_.append(labels) centers_.append(centers) modularity_.append(modularity) # Select restart with the highest modularity idx_max = np.argmax(modularity_) self.labels_ = np.array(labels_[idx_max]) self.centers_ = np.array(centers_[idx_max]) if self.bipartite: self._split_vars(input_matrix.shape) # Define centers based on center position if self.center_position == "row": self.centers_row_ = self.centers_ elif self.center_position == "col": self.centers_col_ = self.centers_ - n_row else: self.centers_row_ = self.centers_[self.centers_ < n_row] self.centers_col_ = self.centers_[~np.isin(self.centers_, self.centers_row_)] - n_row return self ``` -------------------------------- ### Importing necessary libraries Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/clustering/kcenters.ipynb.txt Before running the k-centers algorithm, import the required libraries: `numpy` for numerical operations and `scikit-network` for the clustering algorithm. ```python import numpy as np from sknetwork.clustering import k_centers ``` -------------------------------- ### KCenters Clustering Example Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/clustering/kcenters.html Demonstrates how to use the KCenters class to perform clustering on a graph. Requires the karate club dataset and the KCenters class. The output shows the number of clusters found. ```python from sknetwork.clustering import KCenters from sknetwork.data import karate_club kcenters = KCenters(n_clusters=2) adjacency = karate_club() labels = kcenters.fit_predict(adjacency) len(set(labels)) ``` -------------------------------- ### Spring Layout Initialization and Transformation Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/embedding/spring.html Demonstrates how to initialize the Spring layout and apply it to a graph. The `fit_transform` method computes the node embeddings. The resulting embedding shape is printed. ```python from sknetwork.embedding import Spring from sknetwork.data import karate_club spring = Spring() adjacency = karate_club() embedding = spring.fit_transform(adjacency) print(embedding.shape) ``` -------------------------------- ### Get Neighbors of a Node in a Graph Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/utils/neighbors.html Retrieves the neighbors (successors by default) of a specific node in a graph. For directed graphs, set `transpose=True` to get predecessors. Works with adjacency or biadjacency matrices. ```python from sknetwork.data import house adjacency = house() print(get_neighbors(adjacency, node=0)) ``` -------------------------------- ### Get Node Neighbors Source: https://scikit-network.readthedocs.io/en/latest/reference/utils.html Finds the direct neighbors of a specified node. For directed graphs, this returns successors by default; set transpose=True to get predecessors. This function is applicable to both adjacency and biadjacency matrices. ```python from sknetwork.data import house adjacency = house() get_neighbors(adjacency, node=0) array([1, 4], dtype=int32) ``` -------------------------------- ### Initialize and Use Propagation for Node Classification Source: https://scikit-network.readthedocs.io/en/latest/reference/classification.html This example demonstrates how to initialize the Propagation class and use it to predict labels on a graph. It requires importing the class and a dataset, then fitting the model with initial labels and predicting the rest. ```python >>> from sknetwork.classification import Propagation >>> from sknetwork.data import karate_club >>> propagation = Propagation() >>> graph = karate_club(metadata=True) >>> adjacency = graph.adjacency >>> labels_true = graph.labels >>> labels = {0: labels_true[0], 33: labels_true[33]} >>> labels_pred = propagation.fit_predict(adjacency, labels) >>> float(np.round(np.mean(labels_pred == labels_true), 2)) 0.94 ``` -------------------------------- ### Get Weights of Nodes in a Graph Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/utils/neighbors.html Computes the total weight of outgoing links for each node (out-weights). If the graph is unweighted, it returns the out-degrees. Set `transpose=True` to get in-weights. Works for weighted and unweighted graphs. ```python from sknetwork.data import house adjacency = house() print(get_weights(adjacency)) ``` -------------------------------- ### GNNClassifier Example: Karate Club Node Classification Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/gnn/gnn_classifier.html Demonstrates how to use GNNClassifier for node classification on the Karate Club dataset. It shows model initialization, fitting, and prediction, with early stopping disabled for this example. ```python from sknetwork.gnn.gnn_classifier import GNNClassifier from sknetwork.data import karate_club from numpy.random import randint graph = karate_club(metadata=True) adjacency = graph.adjacency labels_true = graph.labels labels = {i: labels_true[i] for i in [0, 1, 33]} features = adjacency.copy() gnn = GNNClassifier(dims=1, early_stopping=False) labels_pred = gnn.fit_predict(adjacency, features, labels, random_state=42) float(round(np.mean(labels_pred == labels_true), 2)) ``` -------------------------------- ### Initialize and Apply Louvain Clustering Source: https://scikit-network.readthedocs.io/en/latest/_sources/use_cases/votes.ipynb.txt Initializes the Louvain clustering algorithm and applies it to the 'for' vote biadjacency matrix to predict community labels. ```python louvain = Louvain() ``` ```python labels_pred = louvain.fit_predict(biadjacency_for) ``` ```python np.unique(labels_pred, return_counts=True) ``` -------------------------------- ### NNLinker.get_params Source: https://scikit-network.readthedocs.io/en/latest/reference/linkpred.html Get parameters as dictionary. ```APIDOC ## get_params ### Description Get parameters as dictionary. ### Returns #### Returns - **params** (dict) - Parameters of the algorithm. ### Return type dict ``` -------------------------------- ### Louvain Initialization Source: https://scikit-network.readthedocs.io/en/latest/reference/hierarchy.html Initializes the Louvain algorithm with an input matrix and an optional flag to force bipartite interpretation. ```APIDOC ## Louvain ### Parameters * **input_matrix** (_sparse.csr_matrix_ _,__np.ndarray_) – Adjacency matrix or biadjacency matrix of the graph. * **force_bipartite** – If `True`, force the input matrix to be considered as a biadjacency matrix. ### Returns **self** ### Return type `LouvainIteration` ``` -------------------------------- ### sknetwork.path.breadth_first_search Source: https://scikit-network.readthedocs.io/en/latest/reference/path.html Breadth-first ordering starting from some node. ```APIDOC ## sknetwork.path.breadth_first_search ### Description Breadth-first ordering starting from some node. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **adjacency** (csr_matrix) - Adjacency matrix of the graph. * **source** (int) - Source node. ### Returns **index** – Node index corresponding to the breadth-first-search from the source. The length of the vector is the number of nodes reachable from the source. Return type: np.ndarray ``` -------------------------------- ### Initialize and Fit Force Atlas Layout Source: https://scikit-network.readthedocs.io/en/latest/reference/embedding.html Demonstrates how to initialize the ForceAtlas class and compute the node embeddings using the fit_transform method with the karate club dataset. The shape of the resulting embedding is then checked. ```python >>> from sknetwork.embedding.force_atlas import ForceAtlas >>> from sknetwork.data import karate_club >>> force_atlas = ForceAtlas() >>> adjacency = karate_club() >>> embedding = force_atlas.fit_transform(adjacency) >>> embedding.shape (34, 2) ``` -------------------------------- ### sknetwork.hierarchy.reorder_dendrogram Source: https://scikit-network.readthedocs.io/en/latest/_sources/reference/hierarchy.rst.txt Reorders the nodes in a dendrogram, for example, for visualization purposes. ```APIDOC ## sknetwork.hierarchy.reorder_dendrogram ### Description Reorders the nodes in a dendrogram, for example, for visualization purposes. ### Function `sknetwork.hierarchy.reorder_dendrogram` ``` -------------------------------- ### reindex_labels Source: https://scikit-network.readthedocs.io/en/latest/_sources/reference/clustering.rst.txt Reindexes the cluster labels to be contiguous starting from 0. ```APIDOC ## reindex_labels ### Description Reindexes the cluster labels to be contiguous starting from 0. ### Parameters - **labels** (ndarray): The cluster labels to reindex. ``` -------------------------------- ### sknetwork.path.get_distances Source: https://scikit-network.readthedocs.io/en/latest/reference/path.html Get the distances from a source (or a set of sources) in number of hops. ```APIDOC ## sknetwork.path.get_distances ### Description Get the distances from a source (or a set of sources) in number of hops. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **input_matrix** (csr_matrix) - Adjacency matrix or biadjacency matrix of the graph. * **source** (int | Iterable | None) - If an integer, index of the source node. If a list or array, indices of source nodes (the shortest distances to one of these nodes is returned). * **source_row** (int | Iterable | None) - For bipartite graphs, index of source nodes on rows and columns. The parameter source_row is an alias for source (at least one of them must be `None`). * **source_col** (int | Iterable | None) - For bipartite graphs, index of source nodes on rows and columns. The parameter source_row is an alias for source (at least one of them must be `None`). * **transpose** (bool) - If `True`, transpose the input matrix. * **force_bipartite** (bool) - If `True`, consider the input matrix as the biadjacency matrix of a bipartite graph. Set to `True` is the parameters source_row or source_col re specified. ### Returns **distances** – Vector of distances from source (distance = -1 if no path exists from the source). For a bipartite graph, two vectors are returned, one for the rows and one for the columns. Return type: np.ndarray of shape (n_nodes,) ### Request Example ```python >>> from sknetwork.data import cyclic_digraph >>> adjacency = cyclic_digraph(3) >>> get_distances(adjacency, source=0) array([0, 1, 2]) >>> get_distances(adjacency, source=[0, 2]) array([0, 1, 0]) ``` ``` -------------------------------- ### Import necessary libraries Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/visualization/pie_charts.ipynb.txt Imports IPython.display for SVG output and scipy.sparse for sparse matrix operations. ```python from IPython.display import SVG from scipy import sparse ``` -------------------------------- ### Initialize Louvain Algorithm Source: https://scikit-network.readthedocs.io/en/latest/_sources/use_cases/wikipedia.ipynb.txt Initializes the Louvain algorithm for graph clustering. This is the first step before applying the clustering to a graph. ```python algo = Louvain() ``` -------------------------------- ### sknetwork.path.get_shortest_path Source: https://scikit-network.readthedocs.io/en/latest/reference/path.html Get the shortest paths from a source (or a set of sources) in number of hops. ```APIDOC ## sknetwork.path.get_shortest_path ### Description Get the shortest paths from a source (or a set of sources) in number of hops. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **input_matrix** (csr_matrix) - Adjacency matrix or biadjacency matrix of the graph. * **source** (int | Iterable | None) - If an integer, index of the source node. If a list, indices of source nodes (the shortest distances to one of these nodes in returned). * **source_row** (int | Iterable | None) - For bipartite graphs, index of source nodes on rows and columns. The parameter source_row is an alias for source (at least one of them must be `None`). * **source_col** (int | Iterable | None) - For bipartite graphs, index of source nodes on rows and columns. The parameter source_row is an alias for source (at least one of them must be `None`). * **force_bipartite** (bool) - If `True`, consider the input matrix as the biadjacency matrix of a bipartite graph. Set to `True` is the parameters source_row or source_col are specified. ### Returns **path** – Adjacency matrix of the graph of the shortest paths from the source node (or the set of source nodes). If the input graph is a bipartite graph, the shape of the matrix is (n_row + n_col, n_row + n_col) with the new index corresponding to the rows then the columns of the original graph. Return type: sparse.csr_matrix ### Request Example ```python >>> from sknetwork.data import cyclic_digraph >>> adjacency = cyclic_digraph(3) >>> path = get_shortest_path(adjacency, source=0) >>> path.toarray().astype(int) array([[0, 1, 0], [0, 0, 1], [0, 0, 0]]) ``` ``` -------------------------------- ### Print Beginning of Text Source: https://scikit-network.readthedocs.io/en/latest/_sources/use_cases/text.ipynb.txt Prints the first 494 characters of the loaded text to the console. ```python print(text[:494]) ``` -------------------------------- ### Get 'People' Category ID Source: https://scikit-network.readthedocs.io/en/latest/_sources/use_cases/wikipedia.ipynb.txt Retrieves the numerical ID for the 'People' category from a mapping. ```python people = label_id['People'] ``` -------------------------------- ### NNLinker Example: Predicting Links Source: https://scikit-network.readthedocs.io/en/latest/reference/linkpred.html Demonstrates how to initialize NNLinker, fit it to a graph's adjacency matrix, and predict links. The resulting links matrix shape is shown. ```python >>> from sknetwork.linkpred import NNLinker >>> from sknetwork.data import karate_club >>> linker = NNLinker(n_neighbors=5, threshold=0.5) >>> graph = karate_club(metadata=True) >>> adjacency = graph.adjacency >>> links = linker.fit_predict(adjacency) >>> links.shape (34, 34) ``` -------------------------------- ### Prepare Training Data Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/gnn/gnn_classifier.ipynb.txt Sets up the training labels by masking a portion of the true labels. ```python # Training set labels = labels_true.copy() np.random.seed(42) train_mask = np.random.random(size=len(labels)) < 0.5 labels[train_mask] = -1 ``` -------------------------------- ### Get Length of Text Source: https://scikit-network.readthedocs.io/en/latest/_sources/use_cases/text.ipynb.txt Calculates and returns the total number of characters in the loaded text. ```python len(text) ``` -------------------------------- ### Get Core Decomposition Values Source: https://scikit-network.readthedocs.io/en/latest/_sources/use_cases/sport.ipynb.txt Calculates the core decomposition values for an undirected graph. ```python values = get_core_decomposition(adjacency_sym) ``` -------------------------------- ### Import Visualization Tools Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/overview/get_started.ipynb.txt Import necessary functions for graph visualization, including SVG display and the visualize_graph function. ```python from IPython.display import SVG from sknetwork.visualization import visualize_graph ``` -------------------------------- ### Import necessary libraries Source: https://scikit-network.readthedocs.io/en/latest/tutorials/clustering/louvain.html Imports all required modules for data loading, clustering, normalization, and visualization. ```python from sknetwork.data import karate_club, painters, movie_actor from sknetwork.clustering import Louvain, get_modularity from sknetwork.linalg import normalize from sknetwork.utils import get_membership from sknetwork.visualization import visualize_graph, visualize_bigraph ``` -------------------------------- ### Get dimensions of the biadjacency matrix Source: https://scikit-network.readthedocs.io/en/latest/use_cases/votes.html Determines the number of deputies and bills from the shape of the biadjacency matrix. ```python n_deputy, n_bill = biadjacency.shape ``` -------------------------------- ### Import visualization functions and data loaders Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/visualization/graphs.ipynb.txt Import data loading functions like `karate_club` and visualization functions `visualize_graph`, `visualize_bigraph`. ```python from sknetwork.data import karate_club, painters, movie_actor, load_netset from sknetwork.visualization import visualize_graph, visualize_bigraph ``` -------------------------------- ### Get Number of Movies and Users Source: https://scikit-network.readthedocs.io/en/latest/_sources/use_cases/recommendation.ipynb.txt Determines the number of movies and users from the shape of the biadjacency matrix. ```python n_movies, n_users = biadjacency.shape ``` -------------------------------- ### Import necessary libraries Source: https://scikit-network.readthedocs.io/en/latest/tutorials/embedding/gsvd.html Import libraries for data handling, GSVD, and visualization. ```python from IPython.display import SVG ``` ```python import numpy as np ``` ```python from sknetwork.data import karate_club, painters, movie_actor from sknetwork.embedding import GSVD from sknetwork.visualization import visualize_graph, visualize_bigraph ``` -------------------------------- ### Get Bias Shapes in GraphSAGE Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/gnn/gnn_classifier.ipynb.txt Displays the shapes of the bias vectors for each layer in the GraphSAGE model. ```python [bias.shape for bias in biases] ``` -------------------------------- ### Import necessary libraries Source: https://scikit-network.readthedocs.io/en/latest/tutorials/clustering/propagation.html Imports modules for data loading, clustering, linear algebra, utility functions, and visualization. ```python from sknetwork.data import karate_club, painters, movie_actor from sknetwork.clustering import PropagationClustering, get_modularity from sknetwork.linalg import normalize from sknetwork.utils import get_membership from sknetwork.visualization import visualize_graph, visualize_bigraph ``` -------------------------------- ### Get Weight Shapes in GraphSAGE Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/gnn/gnn_classifier.ipynb.txt Displays the shapes of the weight matrices for each layer in the GraphSAGE model. ```python [weight.shape for weight in weights] ``` -------------------------------- ### Import necessary libraries Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/classification/propagation.ipynb.txt Imports `SVG` for displaying visualizations. ```python from IPython.display import SVG ``` -------------------------------- ### Set up local development environment Source: https://scikit-network.readthedocs.io/en/latest/contributing.html Install scikit-network into a virtual environment for local development using virtualenvwrapper. ```bash $ mkvirtualenv sknetwork $ cd sknetwork/ $ python setup.py develop ``` -------------------------------- ### Label Propagation Example Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/classification/propagation.html Demonstrates how to use the Propagation classifier to predict node labels on a graph. Initializes the classifier, fits it to the adjacency matrix and known labels, and predicts the labels for the remaining nodes. ```python from sknetwork.classification import Propagation from sknetwork.data import karate_club propagation = Propagation() graph = karate_club(metadata=True) adjacency = graph.adjacency labels_true = graph.labels labels = {0: labels_true[0], 33: labels_true[33]} labels_pred = propagation.fit_predict(adjacency, labels) float(np.round(np.mean(labels_pred == labels_true), 2)) ``` -------------------------------- ### Get Prediction Probabilities Source: https://scikit-network.readthedocs.io/en/latest/tutorials/gnn/gnn_classifier.html Obtains the probability distribution over labels for each node in the graph from the trained GNN classifier. ```python # probability distribution over labels probs = gnn.predict_proba() ``` -------------------------------- ### Get Length of Main Text Source: https://scikit-network.readthedocs.io/en/latest/_sources/use_cases/text.ipynb.txt Calculates and returns the number of characters in the extracted main text content. ```python len(main) ``` -------------------------------- ### Configure and fit RandomProjection for bipartite graphs Source: https://scikit-network.readthedocs.io/en/latest/tutorials/embedding/random_projection.html Initializes RandomProjection with specific parameters (normalized=False) and fits it to a bipartite graph's biadjacency matrix. The default parameters are shown for reference. ```python graph = movie_actor(metadata=True) biadjacency = graph.biadjacency names_row = graph.names_row names_col = graph.names_col ``` ```python projection = RandomProjection(2, normalized=False) projection.fit(biadjacency) ``` ```python RandomProjection(n_components=2, alpha=0.5, n_iter=3, random_walk=False, regularization=-1, normalized=False) ``` -------------------------------- ### Get probability distribution over labels Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/classification/diffusion.ipynb.txt Calculates the probability distribution for each node belonging to each class after fitting the classifier. ```python # probability distribution over labels probs = diffusion.predict_proba() ``` -------------------------------- ### Import visualization and clustering tools Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/visualization/pie_charts.ipynb.txt Imports functions for graph data generation, visualization, and Louvain clustering. ```python from sknetwork.data import bow_tie, karate_club, painters from sknetwork.visualization import visualize_graph from sknetwork.clustering import Louvain ``` -------------------------------- ### Prepare Training Data Source: https://scikit-network.readthedocs.io/en/latest/tutorials/gnn/gnn_classifier.html Prepares the training labels by copying the true labels and masking a portion for training. Uses a random seed for reproducibility. ```python # Training set labels = labels_true.copy() np.random.seed(42) train_mask = np.random.random(size=len(labels)) < 0.5 labels[train_mask] = -1 ``` -------------------------------- ### Get GNN Bias Shapes Source: https://scikit-network.readthedocs.io/en/latest/tutorials/gnn/gnn_classifier.html Display the shapes of the biases for each layer in the GNN. This shows the dimensionality of the learned biases. ```python [bias.shape for bias in biases] ``` -------------------------------- ### Count Column Names Source: https://scikit-network.readthedocs.io/en/latest/tutorials/data/load_data.html Get the total number of column names, which represents the number of features in the binarized dataset. ```python len(names_col) ``` -------------------------------- ### Import Bunch, load, and save functions Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/data/save.ipynb.txt Import the core components for data handling: Bunch for structuring graph data, and load/save for persistence. ```python from sknetwork.data import Bunch, load, save ``` -------------------------------- ### Perform Louvain embedding Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/embedding/louvain_embedding.ipynb.txt Applies the LouvainEmbedding algorithm to the graph's adjacency matrix and gets the embedding shape. ```python louvain = LouvainEmbedding() embedding = louvain.fit_transform(adjacency) embedding.shape ``` -------------------------------- ### Import classification and visualization tools Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/classification/propagation.ipynb.txt Imports graph datasets, the `Propagation` classifier, and visualization functions. ```python from sknetwork.data import karate_club, painters, movie_actor from sknetwork.classification import Propagation from sknetwork.visualization import svg_graph, visualize_bigraph ``` -------------------------------- ### sknetwork.data.bow_tie Source: https://scikit-network.readthedocs.io/en/latest/_sources/reference/data.rst.txt Generates a toy graph representing a bow-tie structure. This is a predefined graph useful for network analysis examples. ```APIDOC ## sknetwork.data.bow_tie ### Description Generates a toy graph representing a bow-tie structure. ### Method Not applicable (Python function) ### Parameters (Details not provided in source) ### Request Example (Not provided in source) ### Response (Details not provided in source) ``` -------------------------------- ### Instantiate Optimizer with get_optimizer Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/gnn/optimizer.html Use the get_optimizer function to create an optimizer instance. It supports 'Adam' and 'GD' (Gradient Descent) by name, or accepts a custom optimizer object. Specify the learning rate when using named optimizers. ```python from typing import Union from sknetwork.gnn.optimizer import get_optimizer, BaseOptimizer, ADAM, GD # Example usage: optimizer_adam = get_optimizer('Adam', learning_rate=0.005) print(f"Created optimizer: {type(optimizer_adam).__name__}") optimizer_gd = get_optimizer('GD', learning_rate=0.01) print(f"Created optimizer: {type(optimizer_gd).__name__}") # Using a custom optimizer object custom_optimizer = ADAM(learning_rate=0.001) optimizer_custom = get_optimizer(custom_optimizer) print(f"Created optimizer: {type(optimizer_custom).__name__}") # Example of invalid input try: get_optimizer('SGD') except ValueError as e: print(f"Error: {e}") try: get_optimizer(123) except TypeError as e: print(f"Error: {e}") ``` -------------------------------- ### Display Sample of Seen Movies Source: https://scikit-network.readthedocs.io/en/latest/use_cases/recommendation.html Shows a sample of the movie titles that the user has seen. This helps in understanding the input data for the recommendation process. ```python # seen movies (sample) names[targets][:10] ``` -------------------------------- ### Calculate Personalized PageRank Source: https://scikit-network.readthedocs.io/en/latest/use_cases/recommendation.html Computes personalized PageRank scores, starting from a specific target movie (index 175). ```python scores_ppr = pagerank.fit_predict(positive, weights={175:1}) ``` -------------------------------- ### Import scikit-network modules Source: https://scikit-network.readthedocs.io/en/latest/tutorials/visualization/dendrograms.html Import data loading functions, the Paris clustering algorithm, and visualization utilities. ```python from sknetwork.data import karate_club, painters, movie_actor from sknetwork.hierarchy import Paris from sknetwork.visualization import visualize_graph, visualize_bigraph from sknetwork.visualization import visualize_dendrogram ``` -------------------------------- ### Visualize Louvain Embedding with Cytoscape Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/embedding/louvain_embedding.ipynb.txt Visualize the computed Louvain embedding using a Cytoscape graph. This requires the 'cytoscape-jupyter-widget' to be installed. ```python from sknetwork.visualization import svg_graph, display_graph # Visualize the graph with Louvain communities # The embedding object contains the community labels image = svg_graph(G, embedding.labels_) display_graph(image) ``` -------------------------------- ### Initialize PageRank for Bipartite Graphs Source: https://scikit-network.readthedocs.io/en/latest/_sources/tutorials/ranking/pagerank.ipynb.txt Initializes the PageRank algorithm. This object will be used to compute scores on the bipartite graph. ```python pagerank = PageRank() ``` -------------------------------- ### Get cluster probabilities for bipartite graph Source: https://scikit-network.readthedocs.io/en/latest/tutorials/clustering/louvain.html Calculates the probability distribution over clusters for both row and column nodes in the bipartite graph. ```python # probability distribution over clusters probs_row = louvain.predict_proba() probs_col = louvain.predict_proba(columns=True) ``` -------------------------------- ### Get cluster probabilities for Karate Club graph Source: https://scikit-network.readthedocs.io/en/latest/tutorials/clustering/propagation.html Calculates the probability distribution over clusters for each node in the Karate Club graph. ```python probs = propagation.predict_proba() # scores for cluster 1 scores = probs[:,1] image = visualize_graph(adjacency, position, scores=scores) SVG(image) ``` -------------------------------- ### Cluster Karate Club Graph with Louvain Algorithm Source: https://scikit-network.readthedocs.io/en/latest/_sources/first_steps.rst.txt Example of clustering the Karate club graph using the Louvain algorithm. This demonstrates a common use case for graph analysis. ```python from sknetwork.data import karate_club from sknetwork.clustering import Louvain adjacency = karate_club() algorithm = Louvain() algorithm.fit(adjacency) ``` -------------------------------- ### Spring Class Initialization Source: https://scikit-network.readthedocs.io/en/latest/reference/embedding.html Initializes the Spring layout algorithm with specified parameters for graph embedding. ```APIDOC ## Spring Class ### Description Initializes the Spring layout algorithm for displaying small graphs using a force-directed placement approach. ### Parameters * **n_components** (int) - Optional - Dimension of the graph layout. Defaults to 2. * **strength** (float) - Optional - Intensity of the force that moves the nodes. Defaults to None. * **n_iter** (int) - Optional - Number of iterations to update positions. Defaults to 50. * **tol** (float) - Optional - Minimum relative change in positions to continue updating. Defaults to 0.0001. * **approx_radius** (float) - Optional - If a positive value is provided, only the nodes within this distance a given node are used to compute the repulsive force. Defaults to -1. * **position_init** (str) - Optional - How to initialize the layout. If ‘spectral’, use Spectral embedding in dimension 2, otherwise, use random initialization. Defaults to 'random'. ``` -------------------------------- ### Get k-core decomposition of a graph Source: https://scikit-network.readthedocs.io/en/latest/reference/topology.html Calculates the core value for each node in a graph. Use this to understand the hierarchical structure of a network. ```python from sknetwork.data import karate_club adjacency = karate_club() core_values = get_core_decomposition(adjacency) len(core_values) ``` -------------------------------- ### Get Article Neighbors Source: https://scikit-network.readthedocs.io/en/latest/_sources/use_cases/wikipedia.ipynb.txt Retrieves the indices of neighboring articles for a given article and prints the names of the first 10 neighbors. ```python neighbors = get_neighbors(adjacency, i) print(names[neighbors[:10]]) ``` -------------------------------- ### Diffusion Example Source: https://scikit-network.readthedocs.io/en/latest/_modules/sknetwork/regression/diffusion.html Demonstrates how to use the Diffusion class to predict node values based on initial seed values and an adjacency matrix. The diffusion process is iterated a specified number of times with a given damping factor. ```python from sknetwork.data import house from sknetwork.regression import Diffusion diffusion = Diffusion(n_iter=1) adjacency = house() values = {0: 1, 2: 0} values_pred = diffusion.fit_predict(adjacency, values) print(np.round(values_pred, 1)) ```