草庐IT

python - 使用scipy,numpy,python等进行S型回归

coder 2023-05-24 原文

我有两个变量(x和y)彼此之间具有某种S型关系,并且我需要找到某种预测方程,使我能够在给定任何x值的情况下预测y的值。我的预测方程式需要显示两个变量之间的某种S形关系。因此,我无法解决产生一条线的线性回归方程。我需要看到在两个变量的曲线图的左右两侧都发生了斜率的逐渐曲线变化。

在谷歌搜索曲线回归和python之后,我开始使用numpy.polyfit,但这给了我可怕的结果,如果您运行下面的代码,您可以看到。 谁能告诉我如何重新编写以下代码以获得所需的S型回归方程式?

如果运行下面的代码,则可以看到它具有向下的抛物线,这与变量之间的关系不一样。相反,我的两个变量之间应该有更多的S型关系,但与下面代码中使用的数据紧密匹配。以下代码中的数据是来自大型样本研究的数据,因此它们具有比其五个数据点所暗示的更多的统计能力。我没有来自大样本研究的实际数据,但确实有以下均值及其标准偏差(未显示)。我宁愿只用下面列出的均值数据绘制一个简单的函数,但是如果复杂度可以提供实质性的改进,则代码可能会变得更加复杂。

如何更改代码以显示最合适的S型函数,最好使用scipy,numpy和python? 这是我的代码的当前版本,需要修复:

import numpy as np
import matplotlib.pyplot as plt

# Create numpy data arrays
x = np.array([821,576,473,377,326])
y = np.array([255,235,208,166,157])

# Use polyfit and poly1d to create the regression equation
z = np.polyfit(x, y, 3)
p = np.poly1d(z)
xp = np.linspace(100, 1600, 1500)
pxp=p(xp)

# Plot the results
plt.plot(x, y, '.', xp, pxp, '-')
plt.ylim(140,310)
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()

编辑如下:(重新构建问题)

您的回应及其速度令人印象深刻。谢谢你
但是,为了产生更有效的结果,我需要重新构造数据值。这意味着将x值重铸为最大x值的百分比,同时将y值重铸为原始数据中的x值的百分比。我尝试使用您的代码来完成此操作,并提出了以下内容:
import numpy as np 
import matplotlib.pyplot as plt 
import scipy.optimize 

# Create numpy data arrays 
'''
# Comment out original data
#x = np.array([821,576,473,377,326]) 
#y = np.array([255,235,208,166,157]) 
'''

# Re-calculate x values as a percentage of the first (maximum)
# original x value above
x = np.array([1.000,0.702,0.576,0.459,0.397])

# Recalculate y values as a percentage of their respective x values
# from original data above
y = np.array([0.311,0.408,0.440,0.440,0.482])

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

def residuals(p,x,y): 
    return y - sigmoid(p,x) 

p_guess=(600,200,100,0.01) 
(p,  
 cov,  
 infodict,  
 mesg,  
 ier)=scipy.optimize.leastsq(residuals,p_guess,args=(x,y),full_output=1,warning=True)  

'''
# comment out original xp to allow for better scaling of
# new values
#xp = np.linspace(100, 1600, 1500) 
'''

xp = np.linspace(0, 1.1, 1100) 
pxp=sigmoid(p,xp) 

x0,y0,c,k=p 
print('''\ 
x0 = {x0}
y0 = {y0}
c = {c}
k = {k}
'''.format(x0=x0,y0=y0,c=c,k=k)) 

# Plot the results 
plt.plot(x, y, '.', xp, pxp, '-') 
plt.ylim(0,1) 
plt.xlabel('x') 
plt.ylabel('y') 
plt.grid(True) 
plt.show()

您能告诉我如何修改此修订后的代码吗?
注意:通过重新广播数据,我实际上已将2d(x,y)的S型曲线沿z轴旋转了180度。同样,1.000并不是x值的最大值。取而代之的是,1.000是最大测试条件下不同测试参与者的值范围的平均值。

下面的第二个编辑:

谢谢你,ubuntu。我仔细阅读了您的代码,并在scipy文档中查找了代码的各个方面。由于您的名字似乎是作为scipy文档的作者而冒出来的,所以我希望您可以回答以下问题:

1.)Minimumsq()是否会调用残差(),然后该残差返回输入的y向量和sigmoid()函数返回的y向量之间的差?如果是这样,它如何解决输入y矢量和sigmoid()函数返回的y矢量的长度差异?

2)只要我通过残差函数访问该数学方程,就可以调用任何数学方程的minimumsq(),而残差函数又会调用该数学函数。这是真的?

3.)另外,我注意到p_guess与p具有相同数量的元素。这是否意味着p_guess的四个元素分别分别与x0,y0,c和k返回的值相对应?

4.)作为参数发送给residuals()和sigmoid()函数的p是否与plessingsq()输出的p相同,并且lowestsq()函数在返回p之前在内部使用该p?

5.)只要p中的元素数量等于p_guess中的元素数量,p和p_guess可以具有任意数量的元素,取决于用作模型的方程的复杂性?

最佳答案

使用scipy.optimize.leastsq:

import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize

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

def residuals(p,x,y):
    return y - sigmoid(p,x)

def resize(arr,lower=0.0,upper=1.0):
    arr=arr.copy()
    if lower>upper: lower,upper=upper,lower
    arr -= arr.min()
    arr *= (upper-lower)/arr.max()
    arr += lower
    return arr

# raw data
x = np.array([821,576,473,377,326],dtype='float')
y = np.array([255,235,208,166,157],dtype='float')

x=resize(-x,lower=0.3)
y=resize(y,lower=0.3)
print(x)
print(y)
p_guess=(np.median(x),np.median(y),1.0,1.0)
p, cov, infodict, mesg, ier = scipy.optimize.leastsq(
    residuals,p_guess,args=(x,y),full_output=1,warning=True)  

x0,y0,c,k=p
print('''\
x0 = {x0}
y0 = {y0}
c = {c}
k = {k}
'''.format(x0=x0,y0=y0,c=c,k=k))

xp = np.linspace(0, 1.1, 1500)
pxp=sigmoid(p,xp)

# Plot the results
plt.plot(x, y, '.', xp, pxp, '-')
plt.xlabel('x')
plt.ylabel('y',rotation='horizontal') 
plt.grid(True)
plt.show()

产量

具有S型参数
x0 = 0.826964424481
y0 = 0.151506745435
c = 0.848564826467
k = -9.54442292022

请注意,对于较新版本的scipy(例如0.9),还有scipy.optimize.curve_fit函数,它比leastsq易于使用。有关使用curve_fit拟合Sigmoids的相关讨论,可以找到here

编辑:添加了resize函数,以便可以重新缩放原始数据并移动其以适合任何所需的边界框。

"your name seems to pop up as a writer of the scipy documentation"



免责声明:我不是scipy文档的作者。我只是一个用户,而且还是一个新手。我对leastsq的了解大部分来自阅读Travis Oliphant撰写的this tutorial

1.) Does leastsq() call residuals(), which then returns the difference between the input y-vector and the y-vector returned by the sigmoid() function?



是的!确切地。

If so, how does it account for the difference in the lengths of the input y-vector and the y-vector returned by the sigmoid() function?



长度是相同的:
In [138]: x
Out[138]: array([821, 576, 473, 377, 326])

In [139]: y
Out[139]: array([255, 235, 208, 166, 157])

In [140]: p=(600,200,100,0.01)

In [141]: sigmoid(p,x)
Out[141]: 
array([ 290.11439268,  244.02863507,  221.92572521,  209.7088641 ,
        206.06539033])

关于Numpy的妙处之一是,它允许您编写在整个数组上运行的“向量”方程。
y = c / (1 + np.exp(-k*(x-x0))) + y0

看起来好像可以在浮点数上工作(实际上是这样),但是如果将x设置为numpy数组,并将ckx0y0设置为浮点数,则该等式会将y定义为与x形状相同的numpy数组。因此,sigmoid(p,x)返回一个numpy数组。在numpybook中有一个更完整的解释(对于numpy的认真用户必读)。

2.) It looks like I can call leastsq() for any math equation, as long as I access that math equation through a residuals function, which in turn calls the math function. Is this true?



真的。 leastsq尝试最小化残差(差)的平方和。它搜索参数空间(p的所有可能值),以寻找使该平方和最小的p。发送到xyresiduals是您的原始数据值。它们是固定的。他们没有改变。 p尝试最小化的是leastsq s(Sigmoid函数中的参数)。

3.) Also, I notice that p_guess has the same number of elements as p. Does this mean that the four elements of p_guess correspond in order, respectively, with the values returned by x0,y0,c, and k?



正是如此!像牛顿的方法一样,leastsq需要对p进行初始猜测。您将其作为p_guess提供。当你看到
scipy.optimize.leastsq(residuals,p_guess,args=(x,y))

您可以认为,作为minimumsq算法(实际上是Levenburg-Marquardt算法)的一部分,第一次通过,minimumsq调用residuals(p_guess,x,y)
注意之间的视觉相似性
(residuals,p_guess,args=(x,y))


residuals(p_guess,x,y)

它可以帮助您记住leastsq参数的顺序和含义。
residualssigmoid一样,返回一个numpy数组。将数组中的值平方,然后求和。这是要击败的数字。然后随着p_guess寻找一组将leastsq最小化的值,residuals(p_guess,x,y)随之变化。

4.) Is the p that is sent as an argument to the residuals() and sigmoid() functions the same p that will be output by leastsq(), and the leastsq() function is using that p internally before returning it?



好吧,不完全是。众所周知,随着p_guess搜索最小化leastsqp值,residuals(p,x,y)有所不同。发送到pp_guess(er,leastsq)具有与p返回的leastsq相同的形状。显然,除非您是个猜测家,否则值应该是不同的:)

5.) Can p and p_guess have any number of elements, depending on the complexity of the equation being used as a model, as long as the number of elements in p is equal to the number of elements in p_guess?



是的。我还没有对leastsq进行大量参数的压力测试,但这是一个非常强大的工具。

关于python - 使用scipy,numpy,python等进行S型回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4308168/

有关python - 使用scipy,numpy,python等进行S型回归的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  7. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  8. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  9. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  10. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

随机推荐