我在 python 中有以下信息(数据框)
product baskets scaling_factor
12345 475 95.5
12345 108 57.7
12345 2 1.4
12345 38 21.9
12345 320 88.8
我想运行以下非线性回归并估计参数。
a ,b 和 c
我想要拟合的方程:
scaling_factor = a - (b*np.exp(c*baskets))
在sas中我们通常运行以下模型:(使用高斯牛顿法)
proc nlin data=scaling_factors;
parms a=100 b=100 c=-0.09;
model scaling_factor = a - (b * (exp(c*baskets)));
output out=scaling_equation_parms
parms=a b c;
在 Python 中是否有类似的方法使用非线性回归来估计参数,我如何在 Python 中查看绘图。
最佳答案
对于此类问题,我总是使用 scipy.optimize.minimize
用我自己的最小二乘函数。优化算法不能很好地处理各种输入之间的巨大差异,因此最好缩放函数中的参数,以便暴露给 scipy 的参数都在 1 的数量级,就像我在下面所做的那样。
import numpy as np
baskets = np.array([475, 108, 2, 38, 320])
scaling_factor = np.array([95.5, 57.7, 1.4, 21.9, 88.8])
def lsq(arg):
a = arg[0]*100
b = arg[1]*100
c = arg[2]*0.1
now = a - (b*np.exp(c * baskets)) - scaling_factor
return np.sum(now**2)
guesses = [1, 1, -0.9]
res = scipy.optimize.minimize(lsq, guesses)
print(res.message)
# 'Optimization terminated successfully.'
print(res.x)
# [ 0.97336709 0.98685365 -0.07998282]
print([lsq(guesses), lsq(res.x)])
# [7761.0093358076601, 13.055053196410928]
当然,与所有最小化问题一样,使用良好的初始猜测很重要,因为所有算法都可能陷入局部最小值。可以使用method
关键字改变优化方法;一些可能性是
- “内尔德米德”
- “鲍威尔”
- ‘CG’
- 'BFGS'
- “牛顿-CG”
根据 the documentation 默认为 BFGS .
关于python - 如何在 python 中运行非线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39895369/