TF Quantum Circuit Learner¶
Module name: qmlt.tf
Code author: Maria Schuld <maria@xanadu.ai>
This module contains a class to train models for machine learning and optimization based on variational quantum circuits.
The class extends TensorFlow’s tf.estimator
class, and adapts it to unsupervised learning and optimization tasks. It
hides the complexity of defining input functions, hooks and configurations.
The user defines a function that computes the outputs of the variational circuit, as well as the training objective, and specifies the model and training hyperparameters.
There are three basic functionalities. The circuit can be trained, run with the current parameters, and scored.
The TensorFlow learner module has been designed for the training of continuousvariable circuits written in StrawberryFields or BlackBird using the ‘tf’ backend only, but is in principle able to train any userprovided model coded in tensorflow.
Note
Contrary to the numerical learner
, the TensorFlow learner doesn’t contain builtin plotting functions.
The recommended method of visualizing the learner parameters is by using TensorBoard.
CircuitLearner class¶
get_circuit_parameters ([only_print]) 
Print or return all trainable variables. 
Helper methods¶
qcv_model_fn (features, labels, hyperparams, mode) 
Custom model for tensorflow’s Estimator class. 
make_input_fn ([X, Y, steps, batch_size, shuffle]) 
Creates input function that feeds dictionary of numpy arrays into the model. 
check (hp) 
Checks if the hyperparameter dictionary has all required keys, and adds default settings for missing entries. 
check_X (X) 
Checks if inputs have the right format. 
check_Y (Y, X) 
Checks if targets have the right format. 
check_steps (steps) 
Checks if step argument has the right format. 
check_batch_size (batch_size, X) 
Checks if batch_size argument has the right format. 
check_shuffle (shuffle) 
Checks if shuffle argument has the right format. 
Code details¶

class
qmlt.tf.
CircuitLearner
(hyperparams, model_dir=None, config=None)[source]¶ Defines a learner based on tensorflow and automatic differentiation by extending a tensorflow custom estimator class. The extension is done by overwriting model_fn (the core model of the learner) to depend on a custom tensorflow model provided by the user.
Parameters:  hyperparams (dict) –
Dictionary of the following keys:
circuit
(function): Function that computes the output of the variational circuit with the following keywords: If task=’optimization’ use
circuit()
 If task=’unsupervised’ use
circuit()
 If task=’supervised’ use
circuit(X)
Here, X is a batch of training inputs (2d tensor).
 If task=’optimization’ use
task
(str): One of ‘optimization’, ‘unsupervised’ or ‘supervised’.optimizer
(string): One of “Adagrad”, “Adam”, “Ftrl”, “RMSProp”, “SGD”, or a tensorflow optimizer class instance. Defaults to SGD.loss
(function): Loss function that outputs a scalar which measures the quality of a model. Default is a lambda function that returns zero. The function must have the following keywords: If task=’optimization’, use
myloss(circuit_output)
 If task=’unsupervised’, use
myloss(circuit_output, X)
 If task=’supervised’, use
myloss(circuit_output, targets)
Here,
outputs
are the outputs of the circuit function (is a 2d batch for unsupervised and supervised tasks),inputs
is a 2d ndarray representing a batch of inputs, andtargets
are the target outputs. If task=’optimization’, use
regularizer
(function): Regularizer function of the formmyregularizer(regularized_params)
that maps a 1d list of circuit parameters marked for regularization to a scalar. Default is a lambda function that returns zero.
regularization_strength
(float): Strength of regularization. Defaults to 0.init_learning_rate
(float): Initial learning rate used in some optimizers. Defaults to 0.decay
(float): Reduce the learning rate to 1/(1+decay*step). Defaults to 0.print_log
(boolean): If true, prints out information on settings and training progress. Defaults to True.log_every
(int): Print log only every log_every steps. Defaults to 1.warm_start
(boolean): If true, load the initial parameters from the last stored model. If False, delete the logging directory. Defaults to False.plot
(int): Plot in tensorboard every so many steps. Defaults to 1.
 model_dir (str) – Relative path to directory in which model and tensorboard logs get saved. None saves model in temporary directory (default: None).
 config (tf.RunConfig) – Configurations for training. Defaults to None.

train_circuit
(X=None, Y=None, steps=None, batch_size=None, shuffle_data=False, tensors_to_log=None)[source]¶ Simple version of the
tf.Estimator.train_circuit()
function. Callstf.estimator.train()
internally.Parameters:  X (ndarray) – Array of feature vectors.
 Y (ndarray) – Array of target outputs.
 steps (int) – Maximum number of steps of the algorithm.
 batch_size (int) – Size of training batches. Has to be smaller than size of training set.
 shuffle_data (boolean) – If true, shuffle data in each iteration.
 tensors_to_log (dict) – Dictionary of tensors to log. The key is a name displayed during logging, and the value is the name of the tensor (as a string).

run_circuit
(X=None, outputs_to_predictions=None)[source]¶ Get the outcomes when running the circuit with the current circuit parameters. Calls
tf.estimator.predict()
internally.Parameters:  X (ndarray) – Array of inputs (only for supervised learning tasks).
 outputs_to_predictions (function) – Function of the form
outputs_to_predictions(outps)
that takes a single output and maps it to a prediction that can be compared to the targets in order to compute the accuracy of a classification task. If None, run_circuit will return the outputs only.
Returns: Dictionary of outcomes. Always contains the key ‘outputs’ which is the argument returned by the circuit function.
Return type: Dictionary

score_circuit
(X=None, Y=None, outputs_to_predictions=None)[source]¶ Get the score of the circuit. Calls
tf.estimator.evaluate()
internally.Parameters:  X (ndarray) – Array of inputs.
 Y (ndarray) – Array of targets.
 outputs_to_predictions (function) – Function of the form
outputs_to_predictions(outps)
that takes a single output and maps it to a prediction that can be compared to the targets in order to compute the accuracy of a classification task. If None, no ‘accuracy’ is added to score metrics.
Returns: Dictionary of scores.
Return type: Dictionary

get_circuit_parameters
(only_print=False)[source]¶ Print or return all trainable variables.
Parameters: only_print (boolean) – If True, print the variables and return nothing. Defaults to False. Returns: If only_print is False, return return a dictionary of variable names and values. Return type: Dictionary or None

mro
() → list¶ return a type’s method resolution order
 hyperparams (dict) –

qmlt.tf.
qcv_model_fn
(features, labels, hyperparams, mode)¶ Custom model for tensorflow’s Estimator class. Defines the cost, optimiser and core model of the circuit learner, depending on the mode (TRAIN, EVAL or PREDICT). Refer to tensorflow documentation on how to build custom models inheriting from tf.Estimator for details.
Parameters:  features (dict) – Dictionary defined via a tensorflow input_fn function. The inputs of the current batch are
accessible through the
x
key.  labels (input queue) – Labels defined via a tensorflow input_fn function. The labels of the current batch are
directly accessible through
labels
.  hyperparams (dict) – Dictionary of hyperparameters.
Returns: Measures and outputs in the form of an EstimatorSpec.
Return type: tf.estimator.EstimatorSpec
 features (dict) – Dictionary defined via a tensorflow input_fn function. The inputs of the current batch are
accessible through the

qmlt.tf.
make_input_fn
(X=None, Y=None, steps=None, batch_size=None, shuffle=False)¶ Creates input function that feeds dictionary of numpy arrays into the model.
Parameters:  X (ndarray or list)  Input data of shape (num_inputs, input_dim) –
 steps (int) – method. Used to calculate the number of epochs.
 Y (ndarray or list)  labels data of shape (num_inputs, label_dim) –
 batch_size (int) – step (“full batch”).
 shuffle (boolean) –
Returns: tensorflow input_fn data queue.

qmlt.tf.
check
(hp)¶ Checks if the hyperparameter dictionary has all required keys, and adds default settings for missing entries.
The final hyperparameters are printed.
Parameters: hp (dict) – Dictionary of hyperparameters

qmlt.tf.
check_X
(X)¶ Checks if inputs have the right format.

qmlt.tf.
check_Y
(Y, X)¶ Checks if targets have the right format.

qmlt.tf.
check_steps
(steps)¶ Checks if step argument has the right format.

qmlt.tf.
check_batch_size
(batch_size, X)¶ Checks if batch_size argument has the right format.

qmlt.tf.
check_shuffle
(shuffle)¶ Checks if shuffle argument has the right format.