如何使用numpy拟合曲线后找到50%的点 [英] how to find 50% point after curve fitting using numpy

查看:180
本文介绍了如何使用numpy拟合曲线后找到50%的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中使用numpy将数据拟合为S形曲线.将数据拟合到曲线后,如何在曲线的y = 50%点处找到X的值

I have used numpy in python to fit my data to a sigmoidal curve. How can I find the vaue for X at y=50% point in the curve after the data is fit to the curve

enter code here`import numpy as np
enter code here`import pylab
from scipy.optimize import curve_fit

def sigmoid(x, x0, k):
   y = 1 / (1 + np.exp(-k*(x-x0)))
   return y

xdata = np.array([0.0,   1.0,  3.0, 4.3, 7.0,   8.0,   8.5, 10.0, 12.0])
ydata = np.array([0.01, 0.02, 0.04, 0.11, 0.43,  0.7, 0.89, 0.95, 0.99])

popt, pcov = curve_fit(sigmoid, xdata, ydata)
print popt

x = np.linspace(-1, 15, 50)
y = sigmoid(x, *popt)

pylab.plot(xdata, ydata, 'o', label='data')
pylab.plot(x,y, label='fit')
pylab.ylim(0, 1.05)
pylab.legend(loc='best')
pylab.show()

推荐答案

您只需解决为y(x) = 0.50找到的功能.您可以使用 scipy的寻根工具之一. ,尽管这些只能求解零,所以您需要为函数提供一个偏移量:

You just need to solve the function you found for y(x) = 0.50. You can use one of the root finding tools of scipy, though these only solve for zero, so you need to give your function an offset:

def sigmoid(x, x0, k, y0=0):
   y = 1 / (1 + np.exp(-k*(x-x0))) + y0
   return y

然后只需调用选择的寻根方法即可.

Then it's just a matter of calling the root finding method of choice:

from scipy.optimize import brentq

a = np.min(xdata)
b = np.max(xdata)
x0, k = popt
y0 = -0.50

solution = brentq(sigmoid, a, b, args=(x0, k, y0))  # = 7.142


除了您的评论:

我上面的代码使用与您的代码一起计算的原始popt.如果使用更新的sigmoid函数(带有偏移量)进行曲线拟合,则popt还将包含y0的拟合参数.

My code above uses the original popt that was calculated with your code. If you do the curve fitting with the updated sigmoid function (with the offset), popt will also contain a fitted parameter for y0.

可能您不想要此..您需要适合y0=0的曲线.这可以通过仅提供两个值来提供对curve_fit的猜测.这样,将使用Sigmoid函数的y0的默认值:

Probably you don't want this.. you'll want the curve fitted for y0=0. This can be done by supplying a guess for the curve_fit with only two values. This way the default value for y0 of the sigmoid function will be used:

popt, pcov = curve_fit(sigmoid, xdata, ydata, p0 = (1,1))

或者,只需声明两个单独的Sigmmoid函数,一个带有偏移量,另一个不带偏移量.

Alternatively, just declare two seperate sigmmoid functions, one with the offset and one without it.

这篇关于如何使用numpy拟合曲线后找到50%的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆