import numpy as np
class EchoStateNetwork:
"""
A basic Echo State Network (ESN) implementation.
Parameters:
- `input_dim`: Dimensionality of the input.
- `output_dim`: Dimensionality of the output.
- `reservoir_size`: Number of neurons in the reservoir. A larger reservoir can capture more complex dynamics but may overfit if too large.
- `spectral_radius`: Spectral radius of the reservoir's weight matrix. It should be less than 1 for echo state property but close to 1 for richer dynamics.
- `input_scaling`: Scaling factor for the input. Adjusts the impact of inputs on the reservoir.
- `leakage`: Leakage rate (for updating the reservoir state). Controls how much of the previous state is retained.
- `custom_input_weights`: Custom weights to be applied to the input (default=None). Useful for emphasizing certain input dimensions.
- `random_state`: Seed for reproducibility (default=None).
"""
def __init__(self, input_dim, output_dim, reservoir_size=100, spectral_radius=0.95,
input_scaling=0.1, leakage=1.0, custom_input_weights=None, random_state=None):
self.input_dim = input_dim
self.output_dim = output_dim
self.reservoir_size = reservoir_size
self.spectral_radius = spectral_radius
self.input_scaling = input_scaling
self.leakage = leakage
self.custom_input_weights = custom_input_weights if custom_input_weights is not None else np.ones((reservoir_size, input_dim))
self.random_state = random_state
# Initialize the internal random number generator for reproducibility
np.random.seed(self.random_state)
# Initialize the reservoir weights (W) randomly and scale them to ensure the echo state property
self.W = np.random.rand(reservoir_size, reservoir_size) - 0.5
# Scale W to have a specified spectral radius to maintain stability
eigenvalues = np.linalg.eigvals(self.W)
self.W *= self.spectral_radius / np.max(np.abs(eigenvalues))
# Initialize the input weights (W_in) and apply custom scaling if provided
self.W_in = self.input_scaling * (np.random.rand(reservoir_size, input_dim) - 0.5)
# Apply custom input weights if provided to emphasize certain inputs
self.W_in = self.W_in * self.custom_input_weights
# Initialize the output weights (W_out) with zeros (to be trained later)
self.W_out = np.zeros((output_dim, reservoir_size + input_dim))
# Initialize the reservoir state
self.state = np.zeros((reservoir_size, 1))
def _update_state(self, input_pattern):
# Update the reservoir state using the current input and previous state
pre_activation = np.dot(self.W, self.state) + np.dot(self.W_in, input_pattern)
# Apply the tanh activation function and leakage for state update
self.state = (1 - self.leakage) * self.state + self.leakage * np.tanh(pre_activation)
def fit(self, inputs, outputs):
"""
Fit the ESN to the given inputs and outputs.
Parameters:
- `inputs`: Input patterns (array with shape `(n_samples, input_dim)`).
- `outputs`: Target outputs (array with shape `(n_samples, output_dim)`).
"""
# Collect the states for all inputs by iterating through each input pattern
states = np.zeros((inputs.shape[0], self.reservoir_size + self.input_dim))
for i, inp in enumerate(inputs):
# Update the reservoir state for the current input
self._update_state(inp.reshape(-1, 1))
# Stack the current state and input for training the output weights
states[i] = np.vstack((self.state, inp.reshape(1, -1))).flatten()
# Train the output weights (W_out) using ridge regression for simplicity
# This can be replaced with other regression methods
X = states
y = outputs
# Regularization term (1e-8) prevents singular matrix issues
self.W_out = np.dot(np.dot(y.T, X), np.linalg.inv(np.dot(X.T, X) + 1e-8 * np.eye(X.shape[1])))
def predict(self, inputs):
"""
Predict outputs for the given inputs.
Parameters:
- `inputs`: Input patterns (array with shape `(n_samples, input_dim)`).
Returns:
- Predicted outputs (array with shape `(n_samples, output_dim)`).
"""
predicted = np.zeros((inputs.shape[0], self.output_dim))
for i, inp in enumerate(inputs):
# Update the reservoir state for prediction
self._update_state(inp.reshape(-1, 1))
# Combine the current state and input to generate the output
state_inp = np.vstack((self.state, inp.reshape(1, -1))).flatten()
predicted[i] = np.dot(self.W_out, state_inp)
return predicted
# Example Usage
if __name__ == "__main__":
# Define hyperparameters
input_dim = 3
output_dim = 2
reservoir_size = 200 # Larger reservoirs can capture more complex patterns
spectral_radius = 0.95 # Should be < 1 for stability but close to 1 for richer dynamics
input_scaling = 0.1 # Adjusts input impact on the reservoir
leakage = 0.5 # Controls how much of the previous state is retained
# Custom input weights example (optional)
custom_input_weights = np.random.rand(reservoir_size, input_dim) # Example custom weights
# Generate some dummy data
np.random.seed(0)
inputs = np.random.rand(100, input_dim) # 100 samples
outputs = np.random.rand(100, output_dim) # Dummy outputs for demonstration
# Initialize and train the ESN
esn = EchoStateNetwork(input_dim, output_dim, reservoir_size, spectral_radius,
input_scaling, leakage, custom_input_weights, random_state=42)
esn.fit(inputs, outputs)
# Make predictions
predictions = esn.predict(inputs)
print("Predictions Shape:", predictions.shape)
print("First Prediction:\n", predictions[0])