簡體   English   中英

我們如何在Python中擬合S形函數?

[英]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)

這給出了以下圖表。

在此處輸入圖片說明

在此處輸入圖片說明

從圖上可以看到

  • 數據-V具有0.8的商數當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)

這為您提供了以下情節:

比較原始數據和S形擬合

和以下參數空間(用於上面使用的功能):

[-1.82910694e+01  4.88870236e-01  6.15103201e-03  1.82895890e+01]

如果要擬合變量quotient_timequotient ,則只需更改變量。

...
p, _ = curve_fit(sigmoid, quotient_times, quotient)
...

並繪制:

商和S形擬合

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM