【问题标题】:Kernel Restarting on jupyter notebook在 jupyter notebook 上重启内核
【发布时间】:2023-01-13 04:16:13
【问题描述】:

我在下一个代码的开发过程中遇到了一个问题:

import nlopt

import numpy as np

import time

def Rosenbrock(x):

N=len(x)

x1=x[0:N-1]

x2=x[1:N]

return(sum(100*np.square(x2 - np.square(x1)) + np.square(np.ones(N-1) - x1)))

def myfunc1(x, grad):

    if grad.size > 0:

        grad[:]=NULL

    return Rosenbrock(x)`

def myfunc2(x, grad):

    if grad.size > 0:

        grad[:]=Rosen_grad(x)

    return Rosenbrock(x)

names = ["LN_SBPLX", "LN_NELDERMEAD", "LN_PRAXIS", "LN_NEWUOA", "LN_BOBYQA", "LN_COBYLA", "LD_MMA", "LD_LBFGS"]

j=2

for i in range(len(names)):

ini = time.time()
print('entra en el primer loop')
while time.time()-ini < 180:
    x0 = np.repeat(0,j)
    print(names[i])
    a = 'nlopt.' + names[i]
    opt = nlopt.opt(a, len(x0))
    print(a)
    if(i == "LD_MMA" or i == "LD_LBFGS" ): #Depending on the method we have to change the function to optimize
        opt.set_min_objective(myfunc2) 
    else :
        opt.set_min_objective(myfunc1)
    opt.set_lower_bounds(np.repeat(-10, len(x0)))
    opt.set_upper_bounds(np.repeat(10, len(x0)))
    opt.set_xtol_rel(0)
    opt.set_stopval(1e-8)
    start=time.time()
    x = opt.optimize(x0)
    end=time.time()
    with open('results' + i, 'w') as f:
        f.write([i,end-start,opt.last_optimize_result()])
    f.close()of 
   j+=1

如您所见,我正在使用 nlopt 来计算 Rosenbrock 函数的一些优化,然后将每个案例保存在不同的文件中。当我在 Jupyter 上运行这段代码时,我会收到一条错误消息,正如您在图片中看到的那样。

我不确定问题是否出在调用函数 nlopt.opt() 的循环中,或者只是与环境的兼容性问题。

谢谢您的帮助 :)

【问题讨论】:

  • 也可能是 nlop."optimizer" 是一个类而不是字符串。

标签: python jupyter-notebook nlopt


【解决方案1】:

你的假设是正确的。列表名称必须以不同方式定义:

names = [nlopt.LN_NELDERMEAD, nlopt.LN_NEWUOA, nlopt.LN_BOBYQA, nlopt.LN_COBYLA]

为了测试,我将算法的数量和函数的维度减少到 2。

j=2

with open('results_dim_' + str(j) + '.txt', 'w') as f:

    for i in range(len(names)):

        ini = time.time()
        print('entra en el primer loop')
        #while time.time()-ini < 180:
        x0 = np.repeat(0,j)
        print(names[i])
        opt = nlopt.opt(names[i], len(x0))
        if(i == "LD_MMA" or i == "LD_LBFGS" ): #Depending on the method we have to change the function to optimize
            opt.set_min_objective(myfunc2) 
        else :
            opt.set_min_objective(myfunc1)
        opt.set_lower_bounds(np.repeat(-10, len(x0)))
        opt.set_upper_bounds(np.repeat(10, len(x0)))
        opt.set_xtol_rel(1e-8)
        opt.set_stopval(0)
        start=time.time()
        x = opt.optimize(x0)
        end=time.time()
        f.write(str(names[i]) + '	' + str(end-start) + '	' + str(x) + '	' + str(opt.last_optimum_value()) + '
')
f.close() 

我为一维创建了一个包含所有算法结果的文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-26
    • 2018-06-29
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 2022-11-02
    相关资源
    最近更新 更多