自定义函数拟合

一元函数拟合:

"""拟合任意分布"""
from sklearn.metrics import r2_score
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import numpy as np

# 用来拟合的方程
def function(x, a, b, c):
    y = a * np.exp(-b * x) + c
    return y

# 生成x,y
def get_xy():
    xdata: np.ndarray = np.linspace(0, 4, 50)  # x值
    y = function(xdata, 2.5, 1.3, 0.5)
    rng = np.random.default_rng()
    y_noise = 0.2 * rng.normal(size=xdata.size)
    ydata: np.ndarray = y + y_noise  # 拟合的数据 y
    return xdata, ydata


if __name__ == '__main__':
    x_value, y_value = get_xy()

    # 第一个,拟合的函数,第二个x,第三个y
    # popt: 求得的最优参数
    popt, pcov = curve_fit(function, x_value, y_value)

    # 这个写法是加一个限制:0 <= a <= 3, 0 <= b <= 1 and 0 <= c <= 0.5
    # popt_2, pcov_2 = curve_fit(function, x_value, y_value, bounds=([0, 0, 0.5], [3., 1., 1]))

    y_pred = function(x_value, *popt)  # 预测结果
    r2 = r2_score(y_value, y_pred)     # 输出R2

    print("参数: {}, r2: {:0.4f}".format(np.round(popt,4),r2))

    # 绘图
    plt.plot(x_value, y_value, 'b-', label='data')
    plt.plot(x_value, function(x_value, *popt))
    plt.legend(['y', 'y_pred']) # 绘制图例
    plt.show()
D:\python.exe "D:/02.py"
参数: [2.7121 1.5809 0.5202], r2: 0.9273

Process finished with exit code 0

自定义函数拟合_第1张图片

二元函数拟合:

"""拟合任意分布"""
from sklearn.metrics import r2_score
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import numpy as np

# 用来拟合的方程
def function(x, a, b, c):
    y = a*x[0] + b*x[1] + c
    return y

# 生成x,y
def get_xy():
    xdata0 = np.linspace(0, 4, 50)  # x值
    xdata1 = np.linspace(0, 4, 50)
    y = function((xdata0,xdata1), 2.5, 1.3, 0.5)
    rng = np.random.default_rng()
    y_noise = 0.2 * rng.normal(size=xdata0.size)
    ydata = y + y_noise  # 拟合的数据 y
    return (xdata0,xdata1), ydata


if __name__ == '__main__':
    x_value, y_value = get_xy()

    # 第一个,拟合的函数,第二个x,第三个y
    # popt: 求得的最优参数
    popt, pcov = curve_fit(function, x_value, y_value)

    # 这个写法是加一个限制:0 <= a <= 3, 0 <= b <= 1 and 0 <= c <= 0.5
    # popt_2, pcov_2 = curve_fit(function, x_value, y_value, bounds=([0, 0, 0.5], [3., 1., 1]))

    y_pred = function(x_value, *popt)  # 预测结果
    r2 = r2_score(y_value, y_pred)     # 输出R2

    print("参数: {}, r2: {:0.4f}".format(np.round(popt,4),r2))

    # 绘图
    plt.plot(np.linspace(1,len(x_value[0]),50), y_value)
    plt.plot(np.linspace(1,len(x_value[0]),50), function(x_value, *popt))
    plt.legend(['y', 'y_pred']) # 绘制图例
    plt.show()

你可能感兴趣的:(技巧分享,python,开发语言)