如何使用Python中的leastsq优化具有两个变量的数据?

时间:2016-07-01 23:30:52

标签: python numpy optimization scipy scikit-learn

我有以下表格的data

X   Y1  Y2  Y3  Y4  Y5  Y6
1.42857 4.83    4.58    4.43    4.31    4.22    4.14
1.40845 3.87    3.63    3.49    3.38    3.3 3.23
1.38889 3.17    2.93    2.79    2.69    2.62    2.56
1.36986 2.65    2.41    2.27    2.17    2.11    2.05
1.35135 2.27    2.02    1.88    1.78    1.72    1.67
    :     :       :       :       :        :      :
1.01010 2.26    1.6 1.21    0.97    0.79    0.66
1.00000 2.01    1.44    1.1 0.88    0.73    0.62

我正在尝试优化表单的功能:

enter image description here enter image description here

现在我的y变量有6列,我可以优化我在MWE中完成的一列(在MWE#3中)。如何优化函数以获取所有6列值的参数A,n和B?换句话说,如何为y的所有6个值获得A,n和B的值。

MWE

import numpy as np
from scipy.signal import argrelextrema
import scipy.interpolate
from scipy.optimize import leastsq


with open('./exp_fit.dat', "r") as data:
    while True:
        line = data.readline()
        if not line.startswith('#'):
            break
    data_header = [i for i in line.strip().split('\t') if i]
    _data_ = np.genfromtxt(data, names = data_header, dtype = None, delimiter = '\t')
_data_.dtype.names = [j.replace('_', ' ') for j in _data_.dtype.names]
data = np.array(_data_.tolist())

x = _data_['X']
x_interp = np.linspace(x[-1], x[0], 100)

y = np.zeros(shape = (len(x), 6))
y_interp = np.zeros(shape = (len(x_interp), 6))
for i in range(6):
    y[:, i] = data[:, i + 1]
    tck = scipy.interpolate.splrep(x[::-1], y[::-1, i], s=0)
    y_interp[::-1, i] = scipy.interpolate.splev(x_interp, tck, der = 0)


def residuals(p, y, x):
    A_lt, n_lt, B_lt, A_it, n_it, B_it, A_ht, n_ht, B_ht = p
    err = y - (1 / (1 / ((A_it * (15 ** (-n_it)) * np.exp(B_it * x / 1000)) + \
        (A_lt * (15 ** (-n_lt)) * np.exp(B_lt * x / 1000))) + \
        1 / (A_ht * (15 ** (-n_ht)) * np.exp(B_ht * x / 1000))))
    return err
p1 = [2.789E-05, 1.47, 9.368E+03, 2.789E-05, 1.47, 9.368E+03, 2.789E-05, 1.47, 9.368E+03]
plsq = leastsq(residuals, p1, args=(y_interp[:, 2], x_interp))
A1, n1, B1, A2, n2, B2, A3, n3, B3 =  plsq[0]

0 个答案:

没有答案