正确使用scipy.optimize.minimize

时间:2019-06-18 15:04:12

标签: python scipy scipy-optimize scipy-optimize-minimize

我有2个固定参数(A,B)和2个非固定参数(C,T_o),用于计算公式R_computed = A + B*tanh((T-T_o)/C)中的响应值。与之进行比较的实际值“ R”必须在两者之间具有最小的可能误差。我用一个计算平方和的平方根的函数计算了最小误差。

该功能是我试图在optimize.minimize中最小化的功能,其中C,T_ox0args= (A,B,R,T)

此刻,我在第52行出现错误: R_comp = A + B*np.tanh((T-T_o)/C)

TypeError:只有length-1个数组可以转换为Python标量

此错误是新错误,我之前已经过过此错误,但是由于代码太混乱,无法回到原来的状态。最终目标是绘制(T,R)(T,R_new),其中R_new基本上是与R拟合的曲线

我尝试过的所有注释掉了。

import numpy as np
#import math
import matplotlib.pyplot as plt 
import scipy

import csv
import pandas as pd
#import operator

df =pd.DataFrame.from_csv('test.csv', index_col = None)
counter = 0
upper = 0
Lower_shelf = 2.2;
#import csv

with open('test.csv') as fin:
    csvin = csv.reader(fin, skipinitialspace=True)
    col_header = next(csvin, [])[1:]
    row_header, data = zip(*((row[0], row[1:]) for row in csvin))
    for row in data:
        if int(row[2]) >= 95 :
            upper = upper + float(row[0])
            counter = counter + 1
Upper_shelf = upper/counter
A = 33.18
B = 30.98      
T = array([  67.4,  100.7,  125.1,  150.6,  175.6,  200.3,  224.9,  249.8,
        275. ,  300. ,  350.5,  399.9,  425. ,  450.2,  475. ])
R = array([  6. ,  15.5,  20. ,  22. ,  30.5,  34. ,  45. ,  57. ,  54. ,
        63. ,  59. ,  64. ,  66. ,  64. ,  69. ])
T_o = (Tmax + Tmin)/2
C = (Tmax -T_o)/2


def ssre (A,B,T,R,C):
    R_comp = A + B*np.tanh((T-T_o)/C)

    ret_val = np.sqrt((R-R_comp)**2)
    return ret_val

Result = scipy.optimize.minimize(fun = ssre,x0 =[C,T_o], args= (A, B, R,T))
C_new = Result.x[0]
T_new = Result.x[1]
R_new = A + B*np.tanh((T-T_new)/C_new)
print(Result)
plt.plot(T,R, 'o')
plt.plot(T,R_new)

1 个答案:

答案 0 :(得分:0)

要解决这个问题有点棘手,因为尽管进行了编辑,但代码仍然包含各种问题。作为以后发布的建议,请尝试发布minimal, reproducible example,以使其他用户更容易理解您的代码和目标。因此,您将获得快速优质的答案。

关于您的代码,我更正了以下内容:

  • 更正将变量传递给它的ssre函数调用。
  • 校正等于l2-范数的平方和的平方根的计算。
import numpy as np
import matplotlib.pyplot as plt 
from scipy.optimize import minimize


def ssre (x, A, B, R, T):
    C, T_o  = x[0], x[1]
    R_comp  = A + B*np.tanh((T - T_o) / C)
    ret_val = np.linalg.norm(R - R_comp, 2)
    return ret_val

# initializations 
A   = 33.2
B   = 31
T   = np.array([67.4, 100.7, 125.1, 150.6, 175.6, 200.3, 224.9, 249.8, 275., 300., 350.5, 399.9, 425., 450.2, 475.])
R   = np.array([  6.,  15.5,   20.,   22.,  30.5,   34.,   45.,   57.,  54.,  63.,   59.,   64.,  66.,   64.,  69.])
T_o = (np.max(T) + np.min(T))/2
C   = (np.max(T) - T_o)/2

# minimize
Result = minimize(fun  = ssre,
                  x0   = [C, T_o],
                  args = (A, B, R, T))
# format results
C_new = Result.x[0]
T_new = Result.x[1]
R_new = A + B*np.tanh((T-T_new)/C_new)

# print and plot
print(Result)
plt.plot(T, R, 'o')
plt.plot(T, R_new)
plt.show()

结果:

      fun: 11.786475736024007
 hess_inv: array([[84.27271526, -4.45138785],
       [-4.45138785, 23.62509084]])
      jac: array([1.78813934e-06, 9.53674316e-07])
  message: 'Optimization terminated successfully.'
     nfev: 76
      nit: 14
     njev: 19
   status: 0
  success: True
        x: array([ 98.74898359, 182.5084917 ])

enter image description here