【问题标题】:Using scipy.optimize for a non algebraic function对非代数函数使用 scipy.optimize
【发布时间】:2013-12-21 05:29:23
【问题描述】:

我想尝试使用 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)

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

我做错了什么?
如何更改我的queryfunction 以实现 scipy 将最小化的功能?

【问题讨论】:

    标签: python optimization numpy scipy


    【解决方案1】:
    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]])
    

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

    【讨论】:

    • 如果我删除了我定义x 的行,我的数据挖掘工具出现错误...我无法删除此行,因为我将x 写入了一个csv 文件。 .np.savetxt(f, x, delimiter=';', fmt='%.3f',newline='\r\n') 我猜minimize不会改变我的 x - 而且我不知道如何让 scipy 清楚这一点 - 我看到的所有示例都不同。
    • @user2956831:那么,您可能使用错误的数据挖掘工具。绝对不能丢弃传递给函数的 x 的值。
    • 他们有一个代数表达式,如:def rosen(x): #The Rosenbrock function return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)
    • 但是 query(x) 需要一个名为 x 的变量,或者在这种情况下是一个数组 x 如果我没有错,如果我省略了 x,那么得到一个错误是很合乎逻辑的
    • @user2956831:数组x 应该是传入函数的那个​​。你不应该在函数内部重新定义x,忽略传递给它的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 2014-06-08
    相关资源
    最近更新 更多