MindQuantum 中 get_exceptation_with_grad
和 grad_ops
之间的关系
MindQuantum 中模拟器 Simulator
下的两个函数 get_exceptation_with_grad
和 grad_ops
可能会让一些朋友感到疑惑。
他们其实就是基于类和方法、函数嵌套构造起来的。本文中,我们将繁杂的代码简单化,清楚显示出它们之间的关系,以便大家理解。
class Simulator: # simulator 模拟器类
# 模拟器众多方法中的一个
def get_exceptation_with_grad(self, hams=None): # 输入为 hams, circ_right, simulator_left 等,这里就只用 hams 代替。
# get_exceptation_with_grad 唯一嵌套的方法:grad_ops
def grad_ops(input): # 输入为各量子门的参数
f = input * 2 # 进行计算,这里简化为数
g = input * 3
return f, g # 运行结果应该是期望值和梯度
return grad_ops # MindQuantum 中,这里返回的是一个封装了 hams, grad_ops 等的一个封装器,这里简化为单独的 grad_ops
sim = Simulator()
grad_ops = sim.get_exceptation_with_grad() # 出于物理含义,一般也会起名叫做 grad_ops,这可能是朋友们困惑的来源之一
print(grad_ops(3))
f_and_g = sim.get_exceptation_with_grad() # 但也可以叫别的,这就清楚多了。
print(f_and_g(3))
(6, 9)
(6, 9)