如何使用Python对数据进行概率拟合

问题描述 投票:0回答:1

抱歉问了低级问题。我是一名物理学家,但我对编程了解不多 我有数据想要对其进行拟合概率,但我没有解决方案来解决它

示例文件数据

x y z t
-2.6477448112689693E-5 -0.001207315269806859 0.0025318773588394084 287.67551366492546
-2.7110000000000003E-5 -0.00122208 0.0025964600000000005 287.58846937867315
-2.6242756278597524E-5 -0.0012018372028238663 0.002507915658924251 287.70800576511095

所以我想使用xt

我也尝试了这个在互联网上资助的代码,但没有像我预期的那样工作

原代码

from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

# Define the Gaussian function
def Gauss(x, A, B):
    y = A*np.exp(-1*B*x**2)
    return y
def parabola(x, a,b, c):
    return a*(x**2) - c

xdata = [ -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
ydata = [1.2, 4.2, 6.7, 8.3, 10.6, 11.7, 13.5, 14.5, 15.7, 16.1, 16.6, 16.0, 15.4, 14.4, 14.2, 12.7, 10.3, 8.6, 6.1, 3.9, 2.1]

xdata = np.asarray(xdata)
ydata = np.asarray(ydata)
plt.plot(xdata, ydata, 'o')


parameters, covariance = curve_fit(parabola, xdata, ydata)

fit_A = parameters[0]
fit_B = parameters[1]
fit_c =parameters[2]

fit_y = parabola(xdata, fit_A, fit_B,fit_c)
plt.plot(xdata, ydata, 'o', label='data')
plt.plot(xdata, fit_y, '-', label='fit')
plt.legend()

输出

所以我做了一点改变来从我的文件中获取数据,但它现在不起作用

我的代码


import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import os
path = os.path.join(os.getcwd(),"Temp.txt")
f_t = open(path, 'r')

def get_3data(f):
    X=[];Y=[];Z=[];T=[]

    for i in f.readlines():
        x,y,z,t =i.split()
        X.append(float(x))
        Y.append(float(t))

    f.close()
    return X,Y
xarray,yarray = get_3data(f_t)

def fit_probolic(xdata,ydata):

    def parabola(x, c,a):
        return c-a*(x**2)
    #sort data
    L = sorted(zip(xdata,ydata))
    xdata, ydata = zip(*L)
    xdata=np.array(xdata)
    ydata=np.array(ydata)
    
    parameters, covariance = curve_fit(parabola, xdata, ydata)

    fit_A = parameters[0]
    fit_B = parameters[1]
    print('n0 = ', fit_A)
    print('n2 = ',fit_B)
    fit_y =parabola(xdata, fit_A,fit_B)
    plt.plot(xdata, ydata, 'o', label='data',linewidth=0.1)
    plt.plot(xdata, fit_y, '-', label='fit',linewidth=2)
    plt.legend()
    plt.show()

fit_probolic(xarray,yarray)

输出

期待输出

python matplotlib curve-fitting scipy-optimize
1个回答
0
投票

你应该使用

scipy.optimize.curve_fit

from scipy.optimize import curve_fit

popt, pcov = curve_fit(parabola, xdata, ydata)
print(popt)
# [ -0.1477191    1.         -16.02589081]

xs = np.linspace(-10, 10)
ys = parabola(xs, *popt)

plt.plot(xdata, ydata, 'o')
plt.plot(xs, ys, '-')

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.