mindquantum.framework.MQN2AnsatzOnlyLayer
- class mindquantum.framework.MQN2AnsatzOnlyLayer(expectation_with_grad, weight='normal')[source]
MindQuantum trainable layer.
Quantum neural network only include ansatz circuit. The ansatz circuit act as trainable circuit. This layer will calculate the square of absolute value of expectation automatically.
- Parameters
expectation_with_grad (GradOpsWrapper) – a grad ops that receive encoder data and ansatz data and return the expectation value and gradient value of parameters respect to expectation.
weight (Union[Tensor, str, Initializer, numbers.Number]) – Initializer for the convolution kernel. It can be a Tensor, a string, an Initializer or a number. When a string is specified, values from ‘TruncatedNormal’, ‘Normal’, ‘Uniform’, ‘HeUniform’ and ‘XavierUniform’ distributions as well as constant ‘One’ and ‘Zero’ distributions are possible. Alias ‘xavier_uniform’, ‘he_uniform’, ‘ones’ and ‘zeros’ are acceptable. Uppercase and lowercase are both acceptable. Refer to the values of Initializer for more details. Default: ‘normal’.
- Inputs:
enc_data (Tensor) - Tensor of encoder data that you want to encode into quantum state.
- Outputs:
Tensor, The expectation value of the hamiltonian.
- Raises
ValueError – If length of shape of weight is not equal to 1 and shape[0] of weight is not equal to weight_size.
- Supported Platforms:
GPU
,CPU
Examples
>>> import numpy as np >>> import mindspore as ms >>> from mindquantum.core.circuit import Circuit >>> from mindquantum.core.operators import Hamiltonian, QubitOperator >>> from mindquantum.framework import MQN2AnsatzOnlyLayer >>> from mindquantum.simulator import Simulator >>> ms.set_seed(43) >>> ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target="CPU") >>> circ = Circuit().ry('a', 0).h(0).rx('b', 0) >>> ham = Hamiltonian(QubitOperator('Z0')) >>> sim = Simulator('projectq', 1) >>> grad_ops = sim.get_expectation_with_grad(ham, circ) >>> net = MQN2AnsatzOnlyLayer(grad_ops) >>> opti = ms.nn.Adam(net.trainable_params(), learning_rate=0.1) >>> train_net = ms.nn.TrainOneStepCell(net, opti) >>> for i in range(100): ... train_net() >>> net.weight.asnumpy() array([ 0.05957557, -1.5686936 ], dtype=float32) >>> net() Tensor(shape=[1], dtype=Float32, value= [ 1.56737148e-08])