我正在尝试将分段定义的函数与Python中的数据集相匹配。我已经找了好一阵子了,但我还没有找到答案是否可能。
要了解我想做什么,请看下面的示例(它对我不起作用)。在这里,我试图将移位绝对值函数(f(x)=| x-p |)拟合到一个以p为拟合参数的数据集。
import scipy.optimize as so
import numpy as np
def fitfunc(x,p):
if x>p:
return x-p
else:
return -(x-p)
fitfunc = np.vectorize(fitfunc) #vectorize so you can use func with array
x=np.arange(1,10)
y=fitfunc(x,6)+0.1*np.random.randn(len(x))
popt, pcov = so.curve_fit(fitfunc, x, y) #fitting routine that gives error
有没有用Python实现的方法?
在R中执行此操作的方法是:
# Fit of a absolute value function f(x)=|x-p|
f.lr <- function(x,p) {
ifelse(x>p, x-p,-(x-p))
}
x <- seq(0,10) #
y <- f.lr(x,6) + rnorm (length(x),0,2)
plot(y ~ x)
fit.lr <- nls(y ~ f.lr(x,p), start = list(p = 0), trace = T, control = list(warnOnly = T,minFactor = 1/2048))
summary(fit.lr)
coefficients(fit.lr)
p.fit <- coefficients(fit.lr)["p"]
x_fine <- seq(0,10,length.out=1000)
lines(x_fine,f.lr(x_fine,p.fit),type='l',col='red')
lines(x,f.lr(x,6),type='l',col='blue')
经过更多的研究,我找到了一种方法。在这个解决方案中,我不喜欢必须自己定义错误函数的事实。此外,我不确定为什么它必须在这种兰达风格。因此,任何形式的建议或更复杂的解决方案都是非常受欢迎的。
import scipy.optimize as so
import numpy as np
import matplotlib.pyplot as plt
def fitfunc(p,x): return x - p if x > p else p - x
def array_fitfunc(p,x):
y = np.zeros(x.shape)
for i in range(len(y)):
y[i]=fitfunc(x[i],p)
return y
errfunc = lambda p, x, y: array_fitfunc(p, x) - y # Distance to the target function
x=np.arange(1,10)
x_fine=np.arange(1,10,0.1)
y=array_fitfunc(6,x)+1*np.random.randn(len(x)) #data with noise
p1, success = so.leastsq(errfunc, -100, args=(x, y), epsfcn=1.) # -100 is the initial value for p; epsfcn sets the step width
plt.plot(x,y,'o') # fit data
plt.plot(x_fine,array_fitfunc(6,x_fine),'r-') #original function
plt.plot(x_fine,array_fitfunc(p1[0],x_fine),'b-') #fitted version
plt.show()
你就不能把fitfunc换成
然后产生类似
使用switch函数和/或构建块(如
where
)替换分支,应该可以扩展到更复杂的表达式,而无需调用vectorize
。[PS:最小二乘法示例中的
errfunc
不需要是lambda。你可以写相反,如果你喜欢的话。】
为了完成这项工作,我将分享我自己对这个问题的最终解决方案。为了接近我最初的问题,您只需自己定义向量化函数,而不使用
np.vectorize
。输出:
相关问题 更多 >
编程相关推荐