polyadicqml¶
polyadicqml.circuitML¶
-
class
polyadicqml.
circuitML
(make_circuit, nbqbits, nbparams, cbuilder)¶ Abstract Quantum ML circuit interface. Provides a unified interface to run multiple parametric circuits with different input and model parameters, agnostic of the backend, implemented in the subclasses.
- Parameters
make_circuit (callable of signature self.make_circuit) – Function to generate the circuit corresponding to input x and params.
nbqbits (int) – Number of qubits.
nbparams (int) – Number of parameters.
cbuilder (circuitBuilder) – Circuit builder class to be used. It must correspond to the subclass implementation.
-
nbqbits
¶ Number of qubits.
- Type
int
-
nbparams
¶ Number of parameters.
- Type
int
-
grad
(X, params, v=None, eps=None, nbshots=None, job_size=None)¶ Compute the gradient of the circuit w.r.t. parameters params on input X.
Uses finite differences of the circuit runs.
- Parameters
X (array-like) – Input matrix of shape (nb_samples, nb_features).
params (vector-like) – Parameter vector of length nb_params.
v (array-like) – Vector or matrix to right multiply the Jacobian with.
eps (float, optional) – Epsilon for finite differences. By default uses
1e-8
if nbshots is not provided, else usesnbshots (int, optional) – Number of shots for the circuit run, by default
None
. IfNone
, uses the backend default.job_size (int, optional) – Maximum job size, to split the circuit runs, by default
None
. IfNone
, put all nb_samples in the same job.
- Returns
Jacobian matix as an array of shape (nb_params, 2**nbqbits) if v is None, else Jacobian-vector product:
J(circuit) @ v
- Return type
array
-
make_circuit
(bdr, x, params)¶ Generate the circuit corresponding to input x and params. NOTE: This function is to be provided by the user, with the present signature.
- Parameters
bdr (circuitBuilder) – A circuit builder.
x (vector-like) – Input sample
params (vector-like) – Parameter vector.
- Returns
Instructed builder
- Return type
-
random_params
(seed=None)¶ Generate a valid vector of random parameters.
- Parameters
seed (int, optional) – random seed, by default
None
- Returns
Vector of random parameters.
- Return type
vector
-
run
(X, params, nbshots=None, job_size=None)¶ Run the circuit with input X and parameters params.
- Parameters
X (array-like) – Input matrix of shape (nb_samples, nb_features).
params (vector-like) – Parameter vector.
nbshots (int, optional) – Number of shots for the circuit run, by default
None
. IfNone
, uses the backend default.job_size (int, optional) – Maximum job size, to split the circuit runs, by default
None
. IfNone
, put all nb_samples in the same job.
- Returns
Bitstring counts as an array of shape (nb_samples, 2**nbqbits)
- Return type
array
polyadicqml.Classifier¶
-
class
polyadicqml.
Classifier
(circuit, bitstr, **kwargs)¶ Class for quantum classifiers. Defines the API using the scikit-learn format.
- Parameters
circuit (circuitML) – Quantum circuit to simulate, how to use and store is defined in child classes.
bitstr (list of int or list of str) – Which bitstrings should correspond to each class. The number of classes for the classification is defined by the number of elements.
params (vector, optional) – Initial model paramters. If
None
(default) usescircuitML.random_params
.nbshots (int, optional) – Number of shots for the quantum circuit. If 0, negative or None, then exact proabilities are computed, by default
None
.nbshots_increment (float, int or callable, optional) – How to increase the number of shots as optimization progress. If float or int, the increment arise every nbshots_incr_delay iterations: if float, then the increment is multiplicative; if int, then it is added. If callable, the new nbshots is computed by calling nbshots_increment(nbshots, n_iter, loss_value).
nbshots_incr_delay (int, optional) – After how many iteration nb_shots has to increse. By default 20, if nbshots_increment is given
loss (callable, optional) – Loss function, by default Negative LogLoss (Cross entropy).
job_size (int, optional) – Number of runs for each circuit job, by default the number of observations.
budget (int, optional) – Maximum number of optimization steps, by default 100
name (srt, optional) – Name to identify this classifier.
save_path (str, optional) – Where to save intermediate training results, by deafult None. If
None
, intermediate results are not saved.
-
bitstr
¶ Bitstrings (as int) on which to read the classes
- Type
list[int]
-
nbshots
¶ Number of shots to run circuit
- Type
int
-
job_size
¶ Number of circuits to run in each backend job
- Type
int
-
nfev
¶ Number if times the circuit has been run
- Type
int
-
fit
(input_train, target_train, batch_size=None, **kwargs)¶ Fit the model according to the given training data.
- Parameters
input_train (array) – Training design matrix.
target_train (vector) – Labels corresponding to input_train.
batch_size (int, optional) – Minibatches size, by default None. If none uses the full dataset with rndom shuffle at each iteration.
method (str, optional) – Optimization method, by default BFGS
bounds (sequence, optional) – Bounds on variables for L-BFGS-B, TNC, SLSQP, Powell, and trust-constr methods as a sequence of
(min, max)
pairs for each element in x. None is used to specify no bound.options (dict, optional) – Optimizer options, by default {‘maxiter’: budget}
save_loss_progress (bool, optional) – Whether to store the loss progress, by default False
save_output_progress (file path, optional) – Path where to save the output evolution , by default None. If none is given, the output is not saved.
seed (int, optional) – Random seed, by default None
- Returns
self
- Return type
-
info_dict
()¶ Returns a dictionary containing models information.
- Returns
Information dictionary
- Return type
dict
-
predict
(X)¶ Compute the predicted class for each input point of the design matrix.
- Parameters
X (array) – Design matrix of n samples
- Returns
Labels vector
- Return type
vector
-
predict_proba
(X, params=None)¶ Compute the bitstring probabilities associated to each input point of the design matrix.
- Parameters
X (array) – Design matrix of n samples
params (vector, optional) – Circuit parameters, by default None. If not given, model parameters are used.
- Returns
Predicted bitstring probabilities. Rows correspond to samples and columns to bitstrings, whose order is defined in
bitstr
.- Return type
array
-
proba_to_label
(proba) → numpy.ndarray¶ Transforms a matrix of real values in integer labels.
- Parameters
proba (array) – Real valued array
- Returns
Labels vector
- Return type
vector
-
run_circuit
(X, params=None)¶ Run the circuit with input X and parameters params.
- Parameters
X (array-like) – Input matrix of shape (nb_samples, nb_features).
params (vector-like, optional) – Parameter vector, by default uses the model
params
- Returns
Bitstring counts as an array of shape (nb_samples, 2**nbqbits)
- Return type
array
-
set_bitstr
(bitstr)¶ Bitstring setter
- Parameters
bitstr (list[str] or list[int]) – Bitstrings on which to read the class predictions.
- Raises
TypeError – If bitstrings are of wrong type or have eterogenous types
-
set_circuit
(circuit)¶ Set the circuit after testing for validity.
For a circuit to be valid, it has to be an instance of circuitML and, in case self already has a circuit, to use the same make_circuit function.
- Parameters
circuit (circuitML) – QML circuit
- Raises
Union[TypeError, ValueError] – If the circuit is invalid.
-
set_loss
(loss=None)¶ Loss function setter.
- Parameters
loss (callable, optional) – Loss function of the form loss(y_true, y_pred, labels), by default None. If None is given, nothing happens.
-
set_params
(params)¶ Parameters setter
- Parameters
params (vector) – Parameters vector
polyadicqml.circuitBuilder¶
-
class
polyadicqml.
circuitBuilder
(nbqbits, *args, **kwargs)¶ Builder to create parametrized circuit with repetitive structures, by defining general operations without directly writing gates.
- Parameters
nbqbits (int) – Number of qubits.
-
alldiam
(idx=None)¶ Add X-rotation of .
- Parameters
idx (iterable, optional) – Indices on which to apply the rotation, by default
None
. IfNone
, apply to all qubits.- Returns
self
- Return type
- Raises
ValueError – If idx is out of range
TypeError – If the indices are not int
-
allin
(theta)¶ Add input gate to all qubits and input theta.
- Parameters
theta (list-like) – Parameters to input.
- Returns
self
- Return type
-
circuit
()¶ Return the built circuit.
- Raises
NotImplementedError –
-
cz
(a, b)¶ Add CZ gate between qubits a and b
- Parameters
a (int) – Control qubit
b (int) – Target qubit.
- Returns
self
- Return type
- Raises
ValueError – If a or b are out of range
TypeError – If the indices are not int
-
input
(idx, theta)¶ Add input gate.
It correspond to a rotation of .
- Parameters
idx (Union[iterable, int]) – Index[-ices] of qubits on which to input theta.
theta (Union[list-like, float]) – Parameter[s] to input. Has to have the same length as
idx
.
- Returns
self
- Return type
- Raises
ValueError – If idx is out of range
TypeError – If the indices are not int
-
measure_all
()¶ Add measurement.
- Returns
self
- Return type