import mindspore as ms
from mindspore import nn, Parameter
from mindquantum import Circuit, Hamiltonian, Simulator, X, H, RY, RX
from mindquantum.framework import MQLayer # 量子层的封装接口[[2]]
# ① 编码线路:把经典特征映射到量子态
def build_encoder(num_qubits):
circ = Circuit()
for i in range(num_qubits):
circ.h(i) # 初始 Hadamard
circ.ry(f'x{i}', i) # 参数化 Y 旋转,参数名对应特征 x_i
return circ
# ② 可训练线路(Ansatz):待学习的参数化门
def build_ansatz(num_qubits, depth=2):
circ = Circuit()
for d in range(depth):
for i in range(num_qubits):
circ.rx({f't{d}_{i}': 1.0}, i) # 参数化 X 旋转
# 交叉 CNOT 形成纠缠
for i in range(num_qubits - 1):
circ.x(i, i + 1)
return circ
n_qubits = 2
encoder = build_encoder(n_qubits)
ansatz = build_ansatz(n_qubits, depth=2)
# 将编码和 Ansatz 串联
pqc = encoder + ansatz
# 这里以 Z⊗Z 为例,得到一个标量输出
from mindquantum.core.operators import QubitOperator
ham = Hamiltonian(QubitOperator('Z0 Z1', -1))
encoder_params=encoder.params_name
ansatz_params=ansatz.params_name
# ① 使用 Simulator 生成带梯度的期望值算子
sim = Simulator('mqvector', n_qubits) # 也可以换成 'mqvector'、'mqmatrix' 等后端
grad_ops = sim.get_expectation_with_grad(
ham,
pqc,
parallel_worker=4
)
# ② 用 MQLayer 包装
quantum_layer = MQLayer(grad_ops) # 已封装前向+梯度[[6]]
x = ms.Tensor([
[1.0, 2.0],
[2.0, 4.0],
[3.0, 6.0],
[4.0, 8.0]
], ms.float32)
# 前向传播
y = quantum_layer(x)
print("输出形状:", y.shape) # 应该是 (4, 1)
print("输出值:\n", y)
以上代码,为什么报错?
ValueError Traceback (most recent call last)
Cell In[9], line 59
51 x = ms.Tensor([
52 [1.0, 2.0],
53 [2.0, 4.0],
54 [3.0, 6.0],
55 [4.0, 8.0]
56 ], ms.float32)
58 # 前向传播
---> 59 y = quantum_layer(x)
60 print("输出形状:", y.shape) # 应该是 (4, 1)
61 print("输出值:\n", y)
File D:\10_The_Programs\4_The_Codes\00_virtual_environment\DeepLearning\Lib\site-packages\mindspore\nn\cell.py:1355, in Cell.__call__(self, *args, **kwargs)
1352 if not (self.requires_grad or self._dynamic_shape_inputs or self.mixed_precision_type):
1353 if not (self._forward_pre_hook or self._forward_hook or self._backward_pre_hook or self._backward_hook or
1354 self._shard_fn or self._recompute_cell or (self.has_bprop and _pynative_executor.requires_grad())):
-> 1355 return self.construct(*args, **kwargs)
1357 return self._run_construct(*args, **kwargs)
1359 return self._complex_call(*args, **kwargs)
File D:\10_The_Programs\4_The_Codes\00_virtual_environment\DeepLearning\Lib\site-packages\mindquantum\framework\layer.py:94, in MQLayer.construct(self, arg)
92 def construct(self, arg):
93 """Construct a MQLayer node."""
---> 94 return self.evolution(arg, self.weight)
File D:\10_The_Programs\4_The_Codes\00_virtual_environment\DeepLearning\Lib\site-packages\mindspore\nn\cell.py:1355, in Cell.__call__(self, *args, **kwargs)
1352 if not (self.requires_grad or self._dynamic_shape_inputs or self.mixed_precision_type):
1353 if not (self._forward_pre_hook or self._forward_hook or self._backward_pre_hook or self._backward_hook or
1354 self._shard_fn or self._recompute_cell or (self.has_bprop and _pynative_executor.requires_grad())):
-> 1355 return self.construct(*args, **kwargs)
1357 return self._run_construct(*args, **kwargs)
1359 return self._complex_call(*args, **kwargs)
File D:\10_The_Programs\4_The_Codes\00_virtual_environment\DeepLearning\Lib\site-packages\mindquantum\framework\operations.py:134, in MQOps.construct(self, enc_data, ans_data)
132 def construct(self, enc_data, ans_data):
133 """Construct an MQOps node."""
--> 134 check_enc_input_shape(enc_data, self.shape_ops(enc_data), len(self.expectation_with_grad.encoder_params_name))
135 check_ans_input_shape(ans_data, self.shape_ops(ans_data), len(self.expectation_with_grad.ansatz_params_name))
136 fval, g_enc, g_ans = self.expectation_with_grad(enc_data.asnumpy(), ans_data.asnumpy())
File D:\10_The_Programs\4_The_Codes\00_virtual_environment\DeepLearning\Lib\site-packages\mindspore\ops\primitive.py:955, in constexpr.<locals>.decorator.<locals>.ProxyOp.__call__(self, *args, **kwargs)
954 def __call__(self, *args, **kwargs):
--> 955 return fn(*args, **kwargs)
File D:\10_The_Programs\4_The_Codes\00_virtual_environment\DeepLearning\Lib\site-packages\mindquantum\framework\operations.py:38, in check_enc_input_shape(data, encoder_tensor, enc_len)
36 raise TypeError(f"Encoder parameter requires a Tensor but get {type(data)}")
37 if len(encoder_tensor) != 2 or encoder_tensor[1] != enc_len:
---> 38 raise ValueError(
39 'Encoder data requires a two dimension Tensor with second'
40 + f' dimension should be {enc_len}, but get shape {encoder_tensor}'
41 )
ValueError: Encoder data requires a two dimension Tensor with second dimension should be 0, but get shape (4, 2)
最新发布