我们如何在Python中使用sigmoid函数?
出于可再现性的原因,我正在共享我正在使用的简单数据集 为了弄清楚我在做什么——从第2列开始,我读取当前行并将其与前一行的值进行比较。如果它更大,我会继续比较。如果当前值小于上一行的值,我想将较小的当前值除以较大的上一行值。因此,下面是我的源代码我们如何在Python中使用sigmoid函数?,python,python-3.x,numpy,scikit-learn,logistic-regression,Python,Python 3.x,Numpy,Scikit Learn,Logistic Regression,出于可再现性的原因,我正在共享我正在使用的简单数据集 为了弄清楚我在做什么——从第2列开始,我读取当前行并将其与前一行的值进行比较。如果它更大,我会继续比较。如果当前值小于上一行的值,我想将较小的当前值除以较大的上一行值。因此,下面是我的源代码 import numpy as np import scipy.stats import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import beta proto
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)
我们如何将上面定义的商拟合到一个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]
如果您想拟合变量商、时间和商,只需更改变量即可
...
p, _ = curve_fit(sigmoid, quotient_times, quotient)
...
并绘制它:
我向您推荐lmfit套餐。在这里,您可以轻松实现自己的fit功能。希望我能正确理解你的问题,我适合做乙状结肠功能?我以前没用过,但你能试试我共享的数据集吗,Richard?谢谢。将数据集装配到sigmoid和使用sigmoid分类器不一样吗?您只需要提取参数。Scikit learn有一个非常容易使用的sigmoid分类器。我在R中做了一些非常类似的事情,如果我分享它会有帮助吗?@MedImage,谢谢你,但我想在Python中使用它。如果你能用Python和我分享的数据分享你的答案,那会很酷,我会把它标记为一个被接受的答案-是的,这正是我所要求的,但你能用我共享的数据集试试吗?@Brown,这是你的数据集!这是贝塔分布的累积和。真的吗?那么你在哪里传递数据的beta拟合呢?我可以要咖啡吗-D@Brown,它是pdf_beta.cumsum命令,pdf_beta是您在示例代码中提供的。现在,我另外提供了商数和商数乘以的拟合,作为您的第一个绘图。希望能有帮助。当数据是如此的不均匀分布时,拟合很可能不会太好。
...
p, _ = curve_fit(sigmoid, quotient_times, quotient)
...