You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Qiskit中parameter_binds参数类型不兼容错误求助

解决Qiskit中parameter_binds的TypeError与哈希问题

问题根源

你遇到的TypeError是因为Qiskit Aer后端的旧版parameter_binds API要求特定的嵌套列表元组格式,而你使用的字典格式是Qiskit Terra新版本的参数绑定方式,二者不兼容。另外,若self.thetas不是Qiskit官方的Parameter实例,还会触发"列表不可哈希"的错误。

解决方案

优先使用Qiskit推荐的新版parameter_values参数替代parameter_binds,它支持更简洁的列表或字典格式,完全规避旧API的类型限制。

修改后的run函数代码

def run(self, i):
    params = i
    backend = Aer.get_backend('qasm_simulator')            
    # 生成与self.thetas顺序匹配的参数值列表
    param_values = [params[k].item() for k in range(NUM_QUBITS)]
    job_sim = backend.run(self.circuit,
                          shots=self.shots,
                          parameter_values=param_values)  # 替换为新版参数
    result_sim = job_sim.result()
    counts = result_sim.get_counts(self.circuit)
    return self.N_qubit_expectation_Z(counts, self.shots, NUM_QUBITS)

可选:使用字典格式绑定参数

如果需要明确指定参数与值的对应关系(比如参数顺序不确定),可以用字典形式:

def run(self, i):
    params = i
    backend = Aer.get_backend('qasm_simulator')            
    param_values = {self.thetas[k]: params[k].item() for k in range(NUM_QUBITS)}
    job_sim = backend.run(self.circuit,
                          shots=self.shots,
                          parameter_values=param_values)
    result_sim = job_sim.result()
    counts = result_sim.get_counts(self.circuit)
    return self.N_qubit_expectation_Z(counts, self.shots, NUM_QUBITS)

关键注意事项

  1. 确认参数类型:self.thetas[k]必须是Qiskit的qiskit.circuit.Parameter实例,否则会触发哈希错误。
  2. 值类型转换:通过.item()将torch Tensor转换为Python原生float,确保参数值格式符合要求。
  3. API版本适配:parameter_binds已被标记为弃用,新版本Qiskit(0.20+)均推荐使用parameter_values。

旧版本兼容方案(不推荐)

若因环境限制必须使用parameter_binds,需严格按照要求的格式构造参数:

def run(self, i):
    params = i
    backend = Aer.get_backend('qasm_simulator')            
    param_binds = []
    for k in range(NUM_QUBITS):
        # 获取参数在电路中的索引
        param_idx = self.circuit.parameters.index(self.thetas[k])
        # 构造旧API要求的格式:list[list[tuple[tuple[int], list[float]]]]
        param_binds.append([((param_idx,), [params[k].item()])])
    job_sim = backend.run(self.circuit,
                          shots=self.shots,
                          parameter_binds=param_binds)
    result_sim = job_sim.result()
    counts = result_sim.get_counts(self.circuit)
    return self.N_qubit_expectation_Z(counts, self.shots, NUM_QUBITS)

内容的提问来源于stack exchange,提问作者Premuim Active

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 18:05:17