![](/img/trans.png)
[英]How do I use scipy and matplotlib to fit a reverse sigmoid function
[英]How do we fit a sigmoid function in Python?
出於可重復性的原因,我正在共享我在這里工作的簡單數據集。
為了使我清楚自己在做什么-從第2列開始,我正在讀取當前行並將其與上一行的值進行比較。 如果更大,我會繼續比較。 如果當前值小於上一行的值,我想將當前值(較小)除以上一個值(較大)。 因此,以下是我的源代碼。
import numpy as np
import scipy.stats
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import beta
protocols = {}
types = {"data_v": "data_v.csv"}
for protname, fname in types.items():
col_time,col_window = np.loadtxt(fname,delimiter=',').T
trailing_window = col_window[:-1] # "past" values at a given index
leading_window = col_window[1:] # "current values at a given index
decreasing_inds = np.where(leading_window < trailing_window)[0]
quotient = leading_window[decreasing_inds]/trailing_window[decreasing_inds]
quotient_times = col_time[decreasing_inds]
protocols[protname] = {
"col_time": col_time,
"col_window": col_window,
"quotient_times": quotient_times,
"quotient": quotient,
}
plt.figure(); plt.clf()
plt.plot(quotient_times, quotient, ".", label=protname, color="blue")
plt.ylim(0, 1.0001)
plt.title(protname)
plt.xlabel("quotient_times")
plt.ylabel("quotient")
plt.legend()
plt.show()
sns.distplot(quotient, hist=False, label=protname)
這給出了以下圖表。
從圖上可以看到
quotient_times
小於3和商保持0.5如果quotient_times
大於3。 我還使用以下代碼將其安裝到Beta版本中
xt = plt.xticks()[0]
xmin, xmax = min(xt), max(xt)
lnspc = np.linspace(xmin, xmax, len(quotient))
alpha,beta,loc,scale = stats.beta.fit(quotient)
pdf_beta = stats.beta.pdf(lnspc, alpha, beta,loc, scale)
plt.plot(lnspc, pdf_beta, label="Data-V", color="darkblue", alpha=0.9)
plt.xlabel('$quotient$')
#plt.ylabel(r'$p(x|\alpha,\beta)$')
plt.title('Beta Distribution')
plt.legend(loc="best", frameon=False)
我們如何將quotient
(如上定義)擬合到S型函數中,以繪制類似以下內容的圖?
您想擬合一個sigmoid
或一個邏輯函數 。 這可以通過幾種方式來改變,例如斜率,中點,幅度和偏移。
這是定義該sigmoid
函數並利用scipy.optimize.curve_fit
函數通過調整參數使錯誤最小化的代碼。
from scipy.optimize import curve_fit
def sigmoid (x, A, h, slope, C):
return 1 / (1 + np.exp ((x - h) / slope)) * A + C
# Fits the function sigmoid with the x and y data
# Note, we are using the cumulative sum of your beta distribution!
p, _ = curve_fit(sigmoid, lnspc, pdf_beta.cumsum())
# Plots the data
plt.plot(lnspc, pdf_beta.cumsum(), label='original')
plt.plot(lnspc, sigmoid(lnspc, *p), label='sigmoid fit')
plt.legend()
# Show parameters for the fit
print(p)
這為您提供了以下情節:
和以下參數空間(用於上面使用的功能):
[-1.82910694e+01 4.88870236e-01 6.15103201e-03 1.82895890e+01]
如果要擬合變量quotient_time
和quotient
,則只需更改變量。
...
p, _ = curve_fit(sigmoid, quotient_times, quotient)
...
並繪制:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.