Skip to main content
 首页 » 编程设计

python之对非代数函数使用 scipy.optimize

2024年11月01日1198°冷暖

我想尝试使用 Scipy.optimze 为数据挖掘工具构建求解器。

在使用最小化函数之前我必须定义的函数是这样的,它不是代数函数 - 只是对另一个给出输出估计的程序的可调用查询:

def query(x): 
    import numpy as np 
    file_direc_in="path_to_input_file.csv" 
    file_direc_out="path_to_output_file.csv" 
 
    x=np.array([[1,2,4,6]]) 
    with open(file_direc_in, 'w') as f: 
        np.savetxt(f, x, delimiter=';', fmt='%.3f',newline='\r\n') 
    f.close() 
    os.system(Dataset_query.bat) 
    #batch file takes the array i wrote to from input_file and estimates a result 
    #afterwards the output will be taken from the output file: 
    f = open(file_direc_out,'r') 
    out = np.array([[float(f.readlines()[0])]]) 
    f.close() 
    return out 
 
 
from scipy.optimize import minimize 
x0=np.array([[1,1,1,1]])#first guess 
res=minimize(query,x0,method='nelder-mead',callback=True) 

调用 res 部分后,我看到了通常在控制台中看到的内容:数据挖掘工具回答了我的查询,但 res 变成了 的循环x0 数组是每个循环的输入 - 我认为在每个 cicle 上另一个数组由 minimize 函数测试。

我做错了什么?
如何更改我的查询函数以实现 scipy 将最小化的函数?

请您参考如下方法:

def query(x): 
    import numpy as np 
    file_direc_in="path_to_input_file.csv" 
    file_direc_out="path_to_output_file.csv" 
 
    x=np.array([[1,2,4,6]]) 

重要部分:

    x=np.array([[1,2,4,6]]) 

你扔掉了你的输入!不要那样做,看看会发生什么。