2014-09-26 112 views
0

我想擬合一條線,該線使用誤差爲 的倒數作爲權重。scipy polyfit x,y,權重=誤差線

我把我的數據x和y分成10個分檔(每個分26個分)並取其平均值。 這不是價值的矩陣,所以polyfit對此並不滿意。

# note I didn't test this pseudo code.... 
import numpy as np 
import scipy 

x = np.random.randn(100) 
y = np.random.rand(100) 

x_bins = np.linspace(x.min(), x.max(), 10) # reduction of data into 10 bins 
y_bins = np.linspace(y.min(), y.max(), 10) 

x_bin = np.digitize(x, x_bins) 
y_bin = np.digitize(y, y_bins) 

x_mu = np.zeros(10) 
y_mu = x_mu.copy() 
err = x_mu.copy() 

for i in range(10): 
    x_mu = np.mean(x[x_bin==i]) 
    y_mu = np.mean(y[y_bin==i]) 
    err = np.std([y[y_bin==i]) 


x_mu[np.isnan(x_mu)] = 0 
y_mu[np.isnan(y_mu)] = 0 
errror[np.isnan(error)] = 0 

plt.errorbar(x_mu, y_mu, err, fmt='o') 

編輯:scipy.polyfit停止抱怨病態的投入......

out = scipy.polyfit(x_mu, y_mu, deg=1, w=error) 
+0

你能展示一個實際的,經過測試的例子嗎?上面的'x'範圍從0到1,但你似乎在0到100的直方圖。 – 2014-09-26 05:47:10

+0

我將編輯示例感謝 – wbg 2014-09-26 06:00:45

+0

+1 Benjamin Bannier修復我的示例代碼幫助我解決了一些愚蠢的問題,現在是polyfit工程。 ..:/ – wbg 2014-09-26 06:15:21

回答

1

一個numpy.polyfit不允許您明確指定的不確定性。相反,您可以使用scipy.optimize.curve_fit,例如

import numpy as np 
import scipy 
import scipy.optimize 

x = np.linspace(0,1, 100) 
y = np.random.rand(100) 

# bin the data 
n, bins = np.histogram(y, 10, [0, 1]) 
xb = bins[:-1] + 0.05 # at bin center; has overflow bin 
yb = n     # just the per-bin counts 
err = sqrt(n)   # from Poisson statistics 
plt.errorbar(xb, yb, err, fmt='ro') 

# fit a polynomial of degree 1, no explicit uncertainty 
a1, b1 = np.polyfit(xb, yb, 1) 
plt.plot(xb, a1*xb + b1, 'b') 

# fit explicitly taking uncertainty into account 
f = lambda x, a, b: a*x + b # function to fit 
# fit with initial guess for parameters [1, 1] 
pars, corr = scipy.optimize.curve_fit(f, xb, yb, [1, 1], err) 
a2, b2 = pars 
plt.plot(xb, a2*xb + b2, 'r') 

enter image description here

要正確地解釋你需要檢查擬合參數的相關矩陣的配合,但超出了技術問題。

+0

我看到了優化......但我認爲'W'arg會起作用......? – wbg 2014-09-26 06:27:35

+0

我喜歡你的例子..它比烹飪書的例子更容易,對於我來說這真是太深夜了... – wbg 2014-09-26 06:33:14

+0

我想問你關於在另一個線程中解釋適合度,如果你感興趣... – wbg 2014-09-26 17:27:38