import公式
from scipy.optimize import curve_fit
x,y = np.loadtxt("mystery1.csv",delimiter=",",unpack=True)
def test_func( m, a, b, c , d , e ):
return a*m + b*m**2 + c*m + d*np.sin(e*m)
return一个像上面的函数,比如sin,重点是d之后的、
popt, pcov = curve_fit (test_func, x , y , p0 = [0.0556, 1 , 4 , 2, 3 ])
(函数,x,y,po=四个)
a_expected = popt[0]
b_expected = popt[1]
c_expected = popt[2]
d_expected = popt[3]
e_expected = popt[4]
x_model = np.linspace(-4 , 4 , 200)
y_2 = test_func( x_model , a_expected, b_expected, c_expected , d_expected , e_expected)
plt.plot(x_model , y_2 , label = " fit using the curve thing " , color = "green")
plt.scatter(x,y, label = "the picture from data ")
plt.legend()
plt.xlabel("x")
plt.ylabel("y")
plt.title(" the realtionship between x and y ")
example 2
𝑦=𝐴∗𝑠𝑖𝑛(𝐵𝑥+𝐶)
> def my_sin_function(x, A, B, C):
return A * np.sin(B * x + C)
# Use curve_fit by passing in the sin function, x data, and y data
popt, pcov = curve_fit(my_sin_function, x_sin, y_sin)
# Print the array of fitted parameter values
print(popt)
a_expected = popt[0] # get fitted A value
b_expected = popt[1] # get fitted B value
c_expected = popt[2] # get fitted C value
# use my_sin_function with new parameters to get expected y values
y_sin_expected = my_sin_function(x_sin, a_expected, b_expected, c_expected)
# plot our actual data
plt.scatter(x_sin, y_sin, label = "data")
# plot our fitted curve
plt.plot(x_sin, y_sin_expected, color = "orange", label = "fit")
plt.legend()
plt.xlabel('x')
plt.ylabel('y')