Trouble with curve fitting - matplotlib

血红的双手。 提交于 2019-12-12 04:13:12

问题


I am trying to plot a sin function to a data set. I found a tutorial online using scipy.optimize, but it seems not to work even though I copied the code exactly.

At the top:

def func(x, a, b, c, d):
    return a * np.sin(b * (x + c)) + d

At the end:

scipy.optimize.curve_fit(func, clean_time, clean_rate)
pylab.show()

There is no line on the output window.

If anyone would like screencaps or the whole code, feel free to comment below.

Thanks!


回答1:


of course it does not plot anything, curve_fit does not plot.

Look in the documentation, the return values of curve_fit are an array with the estimated parameters and a 2d array with the estimated covariance matrix. You have to plot the fit-function with the estimated parameters yourself.

I also would suggest to fit a*sin(bx +c) +d as then b and c are not correlated.

this works:

import matplotlib.pyplot as plt
import numpy as np
from numpy.random import normal
from scipy.optimize import curve_fit

x_data = np.linspace(0, 2*np.pi, 30)
y_data = np.sin(x_data) + normal(0, 0.2, 30)


def func(x, a, b, c, d):
    return a * np.sin(b*x + c) + d

parameter, covariance_matrix = curve_fit(func, x_data, y_data)

x = np.linspace(min(x_data), max(x_data), 1000)
plt.plot(x_data, y_data, 'rx', label='data')
plt.plot(x, func(x, *parameter), 'b-', label='fit')   # the star is to unpack the parameter array
plt.show()

this is the result:




回答2:


I have an example code with data in the form a sine curve and a user defined function that fits the data.

Here is the code:

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

xdata = np.array([2.65, 2.80, 2.96, 3.80, 3.90, 4.60, 4.80, 4.90, 5.65, 5.92])
ydata = np.sin(xdata)

def func(x,p1,p2,p3): # HERE WE DEFINE A SIN FUNCTION THAT WE THINK WILL FOLLOW THE DATA DISTRIBUTION
    return p1*np.sin(x*p2+p3)

# Here you give the initial parameters for p0 which Python then iterates over
# to find the best fit
popt, pcov = curve_fit(func,xdata,ydata,p0=(1.0,1.0,1.0)) #THESE PARAMETERS ARE USER DEFINED

print(popt) # This contains your two best fit parameters

# Performing sum of squares
p1 = popt[0]
p2 = popt[1]
p3 = popt[2]
residuals = ydata - func(xdata,p1,p2,p3)
fres = sum(residuals**2)

print(fres) #THIS IS YOUR CHI-SQUARE VALUE!

xaxis = np.linspace(1,7,100) # we can plot with xdata, but fit will not look good 
curve_y = func(xaxis,p1,p2,p3)
plt.plot(xdata,ydata,'*')
plt.plot(xaxis,curve_y,'-')
plt.show()



来源:https://stackoverflow.com/questions/25030675/trouble-with-curve-fitting-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!