nonlinear least-square with Python statsmodels

丶灬走出姿态 提交于 2019-12-12 16:27:17

问题


Within the Python library statsmodels, is it possible to perform a nonlinear least-square fitting with nonlinear parameter? In other words, I would like to find the best fit (in term of least-square) for p in the following stat model:

y = ln(p)*x^2 + p

Let's assume I have a set of observation x and y, I can use the function scipy.optimize.leastsq to find the best fit. Here is an example:

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

def fitFunc(p,x):
    return np.log(p[0])*x**2 + p[0]
def errFunc(p,x,y):
    return fitFunc(p,x)-y

# create x, y and y_true
nSample = 100
x = np.linspace(-10,10,nSample)
y_true = fitFunc([1.2],x)
err = np.random.normal(scale=7.0,size=nSample)
y = y_true+err

# find optimal p with least-square and plot it
p1, success = spopt.leastsq(errFunc, [2], args=(x,y))

plt.figure()
plt.scatter(x,y,label='obsevation')
plt.plot(x,y_true,label='true y')
plt.plot(x,fitFunc(p1,x),label='model')
plt.grid(True)
plt.legend()

Is it possible to perform such type of analysis with the library statsmodels?

来源:https://stackoverflow.com/questions/42005881/nonlinear-least-square-with-python-statsmodels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!