## `eigenkit.torch.estimators.recurrent_hqnr`

## `eigenkit.torch.estimators.recurrent_hqnr.RecurrentHQNR`

Bases: `ModelAccessMixin`, `BaseQuantumRegressor`

Hybrid regressor: a recurrent encoder, a quantum layer and a linear head.

The recurrent encoder is a recurrent neural network (RNN). The estimator expects 3-D inputs of shape `(n_samples, seq_len, seq_feature_dim)`. By default, only the last timestep of the RNN output goes to the quantum layer. Set `rnn_return_last_timestep=False`, together with `sequence_length`, to use the full RNN output (flattened) instead. The quantum part is the same as in HQNR: `MinMaxNorm`, the quantum layer and an `nn.Linear` head.

Parameters:

| Name                       | Type                            | Description                                                                                                            | Default                                                                                                                                                                                                                                            |
| -------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `seq_feature_dim`          | `int`                           | The number of features at each time step (the last axis of X).                                                         | *required*                                                                                                                                                                                                                                         |
| `rnn_type`                 | `Literal['rnn', 'gru', 'lstm']` | The type of recurrent layer: "rnn", "gru" (gated recurrent unit) or "lstm" (long short-term memory).                   | `'gru'`                                                                                                                                                                                                                                            |
| `rnn_hidden_dim`           | `int`                           | The hidden size in each direction.                                                                                     | `32`                                                                                                                                                                                                                                               |
| `rnn_num_layers`           | `int`                           | The number of stacked RNN layers.                                                                                      | `1`                                                                                                                                                                                                                                                |
| `rnn_dropout`              | `float`                         | The dropout between the RNN layers. It applies only if rnn_num_layers > 1.                                             | `0.0`                                                                                                                                                                                                                                              |
| `rnn_bidirectional`        | `bool`                          | If True, the RNN is bidirectional, and its output size doubles.                                                        | `False`                                                                                                                                                                                                                                            |
| `rnn_return_last_timestep` | `bool`                          | If True, only the last output step is kept. Otherwise, the full sequence is flattened, which requires sequence_length. | `True`                                                                                                                                                                                                                                             |
| `sequence_length`          | \`int                           | None\`                                                                                                                 | The number of time steps in each sample. It is required when rnn_return_last_timestep=False, and it must equal X.shape[1] in fit.                                                                                                                  |
| `in_quantum`               | \`int                           | None\`                                                                                                                 | The number of inputs of the quantum layer. It defaults to the size of the RNN output that reaches the quantum layer: rnn_hidden_dim, doubled when the RNN is bidirectional, and multiplied by sequence_length when rnn_return_last_timestep=False. |
| `n_qubits`                 | \`int                           | None\`                                                                                                                 | The number of qubits in each circuit. It defaults to in_quantum.                                                                                                                                                                                   |
| `depth`                    | `int`                           | The number of repetitions of the variational layer.                                                                    | `2`                                                                                                                                                                                                                                                |
| `layer_type`               | `str`                           | The quantum layer. It is one of "Basic", "Reupload" and "Ensemble".                                                    | `'Basic'`                                                                                                                                                                                                                                          |
| `enc_rotation`             | \`Literal['RX', 'RY', 'RZ']     | None\`                                                                                                                 | The encoding rotation: "RX", "RY", "RZ" or None.                                                                                                                                                                                                   |
| `var_rotation`             | \`Literal['RX', 'RY', 'RZ']     | None\`                                                                                                                 | The variational rotation of the "basic" ansatz: "RX", "RY", "RZ" or None.                                                                                                                                                                          |
| `variational_type`         | \`Literal['basic', 'strong']    | None\`                                                                                                                 | The type of variational block: "basic", "strong" or None.                                                                                                                                                                                          |
| `basis`                    | \`Literal['X', 'Y', 'Z']        | None\`                                                                                                                 | The measurement basis: "X", "Y", "Z" or None. For these four arguments, None means "use the default of the layer named by layer_type", which is where each of these values is decided.                                                             |
| `provider`                 | `ProviderSpec`                  | The backend. It takes the same options as Circuit(provider=...).                                                       | `'numpy'`                                                                                                                                                                                                                                          |
| `lr`                       | `float`                         | The learning rate of the optimiser.                                                                                    | `0.01`                                                                                                                                                                                                                                             |
| `optimizer`                | `str`                           | The name of the optimiser.                                                                                             | `'adam'`                                                                                                                                                                                                                                           |
| `optimizer_kwargs`         | \`dict                          | None\`                                                                                                                 | Extra keyword arguments passed to the optimiser.                                                                                                                                                                                                   |
| `epochs`                   | `int`                           | The number of training epochs.                                                                                         | `50`                                                                                                                                                                                                                                               |
| `batch_size`               | `int`                           | The size of each mini-batch.                                                                                           | `32`                                                                                                                                                                                                                                               |
| `show_progress`            | `bool`                          | If True, a tqdm progress bar is shown.                                                                                 | `True`                                                                                                                                                                                                                                             |
| `loss_func`                | `str`                           | The regression loss: "mse", "mae" or "huber".                                                                          | `'mse'`                                                                                                                                                                                                                                            |
| `huber_delta`              | `float`                         | The threshold of the Huber loss.                                                                                       | `1.0`                                                                                                                                                                                                                                              |
| `huber_reduction`          | `str`                           | The reduction of the Huber loss: "mean" or "sum".                                                                      | `'mean'`                                                                                                                                                                                                                                           |
| `random_state`             | \`int                           | None\`                                                                                                                 | The seed.                                                                                                                                                                                                                                          |

Attributes:

| Name                 | Type | Description                                                                    |
| -------------------- | ---- | ------------------------------------------------------------------------------ |
| `train_losses_`      |      | The training loss of each epoch, set by fit().                                 |
| `validation_losses_` |      | The validation loss of each epoch, set by fit() when validation data is given. |

### `fit(X, y, X_val=None, y_val=None)`

Fit the estimator on `X` and `y`.

Parameters:

| Name    | Type      | Description                                                            | Default                                                               |
| ------- | --------- | ---------------------------------------------------------------------- | --------------------------------------------------------------------- |
| `X`     | `ndarray` | The sequences, of shape (n_samples, seq_len, seq_feature_dim).         | *required*                                                            |
| `y`     | `ndarray` | One target for each sequence, of shape (n_samples,) or (n_samples, 1). | *required*                                                            |
| `X_val` | \`ndarray | None\`                                                                 | Optional validation sequences, of the same shape as X. Default: None. |
| `y_val` | \`ndarray | None\`                                                                 | The targets of X_val. Default: None.                                  |

Returns:

| Type            | Description                                   |
| --------------- | --------------------------------------------- |
| `RecurrentHQNR` | This estimator, so that calls can be chained. |

### `load(path, *, provider=None, trusted=False)`

Load a fitted model from a `.eigenkit` bundle.

Loading a bundle does not unpickle anything, unless you pass `trusted=True` for a bundle saved before eigenkit 1.3.

Parameters:

| Name       | Type           | Description                                                                                                                                                                                                                                                                                | Default                                 |
| ---------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------- |
| `path`     | \`str          | Path\`                                                                                                                                                                                                                                                                                     | The path of the bundle.                 |
| `provider` | \`ProviderSpec | None\`                                                                                                                                                                                                                                                                                     | A provider that replaces the saved one. |
| `trusted`  | `bool`         | Load a bundle saved before eigenkit 1.3 by QSVC, QSVR or the reservoir classifier. Such a bundle holds joblib pickles, and unpickling runs code, as with torch.load or joblib.load. Pass it only for bundles whose source you trust, and save the model again to store it without pickles. | `False`                                 |

Returns:

| Type                     | Description           |
| ------------------------ | --------------------- |
| `'BaseQuantumEstimator'` | The loaded estimator. |

Raises:

| Type                 | Description                                                                                                                  |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `TypeError`          | If the method is called on a subclass and the bundle holds a different class. BaseQuantumEstimator.load() accepts any class. |
| `SerializationError` | If the bundle holds joblib pickles and trusted is False.                                                                     |

### `predict(X)`

Predict a value for every sample in `X`.

Parameters:

| Name | Type      | Description                                                    | Default    |
| ---- | --------- | -------------------------------------------------------------- | ---------- |
| `X`  | `ndarray` | The sequences, of shape (n_samples, seq_len, seq_feature_dim). | *required* |

Returns:

| Type      | Description                                                                 |
| --------- | --------------------------------------------------------------------------- |
| `ndarray` | One prediction for each sequence, as a float32 array of shape (n_samples,). |

### `save(path)`

Save a fitted model to a `.eigenkit` bundle.

A bundle holds JSON, NumPy arrays without pickle, PyTorch weights and, for models built on scikit-learn objects (`QSVC`, `QSVR`, the reservoir classifier), those objects serialized with skops. None of them is a pickle, so loading a bundle does not run code from it.

Parameters:

| Name   | Type  | Description | Default                                                                   |
| ------ | ----- | ----------- | ------------------------------------------------------------------------- |
| `path` | \`str | Path\`      | The path of the bundle. The suffix .eigenkit is added when it is missing. |
