python nlopt包:“…”;。。。取1个位置参数,但取2个;
以下python代码使用nlopt库训练qonn(量子光学神经网络),以了解CNOT门的功能:python nlopt包:“…”;。。。取1个位置参数,但取2个;,python,nlopt,Python,Nlopt,以下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 s
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
文件“../BOBYQA.py”,第43行,在
theta_opt=opt.optimize([1]*info['numpresses']))
文件“User\Anaconda3\lib\site packages\nlopt.py”,第334行,在优化中
返回_nlopt.opt_优化(self,*args)
TypeError:costfunc()接受1个位置参数,但提供了2个
我做错了什么?我不是python专家。提前感谢优化目标函数签名不正确。请将目标函数的形式更改为
f(x,grad)
NLOPT文档参考,转到目标函数:
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