API Reference¶
Documentación generada automáticamente desde el código fuente de qiskit-data-reuploading.
qdr.models¶
DataReuploadingClassifier¶
qdr.models.classifier.DataReuploadingClassifier(n_qubits: int = 2, n_layers: int = 5, encoding: str = 'rx_ry_rz', entanglement: str = 'full', optimizer: str = 'COBYLA', backend: Any = None, shots: int | None = None, max_iter: int = 100, learning_rate: float = 0.01, seed: int | None = None)
¶
Bases: BaseEstimator, ClassifierMixin
Quantum classifier based on the data re-uploading technique.
Implements a full sklearn-compatible estimator (fit, predict,
predict_proba, score, save / load) backed by Qiskit 2.x
V2 primitives.
Parameters¶
n_qubits : int, optional
Number of qubits. Default 2.
n_layers : int, optional
Number of data-reuploading layers. Default 5.
encoding : str, optional
Rotation encoding — "rx", "ry", "rz", or "rx_ry_rz"
(default).
entanglement : str, optional
Entanglement pattern — "none", "linear", "circular",
"full" (default).
optimizer : str, optional
Optimizer — "SPSA", "COBYLA" (default), or "ADAM".
backend : None, optional
Must be None during fit. Hardware execution is exposed through
:func:qdr.hardware.run_on_ibm_backend so that real-backend cost,
authentication, transpilation, and batching are explicit.
shots : int or None, optional
None = exact statevector simulation. Positive int uses
:class:~qiskit_aer.primitives.EstimatorV2 with that shot count.
max_iter : int, optional
Maximum optimiser iterations. Default 100.
learning_rate : float, optional
Learning rate (ADAM only). Default 0.01.
seed : int or None, optional
Random seed for weight initialisation and stochastic optimisers.
Attributes¶
weights_ : np.ndarray
Trained parameters, shape (n_weights,).
classes_ : np.ndarray
Unique class labels seen during fit.
loss_history_ : list[float]
Per-iteration loss values recorded during training.
n_features_in_ : int
Number of features seen during fit.
Notes¶
The underlying circuit uses data re-uploading gates whose angles are
``angle = w[l, i, r] + x[feat_idx(l, i, r)]``
where feat_idx cycles modulo n_features in
:class:qdr.circuits.DataReuploadingCircuit. Binary classification uses a
single <Z_0> observable. Multiclass classification uses one local Z
observable per class and requires n_qubits >= n_classes.
Source code in qiskit-data-reuploading-src/qdr/models/classifier.py
fit(X: np.ndarray, y: np.ndarray) -> 'DataReuploadingClassifier'
¶
Fit the classifier to training data.
Parameters¶
X : array-like of shape (n_samples, n_features) Training features. y : array-like of shape (n_samples,) Class labels.
Returns¶
self
Raises¶
ValueError
If X is not two-dimensional, contains non-finite values, y
has the wrong shape or length, fewer than two classes are present,
multiclass output requests more classes than qubits, the feature
count exceeds the available data-uploading slots, or the optimizer
or circuit configuration is invalid.
ImportError
If shots is a positive integer and qiskit-aer is not
installed.
Source code in qiskit-data-reuploading-src/qdr/models/classifier.py
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 | |
load(path: str | Path) -> 'DataReuploadingClassifier'
classmethod
¶
Load a previously saved model.
Parameters¶
path : str or Path
Path to a .pkl file created by :meth:save.
Returns¶
DataReuploadingClassifier
Raises¶
FileNotFoundError
If path does not exist.
ValueError
If the saved parameters are inconsistent with the circuit or
observable constraints.
Source code in qiskit-data-reuploading-src/qdr/models/classifier.py
predict(X: np.ndarray) -> np.ndarray
¶
Predict class labels.
Parameters¶
X : array-like of shape (n_samples, n_features)
Returns¶
np.ndarray of shape (n_samples,)
Raises¶
ValueError
If X fails the same validation used by :meth:predict_proba.
sklearn.exceptions.NotFittedError
If the classifier has not been fitted.
Source code in qiskit-data-reuploading-src/qdr/models/classifier.py
predict_proba(X: np.ndarray) -> np.ndarray
¶
Predict class probabilities.
Parameters¶
X : array-like of shape (n_samples, n_features)
Returns¶
np.ndarray of shape (n_samples, n_classes)
Raises¶
ValueError
If X contains non-finite values or its feature count differs
from the data used in fit.
sklearn.exceptions.NotFittedError
If the classifier has not been fitted.
Source code in qiskit-data-reuploading-src/qdr/models/classifier.py
save(path: str | Path) -> None
¶
Serialise the fitted model to a file.
Parameters¶
path : str or Path
Destination file path (e.g. "model.pkl").
Raises¶
sklearn.exceptions.NotFittedError If the classifier has not been fitted.
Source code in qiskit-data-reuploading-src/qdr/models/classifier.py
DataReuploadingRegressor¶
qdr.models.regressor.DataReuploadingRegressor(n_qubits: int = 2, n_layers: int = 5, encoding: str = 'rx_ry_rz', entanglement: str = 'full', optimizer: str = 'COBYLA', backend: Any = None, shots: int | None = None, max_iter: int = 100, learning_rate: float = 0.01, seed: int | None = None)
¶
Bases: BaseEstimator, RegressorMixin
Quantum regressor based on the data re-uploading technique.
Predicts a continuous scalar output as the expectation value of a Z observable, scaled to the target range observed during training.
Parameters¶
n_qubits : int, optional
Number of qubits. Default 2.
n_layers : int, optional
Number of data-reuploading layers. Default 5.
encoding : str, optional
Rotation encoding. Default "rx_ry_rz".
entanglement : str, optional
Entanglement pattern. Default "full".
optimizer : str, optional
"SPSA", "COBYLA" (default), or "ADAM".
backend : None, optional
Must be None during fit. Hardware execution is exposed through
:func:qdr.hardware.run_on_ibm_backend so that real-backend cost,
authentication, transpilation, and batching are explicit.
shots : int or None, optional
None = exact statevector simulation. Positive int uses
:class:~qiskit_aer.primitives.EstimatorV2 with that shot count.
max_iter : int, optional
Maximum optimiser iterations. Default 100.
learning_rate : float, optional
Learning rate for ADAM. Default 0.01.
seed : int or None, optional
Random seed.
Attributes¶
weights_ : np.ndarray Trained parameters. loss_history_ : list[float] Per-iteration loss values. n_features_in_ : int Number of features seen during fit. y_min_ : float Minimum target value seen during training. y_max_ : float Maximum target value seen during training.
Notes¶
The underlying circuit uses gates whose angles are
``angle = w[l, i, r] + x[feat_idx(l, i, r)]``
and predicts one scalar from a single <Z_0> observable. Outputs are
rescaled from [-1, 1] to the target range observed during fit. This
estimator is intentionally single-output; multi-output regression requires
a separate observable design and is not implemented.
Source code in qiskit-data-reuploading-src/qdr/models/regressor.py
fit(X: np.ndarray, y: np.ndarray) -> 'DataReuploadingRegressor'
¶
Fit the regressor.
Parameters¶
X : array-like of shape (n_samples, n_features) y : array-like of shape (n_samples,)
Returns¶
self
Raises¶
ValueError
If X is not two-dimensional, contains non-finite values, y
has the wrong shape or length, targets contain non-finite values,
the feature count exceeds the available data-uploading slots, or
the optimizer or circuit configuration is invalid.
ImportError
If shots is a positive integer and qiskit-aer is not
installed.
Source code in qiskit-data-reuploading-src/qdr/models/regressor.py
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | |
load(path: str | Path) -> 'DataReuploadingRegressor'
classmethod
¶
Load a saved model.
Parameters¶
path : str or Path
Path to a file created by :meth:save.
Returns¶
DataReuploadingRegressor
Raises¶
FileNotFoundError
If path does not exist.
ValueError
If the saved parameters are inconsistent with the circuit
constraints.
Source code in qiskit-data-reuploading-src/qdr/models/regressor.py
predict(X: np.ndarray) -> np.ndarray
¶
Predict continuous target values.
Parameters¶
X : array-like of shape (n_samples, n_features)
Returns¶
np.ndarray of shape (n_samples,)
Raises¶
ValueError
If X contains non-finite values or its feature count differs
from the data used in fit.
sklearn.exceptions.NotFittedError
If the regressor has not been fitted.
Source code in qiskit-data-reuploading-src/qdr/models/regressor.py
save(path: str | Path) -> None
¶
Serialise the fitted model.
Parameters¶
path : str or Path Destination file path.
Raises¶
sklearn.exceptions.NotFittedError If the regressor has not been fitted.
Source code in qiskit-data-reuploading-src/qdr/models/regressor.py
qdr.circuits¶
DataReuploadingCircuit¶
qdr.circuits.data_reuploading.DataReuploadingCircuit(n_qubits: int, n_layers: int, n_features: int, encoding: str = 'rx_ry_rz', entanglement: str = 'full')
¶
Parameterized quantum circuit implementing the data re-uploading technique.
Each layer applies rotation gates whose angles are the sum of a trainable weight and a (cyclically indexed) input feature, followed by entanglement gates. Stacking n_layers of such blocks allows the circuit to act as a universal quantum classifier (Perez-Salinas et al., 2020).
Parameters¶
n_qubits : int
Number of qubits.
n_layers : int
Number of data-reuploading layers.
n_features : int
Number of classical input features.
encoding : str, optional
Rotation scheme — "rx", "ry", "rz", or "rx_ry_rz"
(default).
entanglement : str, optional
Entanglement pattern — "none", "linear", "circular", or
"full" (default).
Notes¶
The angle of each rotation gate in layer l, qubit i, and rotation
axis r is
``angle = w[l, i, r] + x[feat_idx(l, i, r)]``
where feat_idx cycles modulo n_features; see
:meth:build_circuit for the exact assignment rule. The circuit requires
n_features <= n_layers * n_qubits * n_rotations so every declared input
feature is represented by at least one gate.
Source code in qiskit-data-reuploading-src/qdr/circuits/data_reuploading.py
circuit: QuantumCircuit
property
¶
The built :class:~qiskit.QuantumCircuit, building it on first access.
build_circuit() -> QuantumCircuit
¶
Build and return the parameterized quantum circuit.
Features are assigned deterministically and cyclically to the encoding slots:
``feat_idx = slot_idx % n_features``
where slot_idx = layer * n_qubits * n_rots + qubit * n_rots + rot_idx.
If n_features < n_slots, features are reused. For example,
n_features=4 and n_slots=18 uses each feature 4 or 5 times.
With n_features=30 and n_slots=36, features 0-5 are used twice
and features 6-29 once, so the first features receive one extra slot.
Configurations with n_features > n_slots are rejected at
construction time because they would leave trailing features outside
the circuit.
Returns¶
QuantumCircuit The data re-uploading circuit (no measurements).
Notes¶
The angle of each rotation gate is angle = w + x. Data and
trainable weights are mixed inside the same gate, which is the defining
feature of data re-uploading.
Source code in qiskit-data-reuploading-src/qdr/circuits/data_reuploading.py
draw(**kwargs) -> Any
¶
make_param_array(weights: np.ndarray, x: np.ndarray) -> np.ndarray
¶
Return a parameter array for a single sample in circuit.parameters order.
Parameters¶
weights : np.ndarray
Shape (n_weights,).
x : np.ndarray
Shape (n_features,).
Returns¶
np.ndarray
Shape (n_params,).
Raises¶
ValueError
If weights or x has the wrong shape or contains non-finite values.
Source code in qiskit-data-reuploading-src/qdr/circuits/data_reuploading.py
make_param_batch(weights: np.ndarray, X: np.ndarray) -> np.ndarray
¶
Return a batched parameter array for multiple samples.
Parameters¶
weights : np.ndarray
Shape (n_weights,).
X : np.ndarray
Shape (n_samples, n_features).
Returns¶
np.ndarray
Shape (n_samples, n_params).
Raises¶
ValueError
If weights or X has the wrong shape or contains non-finite values.
Source code in qiskit-data-reuploading-src/qdr/circuits/data_reuploading.py
ReuploadingFeatureMap¶
qdr.circuits.feature_maps.ReuploadingFeatureMap(n_qubits: int, n_layers: int, n_features: int, encoding: str = 'rx_ry_rz', entanglement: str = 'full', seed: int | None = None)
¶
Feature map based on data re-uploading, compatible with QML pipelines.
Unlike :class:~qdr.circuits.DataReuploadingCircuit this class treats
the weights as fixed random parameters (frozen at construction time) and
exposes only the input parameters — matching the interface expected by
kernel-based methods and :class:qiskit_machine_learning.kernels.FidelityQuantumKernel.
Parameters¶
n_qubits : int
Number of qubits.
n_layers : int
Number of data-reuploading layers.
n_features : int
Number of classical input features.
encoding : str, optional
Rotation scheme. Default "rx_ry_rz".
entanglement : str, optional
Entanglement pattern. Default "full".
seed : int or None, optional
Random seed for weight initialisation.
Notes¶
The feature map keeps the original data re-uploading angle structure,
``angle = fixed_w[l, i, r] + x[feat_idx(l, i, r)]``
where fixed_w is sampled once at construction time and then frozen.
Only the input parameters x remain symbolic in the returned circuit.
The feature map requires enough encoding slots to upload every declared
feature at least once.
Source code in qiskit-data-reuploading-src/qdr/circuits/feature_maps.py
circuit: QuantumCircuit
property
¶
The feature-map circuit (built on first access).
bind(x: np.ndarray) -> QuantumCircuit
¶
Return a fully bound (non-parameterized) circuit for a single input.
Parameters¶
x : np.ndarray
Feature vector of shape (n_features,).
Returns¶
QuantumCircuit Circuit with all parameters assigned.
Raises¶
ValueError
If x has the wrong shape or contains non-finite values.
Source code in qiskit-data-reuploading-src/qdr/circuits/feature_maps.py
build_circuit() -> QuantumCircuit
¶
Build and return the feature-map circuit with fixed weights.
Returns¶
QuantumCircuit Parameterized only by x (input parameters).
Notes¶
The circuit parameters are the same objects stored in
:attr:input_params; this keeps external QML code from seeing a
different ParameterVector than the one actually used by the circuit.
Source code in qiskit-data-reuploading-src/qdr/circuits/feature_maps.py
qdr.training¶
ParameterShiftGradient¶
qdr.training.gradients.ParameterShiftGradient(circuit_obj: DataReuploadingCircuit, observable: SparsePauliOp, estimator: Any | None = None, shift: float = np.pi / 2)
¶
Parameter-shift gradient of expectation-value circuits.
For a circuit :math:U(\theta) and observable :math:O, the derivative is:
.. math::
\frac{\partial}{\partial \theta_i}\langle O \rangle =
\frac{\langle O \rangle_{\theta_i + s}
- \langle O \rangle_{\theta_i - s}}{2\sin(s)}
The default s = pi/2 recovers the usual 0.5 * (f+ - f-) rule.
With an exact estimator this produces analytic gradients for the Pauli
rotations used by :class:qdr.circuits.DataReuploadingCircuit. With
finite-shot estimators it produces a stochastic gradient estimate.
For an MSE gradient call this implementation evaluates the current
predictions once and then performs two shifted evaluations per trainable
parameter, i.e. 2 * n_weights + 1 batched estimator calls.
Parameters¶
circuit_obj : DataReuploadingCircuit
The parameterized circuit (already built).
observable : SparsePauliOp
Observable to differentiate.
estimator : object or None, optional
Qiskit V2 estimator. A fresh :class:~qiskit.primitives.StatevectorEstimator
is created when None.
shift : float, optional
Shift value s in radians. Default pi/2.
Raises¶
ValueError
If shift is non-finite or makes sin(shift) numerically zero.
Source code in qiskit-data-reuploading-src/qdr/training/gradients.py
compute(weights: np.ndarray, X: np.ndarray, y: np.ndarray, loss_fn: Callable[..., float] | None = None) -> np.ndarray
¶
Compute the gradient of the MSE loss with respect to weights.
.. math::
\nabla_\theta \mathcal{L} =
\frac{2}{N} \sum_i (\hat{y}_i - y_i) \nabla_\theta \hat{y}_i
Parameters¶
weights : np.ndarray
Current weight vector, shape (n_weights,).
X : np.ndarray
Input matrix, shape (n_samples, n_features).
y : np.ndarray
Target values in the same scale as the measured expectation values,
shape (n_samples,).
loss_fn : callable or None
Ignored; kept for API compatibility with possible future gradient
engines.
Returns¶
np.ndarray
Gradient vector, shape (n_weights,).
Raises¶
TypeError
If loss_fn is provided and is not callable.
ValueError
If weights, X, y, or estimator outputs have invalid
shape or non-finite values.
Source code in qiskit-data-reuploading-src/qdr/training/gradients.py
compute_jacobian(weights: np.ndarray, X: np.ndarray) -> np.ndarray
¶
Compute the Jacobian matrix d y_hat_i / d theta_j.
Parameters¶
weights : np.ndarray
Shape (n_weights,).
X : np.ndarray
Shape (n_samples, n_features).
Returns¶
np.ndarray
Jacobian of shape (n_samples, n_weights).
Raises¶
ValueError
If weights, X, or estimator outputs have invalid shape or
non-finite values.
Source code in qiskit-data-reuploading-src/qdr/training/gradients.py
qdr.benchmarks¶
BenchmarkRunner¶
qdr.benchmarks.runner.BenchmarkRunner(test_size: float = 0.2, cv_folds: int = 5, random_state: int | None = 42, verbose: bool = True)
¶
Compare a :class:~qdr.models.DataReuploadingClassifier against baselines.
The runner performs one stratified train/test split and, when cv_folds > 1,
stratified cross-validation on the full dataset. Labels are encoded once with
:class:~sklearn.preprocessing.LabelEncoder so all baselines, including
XGBoost, receive the same target representation.
Parameters¶
test_size : float, optional
Fraction of data held out for evaluation. Default 0.2.
cv_folds : int, optional
Number of stratified cross-validation folds. Default 5. Set to 0
or 1 to skip CV.
random_state : int or None, optional
Controls train/test split and classical model seeds.
verbose : bool, optional
Print progress updates. Default True.
Raises¶
ValueError If constructor parameters are outside their valid ranges.
Notes¶
BenchmarkRunner does not perform angle scaling for the quantum model.
Pass the feature representation intended for the circuit, usually scaled to
a compact angular range such as [-pi, pi].
Source code in qiskit-data-reuploading-src/qdr/benchmarks/runner.py
results: list[BenchmarkResult]
property
¶
Raw list of :class:BenchmarkResult objects.
run(X: np.ndarray, y: np.ndarray, qdr_model: Any | None = None, include_logreg: bool = True, include_svm: bool = True, include_mlp: bool = True, include_rf: bool = True, include_xgboost: bool = False) -> 'BenchmarkRunner'
¶
Run the full benchmark suite.
Parameters¶
X : np.ndarray
Feature matrix of shape (n_samples, n_features).
y : np.ndarray
Class labels, shape (n_samples,).
qdr_model : DataReuploadingClassifier or None
Configured but unfitted quantum model. If None, a default model
is created with enough qubits for the number of classes and enough
layers to upload all features at least once.
include_logreg : bool, optional
Whether to benchmark scaled logistic regression. Default True.
include_svm : bool, optional
Whether to benchmark a scaled RBF-SVM. Default True.
include_mlp : bool, optional
Whether to benchmark a small scaled MLP. Default True.
include_rf : bool, optional
Whether to benchmark a Random Forest. Default True.
include_xgboost : bool, optional
Whether to benchmark XGBoost. Default False because it requires
the optional xgboost package.
Returns¶
BenchmarkRunner
Allows chaining: runner.run(...).summary().
Raises¶
ValueError
If data, resampling settings, or include flags are invalid.
ImportError
If include_xgboost=True and xgboost is not installed.
Source code in qiskit-data-reuploading-src/qdr/benchmarks/runner.py
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 | |
summary() -> pd.DataFrame
¶
Return benchmark results as a :class:~pandas.DataFrame.
Returns¶
pd.DataFrame
Indexed by model name with columns accuracy, f1,
train_time_s, predict_time_s, cv_mean, and cv_std.
Values are returned at full floating-point precision; callers can
round only for presentation.
Raises¶
ValueError
If called before :meth:run has produced results.
Source code in qiskit-data-reuploading-src/qdr/benchmarks/runner.py
qdr.visualization¶
qdr.visualization.plots
¶
Visualization utilities for trained QDR models and benchmarks.
plot_benchmark_comparison(summary_df: Any, metric: str = 'accuracy', ax: 'Axes | None' = None, title: str | None = None) -> 'Figure'
¶
Plot a bar chart comparing benchmark metrics across models.
Parameters¶
summary_df : pandas.DataFrame
Output of :meth:qdr.benchmarks.BenchmarkRunner.summary, indexed by
model name.
metric : str, optional
Numeric column to plot. Default "accuracy".
ax : Axes or None, optional
Existing axes to plot into. If None, a new figure is created.
title : str or None, optional
Plot title. If None, a default title is used.
Returns¶
Figure Matplotlib figure containing the benchmark comparison.
Raises¶
ValueError If the summary is empty, the metric is missing, or metric values are non-numeric/non-finite.
Source code in qiskit-data-reuploading-src/qdr/visualization/plots.py
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | |
plot_bloch_sphere(statevector: np.ndarray, ax: 'Axes | None' = None, title: str = 'Bloch Sphere') -> 'Figure'
¶
Render a normalized single-qubit state on a Bloch sphere.
Parameters¶
statevector : np.ndarray
Complex array with shape (2,) representing
alpha |0> + beta |1>.
ax : Axes or None, optional
Existing 3D axes created with projection="3d". If None, a new
3D axes is created.
title : str, optional
Plot title.
Returns¶
Figure Matplotlib figure containing the Bloch sphere.
Raises¶
ValueError
If statevector is not a finite normalized single-qubit state, or if
ax is provided but is not a 3D axes.
Notes¶
The plotted vector is (<X>, <Y>, <Z>) for the supplied pure state. The
state must be normalized because otherwise these expectation values are not
physically valid Bloch coordinates.
Source code in qiskit-data-reuploading-src/qdr/visualization/plots.py
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 | |
plot_decision_boundary(model: Any, X: np.ndarray, y: np.ndarray, resolution: int = 50, feature_indices: tuple[int, int] = (0, 1), ax: 'Axes | None' = None, title: str = 'Decision Boundary') -> 'Figure'
¶
Plot a 2D decision boundary for a fitted classifier.
Parameters¶
model : fitted classifier
Any object with a predict(X) method.
X : np.ndarray
Feature matrix with shape (n_samples, n_features).
y : np.ndarray
True labels with shape (n_samples,).
resolution : int, optional
Grid resolution, in points per axis. Default 50.
feature_indices : tuple[int, int], optional
Two feature indices to plot. Default (0, 1).
ax : Axes or None, optional
Existing axes to plot into. If None, a new figure is created.
title : str, optional
Plot title.
Returns¶
Figure Matplotlib figure containing the decision boundary.
Raises¶
ValueError If inputs have invalid shape, contain non-finite values, or if model predictions cannot be aligned with the plotted grid.
Notes¶
For n_features > 2, the non-plotted features are fixed to their
empirical mean in X. This draws a well-defined 2D slice of the fitted
model instead of silently moving selected features into the wrong columns.
Source code in qiskit-data-reuploading-src/qdr/visualization/plots.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | |
plot_loss_curve(loss_history: Sequence[float], ax: 'Axes | None' = None, title: str = 'Training Loss', label: str = 'loss') -> 'Figure'
¶
Plot an optimization loss curve.
Parameters¶
loss_history : Sequence[float]
Per-iteration loss values.
ax : Axes or None, optional
Existing axes to plot into. If None, a new figure is created.
title : str, optional
Plot title.
label : str, optional
Legend label for the curve.
Returns¶
Figure Matplotlib figure containing the loss curve.
Raises¶
ValueError
If loss_history is empty, not one-dimensional, or contains
non-finite values.
Source code in qiskit-data-reuploading-src/qdr/visualization/plots.py
qdr.hardware¶
qdr.hardware.ibm_backend
¶
Hardware integration: run data re-uploading circuits on IBM Quantum backends.
list_available_backends(token: str | None = None, channel: str = 'ibm_quantum', min_qubits: int = 2, operational: bool = True) -> list[dict[str, Any]]
¶
Return accessible IBM Quantum backends.
Parameters¶
token : str or None, optional
IBM Quantum API token. If None, uses the saved account.
channel : str, optional
Runtime channel. Default "ibm_quantum".
min_qubits : int, optional
Filter backends with fewer than this many qubits. Default 2.
operational : bool, optional
Only include currently operational backends. Default True.
Returns¶
list[dict[str, Any]]
Each dict has name, n_qubits, status, and pending_jobs.
Raises¶
ImportError
If qiskit-ibm-runtime is not installed.
ValueError
If inputs are malformed.
Source code in qiskit-data-reuploading-src/qdr/hardware/ibm_backend.py
run_on_ibm_backend(circuit: 'QuantumCircuit', observable: 'SparsePauliOp', parameter_values: np.ndarray, backend_name: str, token: str | None = None, channel: str = 'ibm_quantum', optimization_level: int = 1, resilience_level: int | None = 1, default_shots: int | None = None, seed_estimator: int | None = None, precision: float | None = None) -> np.ndarray
¶
Evaluate expectation values on an IBM Quantum backend.
Requires the optional hardware dependency group::
pip install qiskit-data-reuploading[hardware]
Parameters¶
circuit : QuantumCircuit
Parameterized circuit without measurements.
observable : SparsePauliOp
Observable to estimate.
parameter_values : np.ndarray
Parameter values. Shape (n_samples, n_params) for a batch, or
(n_params,) for one sample.
backend_name : str
IBM Quantum backend name, e.g. "ibm_brisbane".
token : str or None, optional
IBM Quantum API token. If None, the token is read from the saved
account configured with QiskitRuntimeService.save_account(...).
channel : str, optional
Runtime channel. Default "ibm_quantum".
optimization_level : int, optional
Transpiler optimization level, from 0 to 3. Default 1.
resilience_level : int or None, optional
Estimator resilience level. IBM Runtime supports 0, 1, and 2; None
leaves the server default unset. Default 1.
default_shots : int or None, optional
Non-negative total shots per circuit/configuration. Mutually exclusive with
precision.
seed_estimator : int or None, optional
Runtime estimator seed.
precision : float or None, optional
Target precision passed to EstimatorV2.run. Mutually exclusive with
default_shots.
Returns¶
np.ndarray
Expectation values of shape (n_samples,).
Raises¶
ImportError
If qiskit-ibm-runtime is not installed.
ValueError
If inputs are malformed or estimator output has an unexpected shape.
Notes¶
This function submits real or runtime-managed backend jobs and can incur queue time and account cost. It intentionally does not train models; use it for explicit hardware evaluation of already-built circuits/observables.
Source code in qiskit-data-reuploading-src/qdr/hardware/ibm_backend.py
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 | |