函数导致的结果不是使用optimize.curve_fit

时间:2018-09-10 09:37:48

标签: python numpy scipy curve-fitting

我记录了从固体表面到五个位置的实验温度。在每个时间步长处,我都希望将这些读数拟合到由我的函数Temp_Function_JLT(X,h)定义的理论曲线上。

X是一个多维数组,包含x_coordinates以及时间,初始温度和材料属性(所有独立变量)。 “ h”是传热系数,出于本练习的目的,我正尝试对其进行优化(暂时不考虑物理原理。)

这是我的温度函数的定义:

 import pandas as pd
 import numpy as np
 import matplotlib.pyplot as plt
 import pickle
 import scipy.optimize as opt
 from scipy.special import erfc


def Temp_Function_JLT(X,ht):
    # Work around the fact that only one independent variable can be passed to optimize.curve_fit
    x,t,T0,q,alpha,rho,c,k = X 

    term_a = q/ht
    term_b = erfc(x/np.sqrt(4*alpha*t))
    term_c = np.exp(((ht*x)/(np.sqrt(alpha)*np.sqrt(k*rho*c)))+((ht**2)/(k*rho*c)))
    term_d = erfc((ht*np.sqrt(t))/(np.sqrt(k*rho*c)) + (x/np.sqrt(4*alpha*t)))
    Temperature = (term_a * (term_b - term_c * term_d)) + T0 - 273

return Temperature

该功能有效。我可以使用一些初始参数来运行它并获取合理的值。对于这个问题,更重要的是,如果我使用以下数据进行调用:

t = 1
x_test = np.linspace(0.004,0.02,5) # TC locations
time_test = range(1,180,30)
T0_test = 25 + 273
q_test = 20000
h_test = 10

我将获得一个numpy数组作为形状(1,)的解,它给出np.ndim为1的答案(在以下先前的问题中已经提到过:

Least Linear Squares: scipy.optimize.curve_fit() throws "Result from function call is not a proper array of floats."

Fitting a vector function with curve_fit in Scipy

Fitting a 2D Gaussian function using scipy.optimize.curve_fit - ValueError and minpack.error

当我调用opt.curve_fit()时出现问题。 indepth_temperatures是一个列表,其中包含每个测试的数组。我遍历它(遍历每个测试),然后根据以下代码对每一行执行拟合(每个时间步):

for i,test in enumerate(indepth_temperatures):

    # Iterate over every row
    for j,row in enumerate(test):
        # Define tuple that contains all independent variables
        X = (TC_depth,
             times[i][j],
             T0_temperatures[i] + 273,
             20000,
             pmma_alpha,
             pmma_rho,
             pmma_c,
             pmma_k)
        print(Temp_Function_JLT(X,h0))
        print(row)
        print('---')
        # Call function to optimize curve fit on h
        popt, pcov = opt.curve_fit(Temp_Function_JLT,X,row,h0)
        print(popt)

对于第一次迭代,我得到以下结果:

[23.2034 23.2034 23.2034 23.2034 23.2034]   # comes from print(Temp_Function_JLT(X,h0))
[23.937 22.619 22.59 24.884 21.987000000000002]  # comes from print(row)

随后出现此错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'

---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-67-9c4545fd257b> in <module>()
     22         print('---')
     23         # Call function to optimize curve fit on h
---> 24         popt, pcov = opt.curve_fit(Temp_Function_JLT,X,row,h0)
     25         print(popt)

~\AppData\Local\Continuum\anaconda2\envs\py36\lib\site-packages\scipy\optimize\minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs)
    749         # Remove full_output from kwargs, otherwise we're passing it in twice.
    750         return_full = kwargs.pop('full_output', False)
--> 751         res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
    752         popt, pcov, infodict, errmsg, ier = res
    753         cost = np.sum(infodict['fvec'] ** 2)

~\AppData\Local\Continuum\anaconda2\envs\py36\lib\site-packages\scipy\optimize\minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
    392         with _MINPACK_LOCK:
    393             retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol,
--> 394                                      gtol, maxfev, epsfcn, factor, diag)
    395     else:
    396         if col_deriv:

error: Result from function call is not a proper array of floats.

我尝试从我的函数np.ravel(Temperature)或Temperature.flatten()中返回而没有运气。错误仍然存​​在,我不知道为什么会出现。如前所述,我已经检查了函数返回的尺寸,它是一维数组。

任何帮助将不胜感激!

更新:我意识到很难复制这段代码,所以这是一个简化的版本:

Temp_Function_JLT(X,h0):保持不变。

pmma_rho = 1200 # kg/m3
pmma_c = 1500 # J/kgK
pmma_k = 0.16 # W/mK
pmma_alpha = pmma_k/(pmma_rho*pmma_c)
x_test = np.linspace(0.004,0.02,5) # TC locations
t = 1
T0_test = 25 + 273
q_test = 20000
h_test = 10

X = (x_test,t,T0_test,q_test,pmma_alpha,pmma_rho,pmma_c,pmma_k)
y_data = [23.937 22.619 22.59 24.884 21.987000000000002]

opt.curve_fit(Temp_Function_JLT, X, y_data, h_test)

1 个答案:

答案 0 :(得分:1)

我意识到我的代码出了什么问题。即使我的y_data(行)被定义为一维numpy数组,其数据类型还是对象。我还不明白为什么这是原因,但是通过使用np.astype(np.float)强制数据类型,opt.curve_fit起作用了。