2
我想使用scipy curve_fit來適合我的數據高斯函數,在網上有很多有用的例子,我試圖讓幾個工作,但無濟於事。我用一個簡單的腳本編寫了數據來診斷問題。簡而言之,curve_fit沒有做任何擬合,該函數只是返回初始參數值,而不管它們與實數有多接近。下面是簡單的腳本代碼:scipy curve_fit返回初始參數估計
# -*- coding: utf-8 -*-
import numpy
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from scipy import optimize
##Fit
def Fit(datax, datay):
# define your function:
def f(x, *p):
p = m, b
return m*numpy.asarray(x) + b
m = 0.4
b = 2.4
p_init = [m, b]
Initial_model = f(datax, [m, b])
plt.plot(datax, Initial_model, label='Initial Model')
plt.title("Initial Model")
# plt.title('Initial Model')
# plt.show()
# fit! (given that data is an array with the data to fit)
print optimize.curve_fit(f, datax, datay, p_init)
coeff, var_matrix = optimize.curve_fit(f, datax, datay, p_init)
global fit
fit = f(datax, *coeff)
plt.plot(datax, fit, 'r-')
plt.show()
print 'Fitted slope 1 = ', coeff[0]
print 'Fitted intercept 1 = ', coeff[1]
return fit
##Plot
def Plot(datax, datay, fit):
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(datax, datay, 'b*')
l = ax.plot(datax, fit, 'r-', linewidth=2)
ax.set_xlabel('Rate')
ax.set_ylabel('Return')
ax.set_title("Test")
ax.autoscale(enable=True, axis='both', tight=None)
ax.grid(True)
plt.show()
##data
datax = numpy.array([7.02, 20.06, 13.78, 16.92, 10.17], dtype=numpy.float64)
datay = numpy.array([5.14, 10.66, 8.44, 9.64, 6.79], dtype=numpy.float64)
##analyze
Fit(datax, datay)
Plot(datax, datay, fit)
Out:
(array([ 0.4, 2.4]), inf)
Fitted slope 1 = 0.4
Fitted intercept 1 = 2.4
事情我已經嘗試: leastsq直接 - 使用:同樣的問題 -reinstalling SciPy的:沒有變化
我使用蟒蛇在Windows 7
可能是什麼問題?
什麼情況是你給你的數據增加了噪音,並改變了初始猜測值,所以它不再與實際參數相同? –