如何在Python中适合sigmoid函数?

2024-04-25 22:02:29 发布

您现在位置:Python中文网/ 问答频道 /正文

出于可重复性的原因,我共享我正在工作的简单数据集here。在

为了弄清楚我在做什么-从第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)

这给出了以下曲线图。在

enter image description here

enter image description here

从图中我们可以看出

  • quotient_times小于3时,Data-V的商为0.8,如果quotient_times为 大于3。在

我还使用下面的代码将其安装到beta发行版中

^{pr2}$

enter image description here

我们如何将quotient(上面定义的)放入一个sigmoid函数中来绘制如下所示的图?在

enter image description here


Tags: importtimeasnppltcolscipywindow
1条回答
网友
1楼 · 发布于 2024-04-25 22:02:29

你想要一个sigmoid,或者实际上是一个logistic function。这可以通过多种方式改变,例如坡度、中点、幅值和偏移量。在

下面的代码定义了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)

这将给出以下曲线图:

comparison original data and sigmoid fit

以及以下参数空间(对于上述使用的函数):

^{pr2}$

如果您想匹配变量quotient_timequotient,只需更改变量即可。在

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

然后把它画出来:

quotient and sigmoid fit

相关问题 更多 >