在curve_fit(scipy)期间将边界应用于特定变量会导致错误 [英] Applying bounds to specific variable during curve_fit (scipy) leads to an error
问题描述
我正在尝试在曲线拟合过程中将边界应用于某些参数,但尝试这样做时会收到以下错误消息:
I am trying to apply bounds onto some of the parameters during curve fitting but I'm getting the following error message when I tried to do so:
ValueError:太多的值无法解包
绑定命令中的每个2元组不是对应于x0,k,失效,sigmoidscaled中的猜测在我的情况下分别起作用(即也对应于p0)?
Doesn't each 2-tuple in the bound command corresponds to x0, k, lapse, guess in the sigmoidscaled function in my case respectively (Ie. corresponding to p0 too)?
然后我尝试玩耍,希望通过将绑定命令简化为以下内容来摆脱太多的值,以试图弄清它的工作原理:
I then tried playing around in hopes of trying to figure out how it works by reducing the bound command to the following to rid the 'too many values':
bounds =((-np.inf,np.inf),(0,1))
bounds=((-np.inf,np.inf), (0,1))
然后我得到以下错误消息:
Then I get the error message of:
ValueError:边界和 x0
。
我在这里怎么了?
import pylab
from scipy.optimize import curve_fit
from matplotlib.pyplot import *
n = 20 #20 trials
ydata = [0/n, 9.0/n, 9.0/n, 14.0/n, 17.0/n] #Divided by n to fit to a plot of y =1
xdata = np.array([ 1.0, 2.0, 3.0, 4.0, 5.0])
#The scaled sigmoid function
def sigmoidscaled(x, x0, k, lapse, guess):
F = (1 + np.exp(-k*(x-x0)))
z = guess + (1-guess-lapse)/F
return z
p0=[1,1,0,0]
popt, pcov = curve_fit(sigmoidscaled, xdata, ydata, p0, bounds=((-np.inf,np.inf), (-np.inf,np.inf), (0,1), (0,1))
#Start and End of x-axis, in spaces of n. The higher the n, the smoother the curve.
x = np.linspace(1,5,20)
#The sigmoid values along the y-axis, generated in relation to the x values and the 50% point.
y = sigmoidscaled(x, *popt)
pylab.plot(xdata, ydata, 'o', label='Psychometric Raw', color = 'blue')
pylab.plot(x,y, label='Psychometric Fit', color = 'blue')
#y axis range.
pylab.ylim(0, 1)
#Replace x-axis numbers as labels and y-axis numbers as percentage
xticks([1., 2., 3., 4., 5.], ['C1','CN2','N3','CN4','S5'])
yticks([0.0, 0.2, 0.4, 0.6, 0.8, 1.0], ['0%','20%','40%','60%','80%','100%'])
pylab.legend(loc='best')
xlabel('Conditions')
ylabel('% perceived more sin like')
pylab.show()
推荐答案
问题行是:
popt, pcov = curve_fit(sigmoidscaled, xdata, ydata, p0, bounds=((-np.inf,np.inf), (-np.inf,np.inf), (0,1), (0,1))
来自文档,边界
必须是2个元数组,例如数组。因此,而不是指定每个点的上下限,您需要在第一个类似数组的数组中指定每个点的下限,然后是第二个类似数组的数组,如下所示:
From the documentation, bounds
needs to be a 2-tuple of array likes. So instead of specifying the lower and upper bound of each point, you need to specify the lower bound of each point in the first array-like followed by the upper bound of each point in the second array-like, like this:
popt, pcov = curve_fit(sigmoidscaled, xdata, ydata, p0, bounds=((-np.inf, -np.inf, 0, 0), (np.inf, np.inf, 1, 1)))
此更改后,剧情就弹出了!
After this change, the plot popped right up!
这篇关于在curve_fit(scipy)期间将边界应用于特定变量会导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!