【问题标题】:python nlopt package: "...takes 1 positional argument but 2 were given"python nlopt 包:“...接受 1 个位置参数,但给出了 2 个”
【发布时间】:2020-12-31 00:23:24
【问题描述】:

以下 python 代码使用 nlopt 库来训练 qonn(量子光学神经网络)来学习 CNOT 门的功能:

import numpy as np
import bosonic as b
import nlopt
global psi_in, psi_out, system


system, info = b.qonn.build_system_function(2, 4, 2, phi=3.141592653589793, method='clements', lossy=False) #phi is strength nonlinearity
#CNOT dataset
K=4 #aantal input-output pairs

psi_in = np.array([
                [[0], [0], [1], [0], [0], [0], [0], [0], [0], [0]],
                [[0], [0], [0], [1], [0], [0], [0], [0], [0], [0]],
                [[0], [0], [0], [0], [0], [1], [0], [0], [0], [0]],
                [[0], [0], [0], [0], [0], [0], [1], [0], [0], [0]]], dtype=complex)
psi_out = np.array([
                [[0], [0], [1], [0], [0], [0], [0], [0], [0], [0]],
                [[0], [0], [0], [1], [0], [0], [0], [0], [0], [0]],
                [[0], [0], [0], [0], [0], [0], [1], [0], [0], [0]],
                [[0], [0], [0], [0], [0], [1], [0], [0], [0], [0]]], dtype=complex)


#cost function
def costfunc(theta):
    S = system(theta)
    K = psi_in.shape[0]
    res = 1
    for i in range(K):
        temp = np.dot(S,psi_in[i])
        temp2 = np.dot(np.transpose(psi_out[i]),temp)
        res -= (1/K) * ((np.absolute(temp2)) ** 2)
    return res


#nlopt

opt = nlopt.opt(nlopt.LN_BOBYQA, info['numPhases'])
opt.set_min_objective(costfunc)
opt.set_lower_bounds([0]*info['numPhases'])
opt.set_upper_bounds([2*np.pi]*info['numPhases'])
opt.set_maxtime(3)
theta = np.random.rand(info['numPhases'])*2*np.pi
theta_opt = opt.optimize([1]*info['numPhases'])
minf = opt.last_optimum_value()
print("minimum value = ", minf)

但我收到以下错误:

File ".../BOBYQA.py", line 43, in <module>
    theta_opt = opt.optimize([1]*info['numPhases'])
  File "User\Anaconda3\lib\site-packages\nlopt.py", line 334, in optimize
    return _nlopt.opt_optimize(self, *args)
TypeError: costfunc() takes 1 positional argument but 2 were given

我做错了什么?我不是python专家。提前致谢

【问题讨论】:

    标签: python nlopt


    【解决方案1】:

    优化目标函数签名不正确。请将您的目标函数更改为f(x, grad) 的形式。
    NLOPT 文档参考,转到目标函数https://nlopt.readthedocs.io/en/latest/NLopt_Python_Reference/

    def costfunc(theta, grad):
        S = system(theta)
        K = psi_in.shape[0]
        res = 1
        for i in range(K):
            temp = np.dot(S,psi_in[i])
            temp2 = np.dot(np.transpose(psi_out[i]),temp)
            res -= (1/K) * ((np.absolute(temp2)) ** 2)
        return res
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-13
      • 2018-06-24
      • 2019-04-06
      • 2022-01-02
      • 2019-04-20
      • 2018-11-15
      • 2014-07-19
      • 2016-08-09
      相关资源
      最近更新 更多