pyreco package
Submodules
pyreco.cross_validation module
- pyreco.cross_validation.cross_val(model, X: ndarray, y: ndarray, n_splits: int, metric: str = 'mse') Tuple[List[float], float, float] [source]
Performs k-fold cross-validation on a given model.
Parameters: model : object
The RC model to be validated.
- Xnp.ndarray
Feature matrix.
- ynp.ndarray
Target vector.
- n_splitsint
Number of folds.
- metricsstr
Metric to evaluate.
Returns: tuple
A tuple containing: - list of metric’s value for each fold - mean of the metric values - standard deviation of the metric values
pyreco.custom_models module
- class pyreco.custom_models.AutoRC[source]
Bases:
CustomModel
Autonomous version of the reservoir computer.
- class pyreco.custom_models.CustomModel[source]
Bases:
ABC
Abstract base class for custom reservoir computing model.
Has a syntax similar to the one of TensorFlow model API, e.g. using the model.add() statement to add layers to the model.
A model hast an input layer, a reservoir layer and a readout layer.
- add(layer: Layer)[source]
Add a layer to the model.
Is type-sensitive and will assign the layer to the correct attribute.
Args: layer (Layer): Layer to be added to the model.
- compile(optimizer: str = 'ridge', metrics: list | str | None = None, discard_transients: int = 0)[source]
Configure the model for training.
Args: optimizer (str): Name of the optimizer. metrics (list): List of metric names. discard_transients (int): Number of initial transient timesteps to discard.
- compute_reservoir_state(x: ndarray) ndarray [source]
Vectorized computation of reservoir states with batch processing.
- Parameters:
x (np.ndarray) – Input data of shape [n_batch, n_timesteps, n_states]
- Returns:
Reservoir states of shape [(n_batch * n_timesteps), N]
- Return type:
np.ndarray
- evaluate(x: ndarray, y: ndarray, metrics: str | list | None = None) tuple [source]
Evaluate metrics on predictions made for input data.
Args: x (np.ndarray): Input data of shape [n_batch, n_timesteps, n_states] y (np.ndarray): Target data of shape [n_batch, n_timesteps_out, n_states_out] metrics (Union[str, list, None], optional): List of metric names or a single metric name. If None, use metrics from .compile()
Returns: tuple: Metric values
- fit(x: ndarray, y: ndarray, n_init: int = 1, store_states: bool = False) dict [source]
RC training with batch processing.
- get_hp(*args)[source]
Get one or more reservoir hyperparameters. If no args, returns all. Usage: get_hp(‘spec_rad’, ‘activation’) or get_hp()
- plot(path: str)[source]
Print the model to some figure file.
Args: path (str): Path to save the figure.
- class pyreco.custom_models.HybridRC[source]
Bases:
CustomModel
Hybrid version of the reservoir computer.
- class pyreco.custom_models.RC[source]
Bases:
CustomModel
Non-autonomous version of the reservoir computer.
pyreco.datasets module
pyreco.graph_analyzer module
- class pyreco.graph_analyzer.GraphAnalyzer(quantities=None)[source]
Bases:
object
A class for analyzing graph properties and extracting network properties from a graph.
- pyreco.graph_analyzer.available_extractors()[source]
Return a dictionary mapping network property names to their corresponding extractor functions. Make changes here if you want to add more network properties.
- Returns:
A dictionary mapping network property names to their corresponding extractor functions.
- Return type:
- pyreco.graph_analyzer.map_extractor_names(prop_names: str)[source]
Return a dictionary mapping network property names to their corresponding extractor functions for the given property names.
- Returns:
A dictionary mapping network property names to their corresponding extractor functions.
- Return type:
pyreco.initializer module
pyreco.layers module
We will have an abstract Layer class, from which the following layers inherit:
InputLayer
- ReservoirLayer
RandomReservoir
RecurrenceReservoir
EvolvedReservoir
ReadoutLayer
- class pyreco.layers.RandomReservoirLayer(nodes, density: float = 0.1, activation: str = 'tanh', leakage_rate: float = 0.5, fraction_input: float = 0.8, spec_rad: float = 0.9, init_res_sampling='random_normal', seed=None)[source]
Bases:
ReservoirLayer
- class pyreco.layers.ReservoirLayer(nodes, density, activation, leakage_rate, fraction_input, init_res_sampling, seed: int = 42)[source]
Bases:
Layer
- remove_nodes(nodes: list)[source]
Remove specified nodes from the reservoir network. Parameters: nodes (list): A list of indices representing the nodes to be removed. 1. Removes the specified nodes from the adjacency matrix. 2. Updates the reservoir properties including the number of nodes, density, and spectral radius.
pyreco.metrics module
pyreco.models module
Higher-level model definition for default models (built on custom models):
Wrapper for lower-level implementation of RCs. Instead of the Sequential-API-type syntax, this will provide sklearn-ready models, which under the hood build Sequential-API-type models and ship them.
Currently contains a lot of duplicate code, which needs to be ported to the lower-level implementations.
- class pyreco.models.Model(num_nodes: int = 100, activation: str = 'tanh', leakage_rate: float = 0.5)[source]
Bases:
ABC
- class pyreco.models.ReservoirComputer(num_nodes: int = 100, density: float = 0.8, activation: str = 'tanh', leakage_rate: float = 0.5, spec_rad: float = 0.9, fraction_input: float = 1.0, fraction_output: float = 1.0, n_time_in=None, n_time_out=None, n_states_in=None, n_states_out=None, metrics: str | list = 'mean_squared_error', optimizer: str | Optimizer = 'ridge', init_res_sampling='random_normal')[source]
Bases:
Model
pyreco.network_prop_extractor module
pyreco.node_analyzer module
- class pyreco.node_analyzer.NodeAnalyzer(quantities=None)[source]
Bases:
object
A class for analyzing node properties in a graph.
- pyreco.node_analyzer.available_extractors()[source]
Return a dictionary mapping network property names to their corresponding extractor functions. Make changes here if you want to add more network properties.
- Returns:
A dictionary mapping network property names to their corresponding extractor functions.
- Return type:
- pyreco.node_analyzer.map_extractor_names(prop_names: str)[source]
Return a dictionary mapping network property names to their corresponding extractor functions for the given property names.
- Returns:
A dictionary mapping network property names to their corresponding extractor functions.
- Return type:
pyreco.node_selector module
- class pyreco.node_selector.NodeSelector(strategy: str = 'random_uniform_wo_repl', total_nodes: int | None = None, graph: Graph | ndarray | None = None)[source]
Bases:
object
A class to select nodes from a graph based on specific criteria.
This class provides functionality to select a subset of nodes from a total number of nodes using different strategies. Currently, only the “random without replacement” strategy is implemented.
Attributes: - num_total_nodes (int): The total number of nodes in the graph. - num_select_nodes (int): The number of nodes to select. - fraction (float): The fraction of nodes to select. - strategy (str): The strategy used for node selection. - selected_nodes (list): The list of selected nodes.
- select_nodes(fraction: float | None = None, num: int | None = None)[source]
Selects a specified number of nodes from the graph either by fraction or by exact number.
Parameters: - fraction (float, optional): The fraction of the total nodes to select. Must be between 0 and 1. - num (int, optional): The exact number of nodes to select. Must be a positive integer.
Raises: - ValueError: If neither or both of fraction and num are provided. - TypeError: If num is not an integer.
Returns: - list: A list of selected node identifiers.
pyreco.optimizers module
- pyreco.optimizers.assign_optimizer(optimizer: str) Optimizer [source]
Maps names of optimizers to the correct implementation.
- Parameters:
- Returns:
An instance of the optimizer class corresponding to the given name.
- Return type:
- Raises:
ValueError – If the given optimizer name is not implemented.
pyreco.plotting module
Some plotting capabilities
pyreco.pruning module
Capabilities to prune an existing RC model, i.e. try to cut reservoir nodes and improve performance while reducing the reservoir size
- class pyreco.pruning.NetworkPruner(target_score: float | None = None, stop_at_minimum: bool = True, min_num_nodes: int = 3, patience: int = 0, candidate_fraction: float = 0.1, remove_isolated_nodes: bool = False, criterion: str = 'mse', metrics: list | str = ['mse'], maintain_spectral_radius: bool = False, node_props_extractor=None, graph_props_extractor=None, return_best_model: bool = True, graph_analyzer: GraphAnalyzer | None = None, node_analyzer: NodeAnalyzer | None = None)[source]
Bases:
object
- add_dict_to_history(keys, value_dict)[source]
Add a dictionary to history dictionary based on a list of keys.
Args: nested_dict (dict): The nested dictionary. keys (list): A list of keys specifying the path in the nested dictionary. value_dict (dict): The dictionary to add.
pyreco.remove_transients module
pyreco.utils_data module
Provides testing data sets.
SHAPES will always be: inputs X: [n_batch, n_timesteps, n_states] outputs y: [n_batch, n_timesteps, n_states]
pyreco.utils_networks module
Helper routines for networks
- pyreco.utils_networks.convert_to_nx_graph(graph: ndarray) Graph [source]
Convert a numpy array to a NetworkX graph. :param adjacency_matrix: The adjacency matrix of the graph. :type adjacency_matrix: np.ndarray
- Returns:
The NetworkX graph.
- Return type:
nx.Graph
- pyreco.utils_networks.extract_clustering_coefficient(graph: ndarray | Graph | DiGraph) float [source]
- pyreco.utils_networks.extract_density(graph: ndarray | Graph | DiGraph) float [source]
Extract the density of a graph from its adjacency matrix. :param adjacency_matrix: The adjacency matrix of the graph. :type adjacency_matrix: np.ndarray, nx.Graph, nx.DiGraph
- Returns:
The density of the graph.
- Return type:
- pyreco.utils_networks.extract_node_betweenness_centrality(graph: ndarray | Graph | DiGraph, node: int) float [source]
- pyreco.utils_networks.extract_node_clustering_coefficient(graph: ndarray | Graph | DiGraph, node: int) float [source]
- pyreco.utils_networks.extract_node_degree(graph: ndarray | Graph | DiGraph, node: int) float [source]
- pyreco.utils_networks.extract_node_in_degree(graph: ndarray | Graph | DiGraph, node: int) float [source]
- pyreco.utils_networks.extract_node_out_degree(graph: ndarray | Graph | DiGraph, node: int) float [source]
- pyreco.utils_networks.extract_node_pagerank(graph: ndarray | Graph | DiGraph, node: int) float [source]
- pyreco.utils_networks.gen_ER_graph(nodes: int, density: float, spec_rad: float = 0.9, directed: bool = True, seed=None)[source]
Generate an Erdős-Rényi random graph with specified properties.
Bug Fix Documentation:
- Previous Bug:
The line G.remove_nodes_from(list(nx.isolates(G))) removed isolated nodes from the graph before converting to a numpy array. This caused the final matrix to sometimes be smaller than the specified size (e.g., 29x29 instead of 30x30) when isolated nodes were present. This led to dimension mismatches in reservoir computations where other matrices expected the full size.
- Solution:
Instead of removing isolated nodes, we now connect them to maintain the specified network size. This ensures consistency between the reservoir weight matrix and other matrices in the computation.
- param nodes:
Number of nodes in the graph
- type nodes:
int
- param density:
Desired connection density (0 to 1)
- type density:
float
- param spec_rad:
Desired spectral radius
- type spec_rad:
float
- param directed:
Whether to create a directed graph
- type directed:
bool
- param seed:
Random seed for reproducibility
- type seed:
int, optional
- returns:
Adjacency matrix with shape (nodes, nodes)
- rtype:
np.ndarray