VQC

class VQC(num_qubits=None, feature_map=None, ansatz=None, loss='cross_entropy', optimizer=None, warm_start=False, initial_point=None, callback=None, *, sampler=None, interpret=None, output_shape=None, pass_manager=None)[source]

Bases: NeuralNetworkClassifier

A convenient Variational Quantum Classifier implementation.

The variational quantum classifier (VQC) is a variational algorithm where the measured bitstrings are interpreted as the output of a classifier.

Constructs a quantum circuit and corresponding neural network, then uses it to instantiate a neural network classifier.

Labels can be passed in various formats, they can be plain labels, a one dimensional numpy array that contains integer labels like [0, 1, 2, …], or a numpy array with categorical string labels. One hot encoded labels are also supported. Internally, labels are transformed to one hot encoding and the classifier is always trained on one hot labels.

Multi-label classification is partially supported. Please refer to output_shape and interpret arguments. E.g., \([[1, 1, 0], [0, 1, 1], [1, 0, 1]]\).

Parameters:
  • num_qubits (int | None) – The number of qubits for the underlying QNN. If None is given, the number of qubits is derived from the feature map or ansatz. If neither of those is given, raises an exception. The number of qubits in the feature map and ansatz are adjusted to this number if required.

  • feature_map (QuantumCircuit | None) – The (parametrized) circuit to be used as a feature map for the underlying QNN. If None is given, the ZZFeatureMap is used if the number of qubits is larger than 1. For a single qubit classification problem the ZFeatureMap is used by default.

  • ansatz (QuantumCircuit | None) – The (parametrized) circuit to be used as an ansatz for the underlying QNN. If None is given then the RealAmplitudes circuit is used.

  • loss (str | Loss) – A target loss function to be used in training. Default value is cross_entropy.

  • optimizer (Optimizer | Minimizer | None) – An instance of an optimizer or a callable to be used in training. Refer to Minimizer for more information on the callable protocol. When None defaults to SLSQP.

  • warm_start (bool) – Use weights from previous fit to start next fit.

  • initial_point (np.ndarray | None) – Initial point for the optimizer to start from.

  • callback (Callable[[np.ndarray, float], None] | None) – a reference to a user’s callback function that has two parameters and returns None. The callback can access intermediate data during training. On each iteration an optimizer invokes the callback and passes current weights as an array and a computed value as a float of the objective function being optimized. This allows to track how well optimization / training process is going on.

  • sampler (BaseSampler | None) – an optional Sampler primitive instance to be used by the underlying SamplerQNN neural network. If None is passed then an instance of the reference Sampler will be used.

  • pass_manager (BasePassManager | None) – The pass manager to transpile the circuits, if necessary. Defaults to None, as some primitives do not need transpiled circuits.

  • interpret (Callable[[int], int | tuple[int, ...]] | None) – A callable that maps the measured integer to another unsigned integer or tuple of unsigned integers. These are used as new indices for the (potentially sparse) output array. If no interpret function is passed, then a basic parity function will be used by underlying neural network.

  • output_shape (int | None) – The output shape for the underlying neural network, generally equals to number of classes. Defaults to binary classification, 2.

Raises:

QiskitMachineLearningError – Needs at least one out of num_qubits, feature_map or ansatz to be given. Or the number of qubits in the feature map and/or ansatz can’t be adjusted to num_qubits.

Attributes

ansatz

Returns the used ansatz.

callback

Return the callback.

circuit

Returns the underlying quantum circuit.

feature_map

Returns the used feature map.

fit_result

Returns a resulting object from the optimization procedure. Please refer to the documentation of the OptimizerResult class for more details.

Raises:

QiskitMachineLearningError – If the model has not been fit.

initial_point

Returns current initial point

loss

Returns the underlying neural network.

neural_network

Returns the underlying neural network.

num_classes

The number of classes found in the most recent fit.

If called before fit(), this will return None.

num_qubits

Returns the number of qubits used by ansatz and feature map.

optimizer

Returns an optimizer to be used in training.

warm_start

Returns the warm start flag.

weights

Returns trained weights as a numpy array. The weights can be also queried by calling model.fit_result.x, but in this case their representation depends on the optimizer used.

Raises:

QiskitMachineLearningError – If the model has not been fit.

Methods

fit(X, y)

Fit the model to data matrix X and target(s) y.

Parameters:
Returns:

returns a trained model.

Return type:

self

Raises:

QiskitMachineLearningError – In case of invalid data (e.g. incompatible with network)

classmethod load(file_name)

Loads a model from the file. If the loaded model is not an instance of the class whose method was called, then a warning is raised. Nevertheless, the loaded model may be a valid model.

Parameters:

file_name (str) – a file name or path to load a model from.

Returns:

A loaded model.

Raises:

TypeError – if a loaded model is not an instance of the expected class.

Return type:

Any

predict(X)

Perform classification on samples in X.

Parameters:

X (np.ndarray) – Input features. For a callable kernel (an instance of BaseKernel), the shape should be (m_samples, n_features). For a pre-computed kernel, the shape should be (m_samples, n_samples). Here, m_* denotes the set to be predicted, and n_* denotes the size of the training set. In the case of a pre-computed kernel, the kernel values in X must be calculated with respect to the elements of the set to be predicted and the training set.

Returns:

An array of shape (n_samples,), representing the predicted class labels for

each sample in X.

Return type:

np.ndarray

Raises:
predict_proba(X)

Extracts the predicted probabilities for each class based on the output of a neural network.

Parameters:

X (np.ndarray) – Input features. For a callable kernel (an instance of BaseKernel), the shape should be (m_samples, n_features). For a pre-computed kernel, the shape should be (m_samples, n_samples). Here, m_* denotes the set to be predicted, and n_* denotes the size of the training set. In the case of a pre-computed kernel, the kernel values in X must be calculated with respect to the elements of the set to be predicted and the training set.

Returns:

An array of shape (n_samples, n_classes) representing the predicted class

probabilities (in the range \([0, 1]\)) for each sample in X.

Return type:

np.ndarray

save(file_name)

Saves this model to the specified file. Internally, the model is serialized via dill. All parameters are saved, including a primitive instance that is referenced by internal objects. That means if a model is loaded from a file and is used, for instance, for inference, the same primitive will be used even if a cloud primitive was used.

Parameters:

file_name (str) – a file name or path where to save the model.

score(X, y, sample_weight=None)

Returns a score of this model given samples and true values for the samples. In case of classification this should be mean accuracy, in case of regression the coefficient of determination \(R^2\) of the prediction.

Parameters:
  • X (ndarray) – Test samples.

  • y (ndarray) – True values for X.

  • sample_weight (ndarray | None) – Sample weights. Default is None.

Returns:

a float score of the model.

Return type:

float