Scipy - 我怎样才能改进这个曲线拟合 - 找到正确的函数

Scipy - How can I improve this curve fitting - finding the right function

上下文

我试图找到两个变量(pv_ratio、battery_ratio)和第三个变量 'value' 之间的关系。两个比率的范围从 0 到 5,每 0.0625 个点(81x81=6561 个点)并且 'value' 落在 [0,1].

范围内

可以找到 csv here,看起来像这样:

    battery_ratio   pv_ratio    value
0   0.0000  0   1
1   0.0625  0   1
2   0.1250  0   1
3   0.1875  0   1
4   0.2500  0   1
5   0.3125  0   1
6   0.3750  0   1
7   0.4375  0   1
8   0.5000  0   1
9   0.5625  0   1

绘图

先画一些图来了解我的变量之间的关系:

曲线拟合

这是我使用 sicpy.optimize.curve_fit 并寻找指数关系来拟合曲线的代码。此代码片段将 csv 读入 pandas df,找到 f 函数的最佳参数,绘制结果并给出拟合分数。

我一直在迭代工作,尝试了很多f的公式,一点一点提高分数。

from scipy.optimize import curve_fit
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (14.0, 8.0)

def f(X, a, b, c, d, e):
# the function I came up with after some trials, and which I'm trying to improve
    bt_r = X[:,0]  #battery_ratio
    pv_r = X[:,1] #pv_ratio
    return  (1 - a * np.exp(- e * pv_r ** b)) * np.exp(- (d ** bt_r) * c * pv_r)

def fit():
#find optimal parameters and score fit
    X = df[variables].values
    y = df.value.values
    popt, pcov = curve_fit(f, X, y)
    y_real, y_fit = df['value'], f(df[variables].values, *popt)
    score = np.round(np.sum(((y_fit - y_real)**2)),1)
    return popt, score

def check_fit(values):
    #Plot (y_fit, y) for all subsets
    def plot_subset(ax, variable, r_value):
        """Scatter plot (y_fit and y) against 'variable' with the other variable set at ratio
        - variable : string ['pv_ratio', 'battery_ratio']
        - r_value : float 
        """
        # ratio stands for the second variable which is fixed
        ratio = list(set(variables) - set([variable]))[0]
        df_ = df.query("{} == {}".format(ratio, r_value))

        # plot y and y fit
        y_real, y_fit = df_['value'], f(df_[variables].values, *popt)
        for y, c in zip([y_real, y_fit], ['b', 'r']):        
            ax.scatter(df_[variable], y, color=c, s=10, alpha=0.95)
        ax.set_title('{} = {}'.format(ratio, r_value))

    fig, ax = plt.subplots(nrows=2, ncols=len(values), sharex=True, sharey=True)
    for icol, r_value in enumerate(values):
        plot_subset(ax[0, icol], 'pv_ratio', r_value)
        plot_subset(ax[1, icol], 'battery_ratio', r_value)

    fig.tight_layout()
    print 'Score: {}'.format(score)


df = pd.read_csv('data.csv', index_col=0)
variables = ['battery_ratio', 'pv_ratio']
popt, score = fit()
check_fit([0,3,5]) #plot y_real and y_fit for these ratios

上面的代码产生了下面的图片(蓝色:真实,红色:适合)并给出了适合度的分数。 我能得到的最好成绩(=sum((y_real - y_fit)²/len(y)))是9.3e-4,在实践中仍然不是很好,尤其是在ramp-up阶段。

问题

我现在陷入了反复尝试过程显示出其局限性的地步。 我应该如何更快、更有效地设计我的拟合函数? 我能得到比 6.1 更好的分数吗?

感谢您的帮助

更新

归一化分数

按照@jon-custer 的建议,我尝试了 n 多项式拟合。我的代码是 this SO answer.

的略微修改版本
import itertools
import numpy as np
import matplotlib.pyplot as plt

def polyfit2d(data, order=3):
    x = data.pv_ratio
    y = data.battery_ratio
    z = data.value

    ncols = (order + 1)**2
    G = np.zeros((x.size, ncols))

    ij = itertools.product(range(order+1), range(order+1))
    for k, (i,j) in enumerate(ij):
        G[:,k] = x**i * y**j
    m, _, _, _ = np.linalg.lstsq(G, z)

    y['fit'] = polyval2d(x, y, m)
    return m, y_fit

def polyval2d(x, y, m):
    order = int(np.sqrt(len(m))) - 1
    ij = itertools.product(range(order+1), range(order+1))
    z = np.zeros_like(x)
    for a, (i,j) in zip(m, ij):
        z += a * x**i * y**j  
    return z

m, y_fit = polyfit2d(df, 7)

上图显示了最大残差和归一化分数。我得到的最好结果是 7 次多项式。我的分数下降到 ~6.4e-5,残差从不超过 5.5%,这是我满意的准确度。

谢谢。

我找到了这个旧线程,我认为它可以以某种方式帮助某些人。

这不完全是一个 python 相关的线程,您想将您的数据放入一个表面。

还原数据。做一个 1/x 的值,并逐行绘制趋势线。你做到了。