benchmark
eigenkit.benchmark
Comparison of quantum and classical estimators.
The compare() function trains models that follow
the scikit-learn interface on a dataset with several random seeds. It returns a
BenchmarkResult with the aggregated
metrics.
Example
from sklearn.svm import SVC
from eigenkit.qml import QSVC
from eigenkit.benchmark import compare
results = compare(
models={
"Quantum SVC": QSVC(
feature_map="Angle", reps=1, probability=True
),
"Regularized SVC": SVC(C=0.3),
"Flexible SVC": SVC(C=3.0),
},
dataset="iris",
metrics=["accuracy"],
n_seeds=1,
)
print(list(results.fitted_models))
# ['Quantum SVC', 'Regularized SVC', 'Flexible SVC']
BenchmarkResult
dataclass
Results of a benchmark comparison.
It stores the raw metric values of every seed, and aggregates them when you
display them with table(), plot them with plot(), or analyse them with
to_dataframe().
Each entry in raw is a dict with the keys "model", "seed", "metric" and
"value".
fitted_models holds every fitted copy produced by
compare(), keyed by the name of the model in the
benchmark. The names usually match the class names, and repeated names are
numbered (for example, SVC_0 and SVC_1). If compare(models={...})
receives a dict, its keys are used instead.
Example
from sklearn.svm import SVC
from eigenkit.qml import QSVC
from eigenkit.benchmark import compare
results = compare(
models={
"Quantum SVC": QSVC(
feature_map="Angle", reps=1, probability=True
),
"Regularized SVC": SVC(C=0.3),
"Flexible SVC": SVC(C=3.0),
},
dataset="iris",
metrics=["accuracy"],
n_seeds=1,
)
print(list(results.fitted_models))
# ['Quantum SVC', 'Regularized SVC', 'Flexible SVC']
results.plot(save_path="svc_comparison.png")
df = results.to_dataframe()
X_new = [[5.1, 3.5, 1.4, 0.2]]
# Access the fitted estimators
winner = results.best_model(metric="accuracy")
preds = results.predict(X_new)
quantum_fits = results.fitted_models["Quantum SVC"]
# Run inference on new data, with all models or a subset
out = results.inference(X_new)
out = results.inference(X_new, models=["Quantum SVC"], seed=0)
best_model(metric=None, seed='last')
Return the fitted estimator with the best mean score on metric.
When metric is None, the default, the first metric recorded in raw that
is not a timing metric is used. With the default metrics, this is usually
"accuracy" for classification and "r2" for regression. If custom metrics
were passed in a different order, the first of them is used.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric
|
str | None
|
The metric used for ranking, for example |
None
|
seed
|
str | int
|
The seed whose estimator is returned for the winning model.
|
'last'
|
Returns:
| Type | Description |
|---|---|
Any
|
The fitted estimator. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no fitted models are stored, or if |
IndexError
|
If |
confusion_matrix(model_name=None, **kwargs)
Return a scikit-learn confusion matrix computed from the stored predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str | None
|
The model whose predictions are used. |
None
|
**kwargs
|
Any
|
Passed on to |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The confusion matrix, as a NumPy array. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no predictions are stored (run
|
ImportError
|
If scikit-learn is not installed. |
inference(X, models=None, seed='last')
Run every fitted model, or a subset of them, on new data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Any
|
The input features to predict on. |
required |
models
|
list[str] | None
|
The names of the models to run. |
None
|
seed
|
str | int
|
The seed whose estimator is used for each model. |
'last'
|
Returns:
| Type | Description |
|---|---|
dict[str, dict[str, Any]]
|
A dict keyed by model name. Each value contains two entries:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If no fitted models are stored, or if an unknown model name is requested. |
IndexError
|
If |
load(path)
classmethod
Load numeric benchmark results saved by BenchmarkResult.save().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The JSON file to read. |
required |
Returns:
| Type | Description |
|---|---|
'BenchmarkResult'
|
A |
plot(save_path=None, theme='light')
Plot a grouped bar chart with error bars.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_path
|
str | None
|
If given, the figure is saved to this path instead of being shown. |
None
|
theme
|
str
|
The plot theme, |
'light'
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If matplotlib is not installed. |
plot_history(save_path=None, theme='light', seed='last')
Plot the stored training and validation loss curves.
Models without a loss history are left out, and a warning names them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_path
|
str | None
|
If given, the figure is saved to this path instead of being shown. |
None
|
theme
|
str
|
The plot theme, |
'light'
|
seed
|
str | int
|
The run to draw: |
'last'
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If no model has a training or validation loss curve. |
ImportError
|
If matplotlib is not installed. |
predict(X, metric=None)
Predict with the best model ranked by metric.
This is a shortcut for best_model(). It calls predict() on the estimator
returned by best_model(metric=metric).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Any
|
The input features. |
required |
metric
|
str | None
|
The metric used to select the best model. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The predictions of the best estimator's |
save(path)
Save the numeric results of the benchmark to a JSON file.
The fitted estimators are not saved, by design.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The file to write. If it is an existing directory, a file named
|
required |
Returns:
| Type | Description |
|---|---|
Path
|
The path of the file that was written. |
significance_test(metric, method='wilcoxon')
Return a matrix of p-values for each pair of models.
The p-values compare the values of metric on the seeds that both models
share.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric
|
str
|
The metric to compare. |
required |
method
|
str
|
|
'wilcoxon'
|
Returns:
| Type | Description |
|---|---|
'pd.DataFrame'
|
A pandas DataFrame with one row and one column per model. The diagonal is
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If pandas or scipy is not installed. |
ValueError
|
If |
table(show_significance=False)
Return the results as a text table.
The table is drawn with Unicode box-drawing characters and needs no optional dependency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
show_significance
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
str
|
A string with one row per model and one column per metric. Each value is
shown as |
Raises:
| Type | Description |
|---|---|
ImportError
|
If |
to_dataframe()
Return the raw results of every seed as a pandas DataFrame.
Returns:
| Type | Description |
|---|---|
'pd.DataFrame'
|
A DataFrame with the columns |
Raises:
| Type | Description |
|---|---|
ImportError
|
If pandas is not installed. |
compare(models, dataset='breast_cancer_wisconsin', metrics=None, n_seeds=5, test_size=0.15, show_progress=False, save_dir=None, store_predictions=False, validation_size=0.15)
Compare eigenkit models and built-in scikit-learn models on a dataset.
Each model must be a built-in scikit-learn estimator (from the sklearn
package), or a subclass of
BaseQuantumEstimator,
BaseQuantumClassifier or
BaseQuantumRegressor. For
every seed, each model is copied with sklearn.base.clone().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
list | dict[str, Any]
|
The estimator instances to compare. If a
list is passed, the display names come from |
required |
dataset
|
str | dict
|
A dataset name, or a dict that is already split, with
|
'breast_cancer_wisconsin'
|
metrics
|
list | None
|
The metrics to compute. For classification, the
options are |
None
|
n_seeds
|
int
|
The number of seeds to average over. The default is |
5
|
test_size
|
float
|
The fraction of the data kept for the final test set. |
0.15
|
show_progress
|
bool
|
Whether to print the progress of the benchmark, with
the current model and an estimate of the remaining time. The default is
|
False
|
save_dir
|
str | Path | None
|
If set, each fitted model is saved in this
directory, as |
None
|
store_predictions
|
bool
|
If |
False
|
validation_size
|
float
|
The fraction of the data kept for validation. |
0.15
|
Returns:
| Type | Description |
|---|---|
BenchmarkResult
|
An object with the results, and methods such as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If a model name is not a string, or if a model is not a supported type of estimator. |
custom_metric(fn, *, direction, name=None)
Define a custom metric and the direction in which it improves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[ndarray, ndarray], float]
|
The metric function. It receives |
required |
direction
|
MetricDirection
|
|
required |
name
|
str | None
|
The column label of the metric. The default is the name of |
None
|
Returns:
| Type | Description |
|---|---|
CustomMetric
|
A metric specification to pass to |
load_checkpoint(path, *, model=None)
Load a model checkpoint written by compare(..., save_dir=...).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The path to the checkpoint file ( |
required |
model
|
Any
|
The |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The loaded estimator. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If a |
ValueError
|
If the file extension is not supported. |
quick_baselines()
Return a list of common scikit-learn classifiers with sensible defaults.
The list contains a SVC with a radial basis function (RBF) kernel and
probabilities, so that roc_auc can be computed, a RandomForestClassifier, a
LogisticRegression and a KNeighborsClassifier. XGBClassifier and
LGBMClassifier are added when their packages can be imported.
scikit-learn 1.9 deprecates SVC(probability=True). From that version, the
support vector classifier is wrapped as
CalibratedClassifierCV(SVC(), ensemble=False), the replacement that
scikit-learn documents, so the results table calls it CalibratedClassifierCV.
Returns:
| Type | Description |
|---|---|
list[Any]
|
A list of classifiers that follow the scikit-learn interface, created but not fitted. |