mindquantum.framework.MQAnsatzOnlyLayer

查看源文件
class mindquantum.framework.MQAnsatzOnlyLayer(expectation_with_grad, weight='normal')[源代码]

仅包含ansatz线路的量子神经网络,ansatz线路的参数是可训练的参数。

参数:
  • expectation_with_grad (GradOpsWrapper) - 梯度算子,接收encoder数据和ansatz数据,并返回期望值和参数相对于期望的梯度值。

  • weight (Union[Tensor, str, Initializer, numbers.Number]) - 卷积核的初始化器。它可以是Tensor、字符串、Initializer或数字。指定字符串时,可以使用 'TruncatedNormal''Normal''Uniform''HeUniform''XavierUniform' 分布以及常量'One'和'Zero'分布中的值。支持别名 'xavier_uniform''he_uniform''ones''zeros'。同时支持大写和小写。有关更多详细信息,请参阅Initializer的值。默认值: 'normal'

输出:

Tensor,hamiltonian的期望值。

异常:
  • ValueError - 如果 weight 的shape长度不等于1,并且 weight 的shape[0]不等于 weight_size

支持平台:

GPU, CPU

样例:

>>> 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 MQAnsatzOnlyLayer
>>> from mindquantum.simulator import Simulator
>>> ms.set_seed(42)
>>> ms.set_context(mode=ms.PYNATIVE_MODE, device_target="CPU")
>>> circ = Circuit().ry('a', 0).h(0).rx('b', 0)
>>> ham = Hamiltonian(QubitOperator('Z0'))
>>> sim = Simulator('mqvector', 1)
>>> grad_ops = sim.get_expectation_with_grad(ham, circ)
>>> net =  MQAnsatzOnlyLayer(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([-1.5720805e+00,  1.7390326e-04], dtype=float32)
>>> net()
Tensor(shape=[1], dtype=Float32, value= [-9.99999166e-01])